Untitled
unknown
plain_text
3 years ago
1.9 kB
4
Indexable
import numpy as np import itertools G = [[1, 1, 0, 1], [1, 0, 1, 1], [1, 0, 0, 0], [0, 1, 1, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] H = [[1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 1]] R = [[0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]] G = np.array(G) H = np.array(H) R = np.array(R) def hamming_detect_errors(cw): parity_bits = np.zeros((3,)) if False in np.equal(np.mod(np.matmul(H, cw), 2), parity_bits): return "Error" else: return "No errors detected!" def hamming_encode_cw(inp): return np.mod(np.matmul(G, inp), 2) def hamming_decode(cw): return np.mod(np.matmul(R, cw), 2) def corrupt_msg(cw, bit_idx): cw[bit_idx] = not cw[bit_idx] return cw def validate_input_output(input: list[int], output: list[int]): assert len(input) == len(output) for idx in input: if input[idx] != output[idx]: return False return True # Testing section x = [list(x) for x in itertools.product([0,1], repeat=4)] error_count = 0 for word_to_test in x: print(f'Original Codeword: {word_to_test}') code_word = hamming_encode_cw(np.array(word_to_test)) print(f'Encoded: {code_word}') check_error = hamming_detect_errors(code_word) print(f'Errors: {check_error}') decode_word = hamming_decode(code_word) print(f'Decoded: {decode_word}') code_word = corrupt_msg(code_word, 2) print(f'Corrupted Code Word: {code_word}') check_error = hamming_detect_errors(code_word) print(f'Errors: {check_error}') decode_word = hamming_decode(code_word) print(f'Decoded: {decode_word}') if not validate_input_output(word_to_test, decode_word): error_count += 1 print('-'*16) print(f'Error Count: {error_count}')
Editor is loading...