def encode_test7(): data = bitarray('0' * 4084) actual = hamming.encode(data) expected = bitarray('0' * 4098) # 12 + 1 parity bits added return (0, "") if actual == expected else ( 1, "encode_test7 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
def encode_test8(): data = bitarray('0100') actual = hamming.encode(data) expected = bitarray('11001100') return (0, "") if actual == expected else ( 1, "encode_test8 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
def encode_test6(): data = bitarray('1') actual = hamming.encode(data) expected = bitarray('1111') # 2 + 1 parity bits added return (0, "") if actual == expected else ( 1, "encode_test6 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
def encode_test4(): data = bitarray('0' * 17) # 17 zeros -> need 5 + 1 parity bits, all zero actual = hamming.encode(data) expected = bitarray('0' * 23) # 6 parity bits added, all zero return (0, "") if actual == expected else ( 1, "encode_test4 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
def encode_test3(): data = bitarray('0011') actual = hamming.encode(data) expected = bitarray('11000011') # p1 = 1, p2 = 0, p4 = 0, overall = 1 return (0, "") if actual == expected else ( 1, "encode_test3 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
def draw(string, dpi, file_name): binary_str = hamming.encode(hamming.str_to_bin(string)) mm = dpi / 25.4 s = int(2*mm) c_width = int(210*mm) c_height = int(297*mm) m = int(round(sp.sqrt(len(binary_str)) / 4 + 1) * 3) n = int(round(len(binary_str) / m / 4 + 1) * 4) m_left = int(round((c_width - m * s) / 2)) m_top = int(round((c_height - n * s) / 2)) A = sp.array(list(binary_str)) B = mix.on(A, n, m) img = Image.new("L", (c_width, c_height)) d = ImageDraw.Draw(img) d.rectangle([(0, 0), img.size], fill=255) d.rectangle([(int(m_left/4), int(m_top/4)), (int(m_left/4)+10*mm, int(m_top/4)+10*mm)], fill=0) w = 1 d.line([(m_left, m_top), (m_left+s*m, m_top)], fill=0, width=w) d.line([(m_left, m_top), (m_left, m_top+s*n)], fill=0, width=w) d.line([(m_left+s*m, m_top), (m_left+s*m, m_top+s*n)], fill=0, width=w) d.line([(m_left, m_top+s*n), (m_left+s*m, m_top+s*n)], fill=0, width=w) draw_matrix(img, B, m_left, m_top, s, mm) img.save(file_name)
def toBits(self, encodeData=True): bits = [] for k in self.spytf: bits += k.toBits() if encodeData: return encode(bits) else: return bits
def hamming_message(msg, with_error=True): bitarray_msg = bitarray() original_msg = bitarray_msg bitarray_msg.frombytes(msg.encode('unicode_escape')) # Add parity bits for hamming bitarray_msg = encode(bitarray_msg) result_msg, real_msg = to_bitarray(bitarray_msg, with_error) return result_msg, original_msg, real_msg
def zakoduj( input ): #input jako string 0 i 1, funkcja koduje i przygotowuje dane wyjsciowe do przejscia przez kanal binar_input = str_to_bin(input) encodedd_data = encode(binar_input) #print(encodedd_data) cos = list(itertools.chain.from_iterable(encodedd_data.tolist( ))) #cos to lista 0 i 1 po zakodowania gotowa od przejscia przez kanaĆ #print(cos) return cos #zwraca liste np. [0,1,0,1,1] gotowa do przejscia przez kanal
def encode_test5(): # (overall: 1) (p1: 1) (p2: 1) 0 (p4: 1) 110 (p8: 0) 0100011 (p16: 0) 011110110110100 (p32: 1) 101110011000110110111101101101 data = bitarray('01100100011011110110110100101110011000110110111101101101' ) # 'dom.com' in ASCII binary actual = hamming.encode(data) expected = bitarray( '111011100010001100111101101101001101110011000110110111101101101' ) # 6 + 1 parity bits added return (0, "") if actual == expected else ( 1, "encode_test5 FAILED! Expected: {0}, Actual: {1}\n".format( expected, actual))
from PIL import Image import numpy as np import matplotlib.pyplot as plt from blur import blur, randomize from hamming import str_to_bin, bin_to_str, encode, decode, syndrome, correct from stego import insert, extract import matplotlib.image as mpimg # encode our original message using hamming(8,4) original_message = raw_input("Enter Message to Send: ") original_message_bin = str_to_bin(original_message) msg_len = len(original_message) print("Input:") print(original_message) encoded_message = encode(original_message_bin) # open up the image we want to use and get it ready to put data in img = Image.open("image.bmp") img = np.asarray(img) image = mpimg.imread("image.bmp") plt.title("Original Image") plt.imshow(image) plt.show() # insert our message into the image, then blur the image to simulate # compression/transmission/general data loss img_with_message = insert(img, encoded_message) print("Hiding Data in Image") im = Image.fromarray(img_with_message) im.save("image_steg.bmp")
def main(noiseRatio): packets = open('../data/packets.txt', 'r') # CRC VARIABLES crcTransmissions = 0 crcRetransmissions = 0 crcUndetectedErrors = 0 # HAMMING VARIABLES hammingTransmissions = 0 hammingRetransmissions = 0 hammingCorrections = 0 hammingUndetectedErrors = 0 # PACKET ANALYSIS for packet in packets: packet = packet[:len(packet)-1] # Remove the return carriage # CRC success = False crcEncodedPacket = crc.encode(packet) while not success: # Continue until the packet is accurately received crcNoisePacket = noise.gaussian(crcEncodedPacket, noiseRatio) crcTransmissions += 1 success = True if crc.decode(crcNoisePacket) == False: # If error(s) exist crcRetransmissions += 1 success = False elif crcEncodedPacket != crcNoisePacket: # Error occured and CRC didn't catch it crcUndetectedErrors += 1 # HAMMING success = False hammingEncodedPacket = hamming.encode(packet) while not success: # Continue until the packet is accurately received hammingNoisePacket = noise.gaussian(hammingEncodedPacket, noiseRatio) hammingTransmissions += 1 success = True decodedHammingPacket = hamming.decode(hammingNoisePacket) if not decodedHammingPacket: # Hamming decode failed - too many bit flips hammingRetransmissions += 1 success = False elif hammingNoisePacket != hammingEncodedPacket: # If a bit(s) was flipped & the result came back as true hammingCorrections += 1 # SUMMARY print "\n" print "NOISE RATIO: %s\n" % noiseRatio print "CRC ANALYSIS:" print "\tTransmissions: "+str(crcTransmissions) retransmissionRate = round(float(crcRetransmissions)/float(crcTransmissions)*100, 2) print "\tRetransmissions: "+str(crcRetransmissions)+" ~ "+str(retransmissionRate)+"%" print "\tUndetected Errors: "+str(crcUndetectedErrors) print "\n" print "HAMMING ANALYSIS" print "\tTransmissions: "+str(hammingTransmissions) retransmissionRate = round(float(hammingRetransmissions)/float(hammingTransmissions)*100, 2) print "\tRetransmissions: "+str(hammingRetransmissions)+" ~ "+str(retransmissionRate)+"%" print "\tCorrected Packets: "+str(hammingCorrections) print "\tUndetected Errors: "+str(hammingUndetectedErrors) print "\n" # Write data to file with open("../data/crcOut.txt",'a') as fout: fout.write("(%s,%s)"%(noiseRatio,round(float(crcRetransmissions)/float(crcTransmissions)*100, 2))) with open("../data/hammingOut.txt",'a') as fout: fout.write("(%s,%s)"%(noiseRatio,round(float(hammingRetransmissions)/float(hammingTransmissions)*100, 2)))
ber_list = [] sum1, sum2, sum3, sum4, sum5, sum6 = 0, 0, 0, 0, 0, 0 for i in range(10): lst = generate_bits(1000000) coded_lst = code_triple(lst) output = gilbert(coded_lst, *parameter_list) decoded_lst = decode_triple(output) #ber_list.append(ber_triple(lst, decoded_lst)) sum1 += ber_triple(lst, decoded_lst) #plt.plot(ber_list, [3], label='Kodowanie potrojeniowe', marker='o') # ======================================================================== ber_list = [] hamming_encoded = hamming.encode(lst) output_hamming = gilbert(hamming_encoded, *parameter_list) hamming_decoded = hamming.decode(output_hamming) #ber_list.append(ber_triple(lst, hamming_decoded)) sum2 += ber_triple(lst, hamming_decoded) #plt.plot(ber_list, [2], label='Kodowanie Hamminga(8, 4)', marker='o') # ======================================================================== packet_size = 1007 t = 10 redundancy = 1120 / 1007 ber_list = [] chunks = [ lst[x:x + packet_size] for x in range(0, len(lst), packet_size)
from hamming import encode,decode from bitarray import bitarray data = bitarray('1111') data_with_parity = encode(data) print(data_with_parity) data_with_parity[3] = not data_with_parity data_with_parity[4] = not data_with_parity print(decode(data_with_parity))
# Message msm = msm_org # verification msm_bit = bitarray.bitarray() msm_bit.frombytes(msm.encode('utf-8')) # original bits original_msm = bitarray.bitarray() original_msm.frombytes(msm.encode('utf-8')) # Hamming Code if hamming_bool: msm_bit_encoded = encode(msm_bit.to01()) msm_bit.clear() msm_bit.extend(msm_bit_encoded) # Noise noise_bit_cnt = 0 if noise: probabilidad = 1/100 # estimated errors every x bits bitchange = lambda x: 1 if x == 0 else 0 # change a single bit for i in range(len(msm_bit)): toss = random.uniform(0, 1) if toss < probabilidad: noise_bit_cnt += 1
print "CRC RT B\r" print "\tNumTrans:\t" + str(numTrans) print "\tNumRT:\t" + str(numRT) print "\tCorrections:\t" + str(corrections) print "\tBadReads:\t" + str(badReads) numTrans = 0 numRT = 0 badReads = 0 corrections = 0 # Hamming - Gaussian with open('../data/packets.txt', 'r') as fin: for packet in fin: packet = packet.strip() hammingEncodedPacket = hamming.encode(packet) success = False while not success: hammingNoisePacket = noise.gaussian(hammingEncodedPacket, noiseRatio) numTrans += 1 hammingDecodedPacket = hamming.decode(hammingNoisePacket) if hammingEncodedPacket == hammingNoisePacket: # No interference success = True elif hammingDecodedPacket == packet: # Correction was good success = True corrections += 1 elif hammingDecodedPacket == False: # Could not correct numRT += 1 else: # Bad correction badReads += 1 success = True
# To change the probability of error change this value prob_err=float(1/12) # With the input we will add 0's the end to ensure we have groups of 4. a = list(input("Enter a bit string: ")) a = [int(j) for j in a] a = split(a, 4) print(f"Original Message: {[j for sub in a for j in sub]}") # Encode the messages encoded_msg = [] for j in range(len(a)): encoded_msg += hamming.encode(a[j]) # Simulate error err_msg = sim_error(encoded_msg, p_err=prob_err) print(f"Encoded Message: {encoded_msg}\n") print(f"Encoded Message with error: {err_msg}") print(f"The Error: {[j ^ k for j, k in zip(encoded_msg, err_msg)]}\n") # Decode err_msg_chuncked = split(err_msg, 7) decoded_msg = [] for j in range(len(err_msg_chuncked)): decoded_msg += hamming.decode(err_msg_chuncked[j]) print(f"Decoded Message: {decoded_msg}")