use crate::GF2;
use rand::distributions::Uniform;
use rand::{thread_rng, Rng};
pub trait BinaryChannel: Sync + Send {
fn intrinsic_likelyhood(&self, output: GF2) -> f64;
fn send(&self, input: GF2) -> GF2;
fn message_likelyhood(&self, output: &[GF2]) -> Vec<f64> {
output
.iter()
.map(|x| self.intrinsic_likelyhood(*x))
.collect()
}
fn sample(&self, inputs: &[GF2]) -> Vec<GF2> {
inputs.iter().map(|input| self.send(*input)).collect()
}
fn sample_uniform(&self, input: GF2, n_inputs: usize) -> Vec<GF2> {
(0..n_inputs).map(|_| self.send(input)).collect()
}
}
#[derive(Clone)]
pub struct BinarySymmetricChannel {
prob: f64,
log_likelyhood: f64,
}
impl BinarySymmetricChannel {
pub fn new(prob: f64) -> Self {
if 0.0 <= prob && prob <= 1.0 {
Self {
prob,
log_likelyhood: (prob / (1.0 - prob)).log2(),
}
} else {
panic!("prob is not between 0 and 1")
}
}
}
impl BinaryChannel for BinarySymmetricChannel {
fn intrinsic_likelyhood(&self, output: GF2) -> f64 {
if output == GF2::B0 {
self.log_likelyhood
} else {
-1.0 * self.log_likelyhood
}
}
fn send(&self, input: GF2) -> GF2 {
let rand = thread_rng().sample(Uniform::new(0.0, 1.0));
if rand < self.prob {
input + GF2::B1
} else {
input
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn binary_symmetric_channel() {
let channel = BinarySymmetricChannel::new(0.2);
assert_eq!(channel.intrinsic_likelyhood(GF2::B0), -2.0);
assert_eq!(channel.intrinsic_likelyhood(GF2::B1), 2.0);
assert_eq!(
channel.message_likelyhood(&[GF2::B1, GF2::B0, GF2::B1]),
vec![2.0, -2.0, 2.0]
);
}
}