ldpc_toolbox/cli/
encode.rs

1//! Encode CLI subcommand.
2//!
3//! This command can be used to encode using a systematic LDPC code.
4
5use super::ber::parse_puncturing_pattern;
6use crate::{
7    cli::Run, encoder::Encoder, gf2::GF2, simulation::puncturing::Puncturer, sparse::SparseMatrix,
8};
9use clap::Parser;
10use ndarray::Array1;
11use num_traits::{One, Zero};
12use std::{
13    error::Error,
14    fs::File,
15    io::{ErrorKind, Read, Write},
16};
17
18/// Encode CLI arguments.
19#[derive(Debug, Parser)]
20#[command(about = "Performs LDPC encoding")]
21pub struct Args {
22    /// alist file for the code
23    alist: String,
24    /// input file (information words as unpacked bits)
25    input: String,
26    /// output file (punctured words as unpacked bits)
27    output: String,
28    /// Puncturing pattern (format "1,1,1,0")
29    #[structopt(long)]
30    puncturing: Option<String>,
31}
32
33impl Run for Args {
34    fn run(&self) -> Result<(), Box<dyn Error>> {
35        let puncturer = if let Some(p) = self.puncturing.as_ref() {
36            Some(Puncturer::new(&parse_puncturing_pattern(p)?))
37        } else {
38            None
39        };
40        let h = SparseMatrix::from_alist(&std::fs::read_to_string(&self.alist)?)?;
41        let mut input = File::open(&self.input)?;
42        let mut output = File::create(&self.output)?;
43        let encoder = Encoder::from_h(&h)?;
44        let n = h.num_cols();
45        let k = n - h.num_rows();
46        let mut information_word = vec![0; k];
47        let mut codeword_buf = vec![0; n];
48        loop {
49            match input.read_exact(&mut information_word[..]) {
50                Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
51                ret => ret?,
52            };
53            let word = Array1::from_iter(
54                information_word
55                    .iter()
56                    .map(|&b| if b == 1 { GF2::one() } else { GF2::zero() }),
57            );
58            let codeword = encoder.encode(&word);
59            let codeword = match &puncturer {
60                Some(p) => p.puncture(&codeword)?,
61                None => codeword,
62            };
63            for (x, y) in codeword.iter().zip(codeword_buf.iter_mut()) {
64                *y = x.is_one().into();
65            }
66            output.write_all(&codeword_buf)?;
67        }
68        Ok(())
69    }
70}