LoginSignup
6
5

More than 5 years have passed since last update.

numpyでハミング符号

Posted at

numpyのリファレンスを眺めていたらビット処理にかんする便利そうな関数を発見したので,
テストもかねてハミング符号を実装してみた.
とりあえず,ハミング符号(4,3)にのみ対応.
uint8以外にも対応してればいいのになぁ.

hamming.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import random

if __name__ == '__main__':
    k = 4
    m = 3

    #2のベキ以外からなるリストを作成
    column_values = np.array([ [x] for x in range( 2 ** m ) if ( x & ( x - 1 ) ) != 0 ], dtype=np.uint8 )
    A = np.reshape( np.unpackbits( column_values ), ( k, 8) )[:, -3:].T

    #生成行列と検査行列を作る
    H = np.concatenate( ( A, np.eye( m, dtype=np.uint8 ) ), axis=1 )
    G = np.concatenate( ( np.eye( k, dtype = np.uint8 ), A.T ), axis = 1 )

    #符号化する値を適当に
    random.seed()
    code = random.randint( 0, 2 ** k - 1 )
    bit_code = np.unpackbits( np.array( code, dtype = np.uint8 ) )[-k:]

    #ハミング符号を生成して,あるビットを反転させる
    error_bit_offset = random.randint( 0, ( k + m ) - 1 )
    hamming_code = np.dot( bit_code, G ) % 2
    hamming_code[ error_bit_offset ] = ( hamming_code[ error_bit_offset ] + 1 ) % 2

    #検証

    check_result = np.dot( H, hamming_code ) % 2

    print code
    print hamming_code
    print H
    print error_bit_offset
    print check_result

実行結果

% ./hamming.py 
12
[1 0 0 0 1 1 0]
[[0 1 1 1 1 0 0]
 [1 0 1 1 0 1 0]
 [1 1 0 1 0 0 1]]
1
[1 0 1]
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5