simd opti
This commit is contained in:
194
src/benchmark.rs
194
src/benchmark.rs
@ -3,7 +3,8 @@ use crate::code::{CodeTopology, GenerationMethod, LdpcCode, LdpcParams};
|
||||
use crate::decoder::{build_decoder, DecoderConfig, DecoderMethod};
|
||||
use crate::encoder::{build_encoder, EncodingMethod};
|
||||
use crate::Result as LdpcResult;
|
||||
use rand::{Rng, SeedableRng};
|
||||
use rand::Rng;
|
||||
use rayon::prelude::*;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
@ -37,13 +38,10 @@ pub fn run_simulation(mut code: LdpcCode) -> LdpcResult<()> {
|
||||
}
|
||||
);
|
||||
|
||||
println!("\n[*] Étape 2 : Extraction de G^T et Instanciation de l'Encodeur");
|
||||
println!("\n[*] Étape 2 : Instanciation de l'Encodeur (SIMD Bit-Packing)");
|
||||
let start_enc = Instant::now();
|
||||
let encoder = build_encoder(&mut code, EncodingMethod::Systematic)?;
|
||||
println!(
|
||||
" - Forme systématique calculée en {:.2?}",
|
||||
start_enc.elapsed()
|
||||
);
|
||||
println!(" - Encodeur prêt en {:.2?}", start_enc.elapsed());
|
||||
|
||||
println!("\n[*] Étape 3 : Instanciation des Décodeurs sur Graphe");
|
||||
let config = DecoderConfig {
|
||||
@ -62,12 +60,11 @@ pub fn run_simulation(mut code: LdpcCode) -> LdpcResult<()> {
|
||||
let dec_bf = build_decoder(&code, DecoderMethod::BitFlipping, config.clone());
|
||||
println!(" - Moteurs prêts : Sum-Product, Min-Sum (α=0.8), Bit-Flipping");
|
||||
|
||||
let snr_range = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0];
|
||||
let n_trials = 100;
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
|
||||
let snr_range = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 3.0, 3.5, 4.0];
|
||||
let n_trials = 1000;
|
||||
|
||||
println!(
|
||||
"\n[*] Étape 4 : Simulation sur Canal AWGN ({} trames par SNR)",
|
||||
"\n[*] Étape 4 : Simulation sur Canal AWGN ({} trames par SNR, Multi-threadé)",
|
||||
n_trials
|
||||
);
|
||||
println!("{:-<115}", "");
|
||||
@ -86,6 +83,67 @@ pub fn run_simulation(mut code: LdpcCode) -> LdpcResult<()> {
|
||||
|
||||
for &snr in &snr_range {
|
||||
let channel = AwgnChannel::new(snr, code.rate())?;
|
||||
|
||||
let results: Vec<_> = (0..n_trials)
|
||||
.into_par_iter()
|
||||
.map(|_| {
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
let message: Vec<u8> = (0..code.k()).map(|_| rng.gen::<u8>() & 1).collect();
|
||||
let codeword = encoder.encode(&message).unwrap();
|
||||
let received_llr = channel.transmit(&codeword, &mut rng);
|
||||
|
||||
let mut t_sp_f = 0;
|
||||
let mut t_sp_b = 0;
|
||||
let mut t_ms_f = 0;
|
||||
let mut t_ms_b = 0;
|
||||
let mut t_bf_f = 0;
|
||||
let mut t_bf_b = 0;
|
||||
|
||||
// SP
|
||||
let res_sp = dec_sp.decode(&received_llr);
|
||||
if let Some(decoded) = res_sp.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
t_sp_f = 1;
|
||||
t_sp_b = errs;
|
||||
}
|
||||
} else {
|
||||
t_sp_f = 1;
|
||||
t_sp_b = code.n();
|
||||
}
|
||||
|
||||
// MS
|
||||
let res_ms = dec_ms.decode(&received_llr);
|
||||
if let Some(decoded) = res_ms.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
t_ms_f = 1;
|
||||
t_ms_b = errs;
|
||||
}
|
||||
} else {
|
||||
t_ms_f = 1;
|
||||
t_ms_b = code.n();
|
||||
}
|
||||
|
||||
// BF
|
||||
let res_bf = dec_bf.decode(&received_llr);
|
||||
if let Some(decoded) = res_bf.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
t_bf_f = 1;
|
||||
t_bf_b = errs;
|
||||
}
|
||||
} else {
|
||||
t_bf_f = 1;
|
||||
t_bf_b = code.n();
|
||||
}
|
||||
|
||||
(t_sp_f, t_sp_b, t_ms_f, t_ms_b, t_bf_f, t_bf_b)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Agrégation
|
||||
let mut err_sp_frames = 0;
|
||||
let mut err_sp_bits = 0;
|
||||
let mut err_ms_frames = 0;
|
||||
@ -93,49 +151,13 @@ pub fn run_simulation(mut code: LdpcCode) -> LdpcResult<()> {
|
||||
let mut err_bf_frames = 0;
|
||||
let mut err_bf_bits = 0;
|
||||
|
||||
for _ in 0..n_trials {
|
||||
let message: Vec<u8> = (0..code.k()).map(|_| rng.gen::<u8>() & 1).collect();
|
||||
let codeword = encoder.encode(&message)?;
|
||||
let received_llr = channel.transmit(&codeword, &mut rng);
|
||||
|
||||
// SP
|
||||
let res_sp = dec_sp.decode(&received_llr);
|
||||
if let Some(decoded) = res_sp.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
err_sp_frames += 1;
|
||||
err_sp_bits += errs;
|
||||
}
|
||||
} else {
|
||||
err_sp_frames += 1;
|
||||
err_sp_bits += code.n();
|
||||
}
|
||||
|
||||
// MS
|
||||
let res_ms = dec_ms.decode(&received_llr);
|
||||
if let Some(decoded) = res_ms.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
err_ms_frames += 1;
|
||||
err_ms_bits += errs;
|
||||
}
|
||||
} else {
|
||||
err_ms_frames += 1;
|
||||
err_ms_bits += code.n();
|
||||
}
|
||||
|
||||
// BF
|
||||
let res_bf = dec_bf.decode(&received_llr);
|
||||
if let Some(decoded) = res_bf.codeword() {
|
||||
let errs = count_bit_errors(&codeword, decoded);
|
||||
if errs > 0 {
|
||||
err_bf_frames += 1;
|
||||
err_bf_bits += errs;
|
||||
}
|
||||
} else {
|
||||
err_bf_frames += 1;
|
||||
err_bf_bits += code.n();
|
||||
}
|
||||
for res in results {
|
||||
err_sp_frames += res.0;
|
||||
err_sp_bits += res.1;
|
||||
err_ms_frames += res.2;
|
||||
err_ms_bits += res.3;
|
||||
err_bf_frames += res.4;
|
||||
err_bf_bits += res.5;
|
||||
}
|
||||
|
||||
let total_bits = (n_trials * code.n()) as f64;
|
||||
@ -162,39 +184,39 @@ fn count_bit_errors(transmitted: &[u8], decoded: &[u8]) -> usize {
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn generate_valid_code(
|
||||
n: usize,
|
||||
k: usize,
|
||||
wc: usize,
|
||||
wr: usize,
|
||||
generation_method: GenerationMethod,
|
||||
) -> LdpcResult<LdpcCode> {
|
||||
let mut attempt = 0;
|
||||
let start_gen = Instant::now();
|
||||
loop {
|
||||
attempt += 1;
|
||||
let params = LdpcParams {
|
||||
n,
|
||||
k,
|
||||
topology: CodeTopology::Regular { wc, wr },
|
||||
generation: generation_method.clone(),
|
||||
seed: Some(rand::random()),
|
||||
};
|
||||
|
||||
if let Ok(mut code) = LdpcCode::new(params) {
|
||||
if code.compute_systematic_form().is_ok() {
|
||||
if attempt > 1 {
|
||||
println!(
|
||||
" -> Matrice inversible obtenue après {} tentatives.",
|
||||
attempt
|
||||
);
|
||||
}
|
||||
println!(" - Génération : Terminée en {:.2?}", start_gen.elapsed());
|
||||
return Ok(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// pub fn generate_valid_code(
|
||||
// n: usize,
|
||||
// k: usize,
|
||||
// wc: usize,
|
||||
// wr: usize,
|
||||
// generation_method: GenerationMethod,
|
||||
// ) -> LdpcResult<LdpcCode> {
|
||||
// let mut attempt = 0;
|
||||
// let start_gen = Instant::now();
|
||||
// loop {
|
||||
// attempt += 1;
|
||||
// let params = LdpcParams {
|
||||
// n,
|
||||
// k,
|
||||
// topology: CodeTopology::Regular { wc, wr },
|
||||
// generation: generation_method.clone(),
|
||||
// seed: Some(rand::random()),
|
||||
// };
|
||||
//
|
||||
// if let Ok(mut code) = LdpcCode::new(params) {
|
||||
// if code.compute_systematic_form().is_ok() {
|
||||
// if attempt > 1 {
|
||||
// println!(
|
||||
// " -> Matrice inversible obtenue après {} tentatives.",
|
||||
// attempt
|
||||
// );
|
||||
// }
|
||||
// println!(" - Génération : Terminée en {:.2?}", start_gen.elapsed());
|
||||
// return Ok(code);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
pub fn get_or_generate_cached_code(
|
||||
n: usize,
|
||||
|
||||
228
src/benchmark2.rs
Normal file
228
src/benchmark2.rs
Normal file
@ -0,0 +1,228 @@
|
||||
use crate::benchmark::get_or_generate_cached_code;
|
||||
use crate::channel::{AwgnChannel, Channel};
|
||||
use crate::code::GenerationMethod;
|
||||
use crate::decoder::{build_decoder, DecoderConfig, DecoderMethod};
|
||||
use crate::encoder::{build_encoder, EncodingMethod};
|
||||
use crate::Result as LdpcResult;
|
||||
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use rand::Rng;
|
||||
use rayon::prelude::*;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CodeScenario {
|
||||
pub n: usize,
|
||||
pub k: usize,
|
||||
pub wc: usize,
|
||||
pub wr: usize,
|
||||
pub method: GenerationMethod,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub struct CampaignConfig {
|
||||
pub scenarios: Vec<CodeScenario>,
|
||||
pub snr_range: Vec<f64>,
|
||||
pub n_trials: usize,
|
||||
pub max_iterations: usize,
|
||||
pub output_csv: String,
|
||||
pub export_graph: bool,
|
||||
}
|
||||
|
||||
pub fn run_massive_campaign(config: CampaignConfig) -> LdpcResult<()> {
|
||||
println!("TEST)");
|
||||
println!("Fichier de sortie : {}", config.output_csv);
|
||||
println!("Scenarios a tester: {}", config.scenarios.len());
|
||||
println!("SNRs par scenario : {}", config.snr_range.len());
|
||||
println!("Trames par point : {}\n", config.n_trials);
|
||||
|
||||
let file_exists = std::path::Path::new(&config.output_csv).exists();
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&config.output_csv)
|
||||
.expect("Impossible d'ouvrir le fichier CSV");
|
||||
|
||||
if !file_exists {
|
||||
writeln!(
|
||||
file,
|
||||
"Scenario,N,K,Rate,Wc,Wr,Method,Girth,Density_pct,SNR_dB,Capacity,Decoder,FER_pct,BER_pct,Frames,Time_ms"
|
||||
).unwrap();
|
||||
}
|
||||
|
||||
let total_steps = (config.scenarios.len() * config.snr_range.len()) as u64;
|
||||
let pb = ProgressBar::new(total_steps);
|
||||
pb.set_style(
|
||||
ProgressStyle::default_bar()
|
||||
.template("{spinner:.cyan} [{elapsed_precise}] [{bar:40.green/blue}] {pos}/{len} ({eta}) - {msg}")
|
||||
.unwrap()
|
||||
.progress_chars("=>-"),
|
||||
);
|
||||
|
||||
for scenario in config.scenarios {
|
||||
pb.set_message(format!("Generation Matrice: {}", scenario.name));
|
||||
|
||||
let mut code = get_or_generate_cached_code(
|
||||
scenario.n,
|
||||
scenario.k,
|
||||
scenario.wc,
|
||||
scenario.wr,
|
||||
scenario.method.clone(),
|
||||
)?;
|
||||
|
||||
if config.export_graph {
|
||||
let dot_filename = format!("{}_tanner.dot", scenario.name);
|
||||
let mut dot_file = std::fs::File::create(&dot_filename).expect("Erreur creation .dot");
|
||||
|
||||
writeln!(dot_file, "graph TannerGraph {{").unwrap();
|
||||
writeln!(dot_file, " rankdir=TB;").unwrap();
|
||||
writeln!(dot_file, " nodesep=0.5;").unwrap();
|
||||
writeln!(dot_file, " ranksep=2.0;").unwrap();
|
||||
|
||||
writeln!(dot_file, " node [style=filled, fontname=\"Arial\"];").unwrap();
|
||||
|
||||
writeln!(dot_file, " {{ rank=same;").unwrap();
|
||||
for v in 0..code.n() {
|
||||
writeln!(
|
||||
dot_file,
|
||||
" v{} [shape=circle, fillcolor=lightblue, label=\"v{}\"];",
|
||||
v, v
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
writeln!(dot_file, " }}").unwrap();
|
||||
|
||||
writeln!(dot_file, " {{ rank=same;").unwrap();
|
||||
for c in 0..code.m() {
|
||||
writeln!(
|
||||
dot_file,
|
||||
" c{} [shape=square, fillcolor=lightcoral, label=\"c{}\"];",
|
||||
c, c
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
writeln!(dot_file, " }}").unwrap();
|
||||
|
||||
for c in 0..code.m() {
|
||||
for &v in code.graph.chk_neighbors(c) {
|
||||
writeln!(dot_file, " v{} -- c{};", v, c).unwrap();
|
||||
}
|
||||
}
|
||||
writeln!(dot_file, "}}").unwrap();
|
||||
}
|
||||
|
||||
let rate = code.rate();
|
||||
let girth = code.girth();
|
||||
let density = code.h.density() * 100.0;
|
||||
let method_str = match scenario.method {
|
||||
GenerationMethod::Gallager => "Gallager",
|
||||
GenerationMethod::MacKayNeal { .. } => "MacKayNeal",
|
||||
};
|
||||
|
||||
pb.set_message(format!("Initialisation DSP: {}", scenario.name));
|
||||
let encoder = build_encoder(&mut code, EncodingMethod::Systematic)?;
|
||||
|
||||
let dec_config = DecoderConfig {
|
||||
max_iterations: config.max_iterations,
|
||||
early_stopping: true,
|
||||
};
|
||||
let dec_sp = build_decoder(&code, DecoderMethod::SumProduct, dec_config.clone());
|
||||
let dec_ms = build_decoder(
|
||||
&code,
|
||||
DecoderMethod::MinSum {
|
||||
scaling_factor: 0.8,
|
||||
},
|
||||
dec_config.clone(),
|
||||
);
|
||||
let dec_bf = build_decoder(&code, DecoderMethod::BitFlipping, dec_config);
|
||||
|
||||
for &snr in &config.snr_range {
|
||||
pb.set_message(format!("Test: {} | SNR: {:.2} dB", scenario.name, snr));
|
||||
let channel = AwgnChannel::new(snr, rate)?;
|
||||
let cap = channel.capacity();
|
||||
|
||||
let start_snr_time = Instant::now();
|
||||
|
||||
let results: Vec<_> = (0..config.n_trials)
|
||||
.into_par_iter()
|
||||
.map(|_| {
|
||||
let mut rng = rand::thread_rng();
|
||||
let message: Vec<u8> = (0..scenario.k).map(|_| rng.gen::<u8>() & 1).collect();
|
||||
let codeword = encoder.encode(&message).unwrap();
|
||||
let rx_llr = channel.transmit(&codeword, &mut rng);
|
||||
|
||||
let eval_decoder = |decoder: &dyn crate::decoder::Decoder| -> (usize, usize) {
|
||||
if let Some(decoded) = decoder.decode(&rx_llr).codeword() {
|
||||
let errs = codeword
|
||||
.iter()
|
||||
.zip(decoded.iter())
|
||||
.filter(|(a, b)| a != b)
|
||||
.count();
|
||||
(if errs > 0 { 1 } else { 0 }, errs)
|
||||
} else {
|
||||
(1, scenario.n)
|
||||
}
|
||||
};
|
||||
|
||||
let (sp_f, sp_b) = eval_decoder(&*dec_sp);
|
||||
let (ms_f, ms_b) = eval_decoder(&*dec_ms);
|
||||
let (bf_f, bf_b) = eval_decoder(&*dec_bf);
|
||||
|
||||
(sp_f, sp_b, ms_f, ms_b, bf_f, bf_b)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut sp_err = (0, 0);
|
||||
let mut ms_err = (0, 0);
|
||||
let mut bf_err = (0, 0);
|
||||
for r in results {
|
||||
sp_err.0 += r.0;
|
||||
sp_err.1 += r.1;
|
||||
ms_err.0 += r.2;
|
||||
ms_err.1 += r.3;
|
||||
bf_err.0 += r.4;
|
||||
bf_err.1 += r.5;
|
||||
}
|
||||
|
||||
let elapsed_ms = start_snr_time.elapsed().as_millis();
|
||||
let total_f = config.n_trials as f64;
|
||||
let total_b = (config.n_trials * scenario.n) as f64;
|
||||
|
||||
let mut write_csv_line = |dec_name: &str, f_err: usize, b_err: usize| {
|
||||
writeln!(
|
||||
file,
|
||||
"{},{},{},{:.3},{},{},{},{},{:.4},{:.2},{:.4},{},{:.4},{:.4e},{},{}",
|
||||
scenario.name,
|
||||
scenario.n,
|
||||
scenario.k,
|
||||
rate,
|
||||
scenario.wc,
|
||||
scenario.wr,
|
||||
method_str,
|
||||
girth,
|
||||
density,
|
||||
snr,
|
||||
cap,
|
||||
dec_name,
|
||||
(f_err as f64 / total_f) * 100.0,
|
||||
(b_err as f64 / total_b) * 100.0,
|
||||
config.n_trials,
|
||||
elapsed_ms
|
||||
)
|
||||
.unwrap();
|
||||
};
|
||||
|
||||
write_csv_line("SumProduct", sp_err.0, sp_err.1);
|
||||
write_csv_line("MinSum_0.8", ms_err.0, ms_err.1);
|
||||
write_csv_line("BitFlipping", bf_err.0, bf_err.1);
|
||||
|
||||
file.flush().unwrap();
|
||||
pb.inc(1);
|
||||
}
|
||||
}
|
||||
|
||||
pb.finish_with_message("Campagne terminee avec succes !");
|
||||
Ok(())
|
||||
}
|
||||
118
src/bin/generator.rs
Normal file
118
src/bin/generator.rs
Normal file
@ -0,0 +1,118 @@
|
||||
use clap::Parser;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use ldpc::code::{CodeTopology, GenerationMethod, LdpcCode, LdpcParams};
|
||||
use rayon::prelude::*;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about = "Generateur LDPC Haute Performance")]
|
||||
struct Args {
|
||||
#[arg(short, long)]
|
||||
n: usize,
|
||||
#[arg(short, long)]
|
||||
k: usize,
|
||||
#[arg(long, default_value_t = 3)]
|
||||
wc: usize,
|
||||
#[arg(long, default_value_t = 6)]
|
||||
wr: usize,
|
||||
#[arg(short, long, default_value = "mackay")]
|
||||
method: String,
|
||||
}
|
||||
|
||||
fn main() -> ldpc::Result<()> {
|
||||
let args = Args::parse();
|
||||
let m = args.n - args.k;
|
||||
|
||||
if (args.n * args.wc) % m != 0 || (args.n * args.wc) / m != args.wr {
|
||||
println!("Erreur : Parametres impossibles (n*wc != m*wr)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let found = Arc::new(AtomicBool::new(false));
|
||||
let attempts = Arc::new(AtomicU64::new(0));
|
||||
let start_global = Instant::now();
|
||||
|
||||
let pb = ProgressBar::new_spinner();
|
||||
pb.enable_steady_tick(Duration::from_millis(80));
|
||||
pb.set_style(
|
||||
ProgressStyle::default_spinner()
|
||||
.template(
|
||||
"{spinner:.cyan} [{elapsed_precise}] {msg} | Tentatives: {pos} | {per_sec} mats/s",
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
pb.set_message("Recherche d'une matrice valide...");
|
||||
|
||||
let method = if args.method == "mackay" {
|
||||
GenerationMethod::MacKayNeal { max_attempts: 1000 }
|
||||
} else {
|
||||
GenerationMethod::Gallager
|
||||
};
|
||||
|
||||
let pb_clone = pb.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let attempts_clone = Arc::clone(&attempts);
|
||||
|
||||
let result = (0..num_cpus::get())
|
||||
.into_par_iter()
|
||||
.map(|_| {
|
||||
while !found_clone.load(Ordering::Relaxed) {
|
||||
let current_attempt = attempts_clone.fetch_add(1, Ordering::SeqCst);
|
||||
pb_clone.set_position(current_attempt);
|
||||
|
||||
let params = LdpcParams {
|
||||
n: args.n,
|
||||
k: args.k,
|
||||
topology: CodeTopology::Regular {
|
||||
wc: args.wc,
|
||||
wr: args.wr,
|
||||
},
|
||||
generation: method.clone(),
|
||||
seed: Some(rand::random()),
|
||||
};
|
||||
|
||||
if let Ok(mut code) = LdpcCode::new(params) {
|
||||
// Cette etape est la plus longue (Gauss-Jordan)
|
||||
if code.compute_systematic_form().is_ok() {
|
||||
if !found_clone.swap(true, Ordering::SeqCst) {
|
||||
return Some(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.find_any(|res| res.is_some())
|
||||
.flatten();
|
||||
|
||||
if let Some(code) = result {
|
||||
pb.finish_with_message(format!("Succes en {:.2?}", start_global.elapsed()));
|
||||
|
||||
let filename = format!(
|
||||
"cache_ldpc_{}_n{}_k{}.bin",
|
||||
args.method.to_uppercase(),
|
||||
args.n,
|
||||
args.k
|
||||
);
|
||||
let encoded = bincode::serialize(&code).expect("Erreur serialisation");
|
||||
let mut file = File::create(&filename).expect("Erreur creation");
|
||||
file.write_all(&encoded).expect("Erreur ecriture");
|
||||
|
||||
println!("\nFichier genere : {}", filename);
|
||||
println!(
|
||||
"Girth : {} | Densite : {:.2}%",
|
||||
code.girth(),
|
||||
code.h.density() * 100.0
|
||||
);
|
||||
} else {
|
||||
pb.abandon_with_message("Recherche arretee.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -1,5 +1,4 @@
|
||||
use crate::code::LdpcCode;
|
||||
use crate::matrix::DenseMatrixGF2;
|
||||
use crate::{BitVec, Gf2, LdpcError, Result};
|
||||
|
||||
pub trait Encoder: Send + Sync {
|
||||
@ -27,7 +26,8 @@ pub enum EncodingMethod {
|
||||
pub struct SystematicEncoder {
|
||||
k: usize,
|
||||
n: usize,
|
||||
g_t: DenseMatrixGF2,
|
||||
// g_t: DenseMatrixGF2,
|
||||
packed_g_cols: Vec<Vec<u64>>,
|
||||
perm_inv: Vec<usize>,
|
||||
col_perm: Vec<usize>,
|
||||
}
|
||||
@ -36,10 +36,30 @@ impl SystematicEncoder {
|
||||
pub fn new(code: &mut LdpcCode) -> Result<Self> {
|
||||
code.compute_systematic_form()?;
|
||||
let sf = code.systematic_form.as_ref().unwrap();
|
||||
|
||||
let k = code.k();
|
||||
let n = code.n();
|
||||
let g_t = &sf.g;
|
||||
|
||||
let num_blocks = (n + 63) / 64;
|
||||
|
||||
// Bitpacking
|
||||
let mut packed_g_cols = vec![vec![0u64; num_blocks]; k];
|
||||
|
||||
for j in 0..k {
|
||||
for i in 0..n {
|
||||
if g_t.get(i, j) == 1 {
|
||||
let block_idx = i / 64;
|
||||
let bit_idx = i % 64;
|
||||
packed_g_cols[j][block_idx] |= 1 << bit_idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
k: code.k(),
|
||||
n: code.n(),
|
||||
g_t: sf.g.clone(),
|
||||
k,
|
||||
n,
|
||||
packed_g_cols,
|
||||
perm_inv: sf.col_perm_inv.clone(),
|
||||
col_perm: sf.col_perm.clone(),
|
||||
})
|
||||
@ -47,19 +67,44 @@ impl SystematicEncoder {
|
||||
}
|
||||
|
||||
impl Encoder for SystematicEncoder {
|
||||
// fn encode(&self, message: &[Gf2]) -> Result<BitVec> {
|
||||
// self.check_input(message)?;
|
||||
//
|
||||
// let c_perm = self.g_t.multiply_vec(message);
|
||||
//
|
||||
// // Retablir l'ordre initial des bits selon la permutation de H
|
||||
// let mut c = vec![0u8; self.n];
|
||||
// // for (i, &ci) in c_perm.iter().enumerate() {
|
||||
// // c[self.perm_inv[i]] = ci;
|
||||
// // }
|
||||
//
|
||||
// for i in 0..self.n {
|
||||
// c[i] = c_perm[self.perm_inv[i]];
|
||||
// }
|
||||
//
|
||||
// Ok(c)
|
||||
// }
|
||||
fn encode(&self, message: &[Gf2]) -> Result<BitVec> {
|
||||
self.check_input(message)?;
|
||||
|
||||
let c_perm = self.g_t.multiply_vec(message);
|
||||
let num_blocks = (self.n + 63) / 64;
|
||||
let mut accum = vec![0u64; num_blocks];
|
||||
|
||||
for (j, &bit) in message.iter().enumerate() {
|
||||
if bit == 1 {
|
||||
for b in 0..num_blocks {
|
||||
accum[b] ^= self.packed_g_cols[j][b];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Retablir l'ordre initial des bits selon la permutation de H
|
||||
let mut c = vec![0u8; self.n];
|
||||
// for (i, &ci) in c_perm.iter().enumerate() {
|
||||
// c[self.perm_inv[i]] = ci;
|
||||
// }
|
||||
|
||||
for i in 0..self.n {
|
||||
c[i] = c_perm[self.perm_inv[i]];
|
||||
let block_idx = i / 64;
|
||||
let bit_idx = i % 64;
|
||||
let val = ((accum[block_idx] >> bit_idx) & 1) as u8;
|
||||
|
||||
c[self.col_perm[i]] = val;
|
||||
}
|
||||
|
||||
Ok(c)
|
||||
|
||||
200
src/image_sim.rs
200
src/image_sim.rs
@ -5,7 +5,9 @@ use crate::{
|
||||
Gf2, Result,
|
||||
};
|
||||
use image::{ImageBuffer, Rgb};
|
||||
use rand::SeedableRng;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use rayon::prelude::*;
|
||||
use std::time::Instant;
|
||||
|
||||
// Convertit un tableau d'octets en un flux de bits
|
||||
pub fn bytes_to_bits(bytes: &[u8]) -> Vec<Gf2> {
|
||||
@ -32,6 +34,103 @@ pub fn bits_to_bytes(bits: &[Gf2]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
// Transmet une image à travers le canal avec codage LDPC
|
||||
// pub fn transmit_image(
|
||||
// input_path: &str,
|
||||
// noisy_out_path: &str,
|
||||
// decoded_out_path: &str,
|
||||
// encoder: &dyn Encoder,
|
||||
// decoder: &dyn Decoder,
|
||||
// channel: &AwgnChannel,
|
||||
// ) -> Result<()> {
|
||||
// println!("[*] Chargement de l'image : {}", input_path);
|
||||
// let img = image::open(input_path)
|
||||
// .expect("Erreur de chargement de l'image")
|
||||
// .to_rgb8();
|
||||
// let (width, height) = img.dimensions();
|
||||
// let raw_bytes = img.into_raw();
|
||||
//
|
||||
// let mut bits = bytes_to_bits(&raw_bytes);
|
||||
// let original_bit_len = bits.len();
|
||||
//
|
||||
// // Padding
|
||||
// let k = encoder.message_len();
|
||||
// let remainder = bits.len() % k;
|
||||
// if remainder != 0 {
|
||||
// bits.resize(bits.len() + (k - remainder), 0);
|
||||
// }
|
||||
//
|
||||
// let num_blocks = bits.len() / k;
|
||||
// println!(" - Taille: {}x{} pixels", width, height);
|
||||
// println!(" - Blocs à transmettre (k={}): {}", k, num_blocks);
|
||||
//
|
||||
// let mut rng = rand::rngs::StdRng::seed_from_u64(42);
|
||||
//
|
||||
// let mut noisy_bits = Vec::with_capacity(num_blocks * k);
|
||||
// let mut decoded_bits = Vec::with_capacity(num_blocks * k);
|
||||
//
|
||||
// let mut frame_errors = 0;
|
||||
//
|
||||
// println!("[*] Transmission et Décodage en cours...");
|
||||
//
|
||||
// for (i, block) in bits.chunks(k).enumerate() {
|
||||
// if i % 100 == 0 && i > 0 {
|
||||
// println!(" - Progession: {} / {} blocs...", i, num_blocks);
|
||||
// }
|
||||
//
|
||||
// let codeword = encoder.encode(block)?;
|
||||
//
|
||||
// let rx_llr = channel.transmit(&codeword, &mut rng);
|
||||
//
|
||||
// // Sans correction LDPC
|
||||
// let hard_codeword: Vec<Gf2> = rx_llr
|
||||
// .iter()
|
||||
// .map(|&l| if l < 0.0 { 1 } else { 0 })
|
||||
// .collect();
|
||||
// let noisy_block = encoder.extract_message(&hard_codeword);
|
||||
// noisy_bits.extend_from_slice(&noisy_block);
|
||||
//
|
||||
// // Décodage LDPC
|
||||
// let res = decoder.decode(&rx_llr);
|
||||
// if let Some(decoded_codeword) = res.codeword() {
|
||||
// let decoded_msg = encoder.extract_message(decoded_codeword);
|
||||
// decoded_bits.extend_from_slice(&decoded_msg);
|
||||
//
|
||||
// if decoded_msg != block {
|
||||
// frame_errors += 1;
|
||||
// }
|
||||
// } else {
|
||||
// decoded_bits.extend_from_slice(&noisy_block);
|
||||
// frame_errors += 1;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// println!(
|
||||
// "[*] Transmission terminée. FER : {:.2}%",
|
||||
// (frame_errors as f64 / num_blocks as f64) * 100.0
|
||||
// );
|
||||
//
|
||||
// // Suppression du padding
|
||||
// noisy_bits.truncate(original_bit_len);
|
||||
// decoded_bits.truncate(original_bit_len);
|
||||
//
|
||||
// // Reconstitution des images
|
||||
// let noisy_bytes = bits_to_bytes(&noisy_bits);
|
||||
// let decoded_bytes = bits_to_bytes(&decoded_bits);
|
||||
//
|
||||
// let noisy_img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, noisy_bytes)
|
||||
// .expect("Erreur de reconstruction de l'image bruitée");
|
||||
// noisy_img.save(noisy_out_path).unwrap();
|
||||
//
|
||||
// let decoded_img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, decoded_bytes)
|
||||
// .expect("Erreur de reconstruction de l'image décodée");
|
||||
// decoded_img.save(decoded_out_path).unwrap();
|
||||
//
|
||||
// println!(
|
||||
// "[*] Images sauvegardées : {} et {}",
|
||||
// noisy_out_path, decoded_out_path
|
||||
// );
|
||||
// Ok(())
|
||||
// }
|
||||
pub fn transmit_image(
|
||||
input_path: &str,
|
||||
noisy_out_path: &str,
|
||||
@ -40,9 +139,9 @@ pub fn transmit_image(
|
||||
decoder: &dyn Decoder,
|
||||
channel: &AwgnChannel,
|
||||
) -> Result<()> {
|
||||
println!("[*] Chargement de l'image : {}", input_path);
|
||||
println!("\n[*] Chargement de l'image : {}", input_path);
|
||||
let img = image::open(input_path)
|
||||
.expect("Erreur de chargement de l'image")
|
||||
.expect("Erreur : Impossible de trouver ou lire l'image")
|
||||
.to_rgb8();
|
||||
let (width, height) = img.dimensions();
|
||||
let raw_bytes = img.into_raw();
|
||||
@ -50,7 +149,6 @@ pub fn transmit_image(
|
||||
let mut bits = bytes_to_bits(&raw_bytes);
|
||||
let original_bit_len = bits.len();
|
||||
|
||||
// Padding
|
||||
let k = encoder.message_len();
|
||||
let remainder = bits.len() % k;
|
||||
if remainder != 0 {
|
||||
@ -58,60 +156,68 @@ pub fn transmit_image(
|
||||
}
|
||||
|
||||
let num_blocks = bits.len() / k;
|
||||
println!(" - Taille: {}x{} pixels", width, height);
|
||||
println!(" - Blocs à transmettre (k={}): {}", k, num_blocks);
|
||||
println!(" - Résolution : {}x{} pixels", width, height);
|
||||
println!(
|
||||
" - Poids total : {:.2} Mo",
|
||||
raw_bytes.len() as f64 / 1_048_576.0
|
||||
);
|
||||
println!(" - Découpage en : {} blocs de {} bits\n", num_blocks, k);
|
||||
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
|
||||
let start_time = Instant::now();
|
||||
|
||||
let pb = ProgressBar::new(num_blocks as u64);
|
||||
pb.set_style(
|
||||
ProgressStyle::default_bar()
|
||||
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} blocs ({eta})")
|
||||
.unwrap()
|
||||
.progress_chars("=>-")
|
||||
);
|
||||
|
||||
let results: Vec<_> = bits
|
||||
.par_chunks(k)
|
||||
.map(|block| {
|
||||
let mut rng = rand::thread_rng();
|
||||
let codeword = encoder.encode(block).unwrap();
|
||||
let rx_llr = channel.transmit(&codeword, &mut rng);
|
||||
let hard_codeword: Vec<Gf2> = rx_llr
|
||||
.iter()
|
||||
.map(|&l| if l < 0.0 { 1 } else { 0 })
|
||||
.collect();
|
||||
let noisy_block = encoder.extract_message(&hard_codeword);
|
||||
let res = decoder.decode(&rx_llr);
|
||||
|
||||
let (decoded_block, has_error) = if let Some(decoded_codeword) = res.codeword() {
|
||||
let decoded_msg = encoder.extract_message(decoded_codeword);
|
||||
let err = if decoded_msg != block { 1 } else { 0 };
|
||||
(decoded_msg, err)
|
||||
} else {
|
||||
(noisy_block.clone(), 1)
|
||||
};
|
||||
pb.inc(1);
|
||||
(noisy_block, decoded_block, has_error)
|
||||
})
|
||||
.collect();
|
||||
|
||||
pb.finish_with_message("Décodage terminé !");
|
||||
|
||||
let mut noisy_bits = Vec::with_capacity(num_blocks * k);
|
||||
let mut decoded_bits = Vec::with_capacity(num_blocks * k);
|
||||
|
||||
let mut frame_errors = 0;
|
||||
|
||||
println!("[*] Transmission et Décodage en cours...");
|
||||
|
||||
for (i, block) in bits.chunks(k).enumerate() {
|
||||
if i % 100 == 0 && i > 0 {
|
||||
println!(" - Progession: {} / {} blocs...", i, num_blocks);
|
||||
}
|
||||
|
||||
let codeword = encoder.encode(block)?;
|
||||
|
||||
let rx_llr = channel.transmit(&codeword, &mut rng);
|
||||
|
||||
// Sans correction LDPC
|
||||
let hard_codeword: Vec<Gf2> = rx_llr
|
||||
.iter()
|
||||
.map(|&l| if l < 0.0 { 1 } else { 0 })
|
||||
.collect();
|
||||
let noisy_block = encoder.extract_message(&hard_codeword);
|
||||
noisy_bits.extend_from_slice(&noisy_block);
|
||||
|
||||
// Décodage LDPC
|
||||
let res = decoder.decode(&rx_llr);
|
||||
if let Some(decoded_codeword) = res.codeword() {
|
||||
let decoded_msg = encoder.extract_message(decoded_codeword);
|
||||
decoded_bits.extend_from_slice(&decoded_msg);
|
||||
|
||||
if decoded_msg != block {
|
||||
frame_errors += 1;
|
||||
}
|
||||
} else {
|
||||
decoded_bits.extend_from_slice(&noisy_block);
|
||||
frame_errors += 1;
|
||||
}
|
||||
for (n_block, d_block, err) in results {
|
||||
noisy_bits.extend_from_slice(&n_block);
|
||||
decoded_bits.extend_from_slice(&d_block);
|
||||
frame_errors += err;
|
||||
}
|
||||
|
||||
println!(
|
||||
"[*] Transmission terminée. FER : {:.2}%",
|
||||
(frame_errors as f64 / num_blocks as f64) * 100.0
|
||||
);
|
||||
let duration = start_time.elapsed();
|
||||
let fer = (frame_errors as f64 / num_blocks as f64) * 100.0;
|
||||
println!("[*] Transmission terminée en {:.2?}", duration);
|
||||
println!(" - Taux d'Erreur Trame (FER) : {:.2}%", fer);
|
||||
|
||||
// Suppression du padding
|
||||
noisy_bits.truncate(original_bit_len);
|
||||
decoded_bits.truncate(original_bit_len);
|
||||
|
||||
// Reconstitution des images
|
||||
let noisy_bytes = bits_to_bytes(&noisy_bits);
|
||||
let decoded_bytes = bits_to_bytes(&decoded_bits);
|
||||
|
||||
@ -124,7 +230,7 @@ pub fn transmit_image(
|
||||
decoded_img.save(decoded_out_path).unwrap();
|
||||
|
||||
println!(
|
||||
"[*] Images sauvegardées : {} et {}",
|
||||
"[*] Succès ! Images sauvegardées : {} et {}",
|
||||
noisy_out_path, decoded_out_path
|
||||
);
|
||||
Ok(())
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
pub mod benchmark;
|
||||
pub mod benchmark2;
|
||||
pub mod channel;
|
||||
pub mod code;
|
||||
pub mod decoder;
|
||||
|
||||
136
src/main.rs
136
src/main.rs
@ -5,49 +5,116 @@ use ldpc::decoder::{build_decoder, DecoderConfig, DecoderMethod};
|
||||
use ldpc::encoder::{build_encoder, EncodingMethod};
|
||||
use ldpc::image_sim::transmit_image;
|
||||
|
||||
// fn main() -> ldpc::Result<()> {
|
||||
// let n = 1944;
|
||||
// let k = 972;
|
||||
// let wc = 3;
|
||||
// let wr = 6;
|
||||
//
|
||||
// println!("Transmission d'image via code LDPC");
|
||||
//
|
||||
// let code_mn = get_or_generate_cached_code(
|
||||
// n,
|
||||
// k,
|
||||
// wc,
|
||||
// wr,
|
||||
// GenerationMethod::MacKayNeal { max_attempts: 5000 },
|
||||
// )?;
|
||||
//
|
||||
// let mut code = code_mn;
|
||||
// let encoder = build_encoder(&mut code, EncodingMethod::Systematic)?;
|
||||
//
|
||||
// let config = DecoderConfig {
|
||||
// max_iterations: 50,
|
||||
// early_stopping: true,
|
||||
// };
|
||||
//
|
||||
// // Sum-Product
|
||||
// let decoder = build_decoder(&code, DecoderMethod::SumProduct, config);
|
||||
//
|
||||
// let channel = AwgnChannel::new(2.0, code.rate())?;
|
||||
//
|
||||
// transmit_image(
|
||||
// "test.png",
|
||||
// "noisy_out.png",
|
||||
// "decoded_out.png",
|
||||
// &*encoder,
|
||||
// &*decoder,
|
||||
// &channel,
|
||||
// )?;
|
||||
//
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
use clap::Parser;
|
||||
use ldpc::benchmark2::{run_massive_campaign, CampaignConfig, CodeScenario};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about = "Laboratoire de test LDPC - TIPE")]
|
||||
struct Args {
|
||||
#[arg(short, long, default_value_t = 1000)]
|
||||
trials: usize,
|
||||
|
||||
/// Générer les fichiers .dot pour visualiser les graphes de Tanner
|
||||
#[arg(long, default_value_t = false)]
|
||||
export_graph: bool,
|
||||
}
|
||||
|
||||
fn main() -> ldpc::Result<()> {
|
||||
let n = 1944;
|
||||
let k = 972;
|
||||
let wc = 3;
|
||||
let wr = 6;
|
||||
let args = Args::parse();
|
||||
let snrs = vec![1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.5, 4.0];
|
||||
let mut scenarios = Vec::new();
|
||||
|
||||
println!("Transmission d'image via code LDPC");
|
||||
// -------------------------------------------------------------------------
|
||||
// SCÉNARIO "TOY MODEL" : Spécial pour ton document Typst
|
||||
// Un code minuscule R=1/2 avec n=24, k=12, m=12.
|
||||
// Lisible sur une feuille A4.
|
||||
// -------------------------------------------------------------------------
|
||||
if args.export_graph {
|
||||
scenarios.push(CodeScenario {
|
||||
name: "ToyModel_Typst_N24".into(),
|
||||
n: 24,
|
||||
k: 12,
|
||||
wc: 3,
|
||||
wr: 6,
|
||||
method: GenerationMethod::Gallager,
|
||||
});
|
||||
}
|
||||
|
||||
let code_mn = get_or_generate_cached_code(
|
||||
n,
|
||||
k,
|
||||
wc,
|
||||
wr,
|
||||
GenerationMethod::MacKayNeal { max_attempts: 5000 },
|
||||
)?;
|
||||
// Les vrais tests pour tes courbes de performances
|
||||
scenarios.push(CodeScenario {
|
||||
name: "Gallager_N1296_R05".into(),
|
||||
n: 1296,
|
||||
k: 648,
|
||||
wc: 3,
|
||||
wr: 6,
|
||||
method: GenerationMethod::Gallager,
|
||||
});
|
||||
|
||||
let mut code = code_mn;
|
||||
let encoder = build_encoder(&mut code, EncodingMethod::Systematic)?;
|
||||
scenarios.push(CodeScenario {
|
||||
name: "MacKay_N1296_R05".into(),
|
||||
n: 1296,
|
||||
k: 648,
|
||||
wc: 3,
|
||||
wr: 6,
|
||||
method: GenerationMethod::MacKayNeal { max_attempts: 1000 },
|
||||
});
|
||||
|
||||
let config = DecoderConfig {
|
||||
let config = CampaignConfig {
|
||||
scenarios,
|
||||
snr_range: snrs,
|
||||
n_trials: args.trials,
|
||||
max_iterations: 50,
|
||||
early_stopping: true,
|
||||
output_csv: "tipe_results.csv".into(),
|
||||
export_graph: args.export_graph,
|
||||
};
|
||||
|
||||
// Sum-Product
|
||||
let decoder = build_decoder(&code, DecoderMethod::SumProduct, config);
|
||||
|
||||
let channel = AwgnChannel::new(2.0, code.rate())?;
|
||||
|
||||
transmit_image(
|
||||
"test.png",
|
||||
"noisy_out.png",
|
||||
"decoded_out.png",
|
||||
&*encoder,
|
||||
&*decoder,
|
||||
&channel,
|
||||
)?;
|
||||
run_massive_campaign(config)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// use ldpc::benchmark::{generate_valid_code, run_simulation};
|
||||
// use ldpc::code::GenerationMethod;
|
||||
// use ldpc::benchmark::run_simulation;
|
||||
//
|
||||
// fn main() -> ldpc::Result<()> {
|
||||
// let n = 1944;
|
||||
@ -59,17 +126,18 @@ fn main() -> ldpc::Result<()> {
|
||||
// println!();
|
||||
//
|
||||
// println!("Test 1: Génération MacKayNeal\n");
|
||||
// let code_mn = generate_valid_code(
|
||||
// let code_mn = get_or_generate_cached_code(
|
||||
// n,
|
||||
// k,
|
||||
// wc,
|
||||
// wr,
|
||||
// GenerationMethod::MacKayNeal { max_attempts: 1000 },
|
||||
// GenerationMethod::MacKayNeal { max_attempts: 5000 },
|
||||
// )?;
|
||||
//
|
||||
// run_simulation(code_mn)?;
|
||||
//
|
||||
// println!("\nTest 2 : Génération Gallager\n");
|
||||
// let code_gal = generate_valid_code(n, k, wc, wr, GenerationMethod::Gallager)?;
|
||||
// let code_gal = get_or_generate_cached_code(n, k, wc, wr, GenerationMethod::Gallager)?;
|
||||
// run_simulation(code_gal)?;
|
||||
//
|
||||
// Ok(())
|
||||
|
||||
Reference in New Issue
Block a user