def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") #print(byte_stream) if "201502091" in byte_stream: # remove studentId new_byteStream = byte_stream.replace('201502091 ', '').strip() display(new_byteStream) #print(new_byteStream) #print(type(new_byteStream) new_byteStream = RSCodec(FEC_BYTES).encode(new_byteStream) #print(type(new_byteStream))--> bytearray play(new_byteStream) # call main function #new_byteStream = new_byteStream.encode("utf-8") #new_byteStream = RSCodec(FEC_BYTES).encode(new_byteStream) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def _ehead(self, data: bytes): header = b'FsTeg\x01\x02\x03' ee = pad(data, self.block_size) ll = struct.pack('i', 1 + len(ee) // self.block_size) _rrs1 = RSCodec() _rrs2 = RSCodec(_check) return _rrs1.encode(pad(header + ll, _header_size - 10)) + _rrs2.encode(pad(data, _rsc_block))
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) #print(dom) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") #print(byte_stream) #이 부분을 찍어보면 최종 문자열을 확인가능 if "201502127" in byte_stream: # in 키워드를 이용하면 문자열이 있는지를 찾을 수 있다. ID_count = byte_stream.count( "201502127") #201502127이 몇번 출현하는지 찾는다. byte_stream = extract_Data(byte_stream, ID_count) display(byte_stream) try: byte_stream = RSCodec(FEC_BYTES).encode( byte_stream.encode("utf-8") ) # 필요한 데이터 뒤에 오류 코드까지 아스키 코드(1byte)로 인코딩 되어 나온다. #print(byte_stream[0:4]) #byteArray가 된 " hel"이 출력됨. sound(bytes_to_freq(byte_stream)) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL) mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) print("original code", byte_stream) if match_num(byte_stream) == False: break try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") print(byte_stream) byte_stream = byte_stream.replace("201702087", "") display(byte_stream) display("") sin_freq = [] byte_stream = byte_stream.encode("utf-8") byte_stream = RSCodec(FEC_BYTES).encode(byte_stream) sin_freq = make_freq(byte_stream, sin_freq) print(sin_freq) make_sound(sin_freq) except ReedSolomonError as e: print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) #소리를 주파수로 변환하는 함수(dominant), 소리에 맞게 주파수를 분리 if in_packet and match(dom, HANDSHAKE_END_HZ): #끝 주파수를 수신함 byte_stream = extract_packet( packet) #주파수의 묶음을 데이터로 바꿔줌(extract packet) try: byte_stream = RSCodec(FEC_BYTES).decode( byte_stream) #RSCodec 함수로 FEC_BYTES 디코딩 byte_stream = byte_stream.decode("utf-8") #문자값으로로 디코딩 #print(byte_stream) if byte_stream[:9] == number: #학번이 입력되면 #print(byte_stream[:9]) display(byte_stream[9:]) #학번 이후부터 결과출력 byte_stream = byte_stream[9:] # print(byte_stream[9:]) byte_stream = byte_stream.encode("utf-8") #아스키코드값으로 인코딩 byte_stream = RSCodec(FEC_BYTES).encode( byte_stream) #RSCodec 함수로 FEC_BYTES 인코딩 make_sound(byte_stream) #make_sound함수 호출 except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) #주파수를 받음 elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) #print("packet: ",packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream_test = byte_stream.decode("utf-8") if '201402455' in byte_stream_test: byte_stream = re.sub(b'201402455',b''0,byte_stream) byte_stream = RSCodec(FEC_BYTES).encode(byte_stream) temp_stream = [] temp_stream.append(HANDSHAKE_START_HZ) temp_stream.append(HANDSHAKE_START_HZ) for i in range(len(byte_stream)): temp_stream.append(((byte_stream[i] >> 4)*STEP_HZ)+START_HZ) temp_stream.append(((byte_stream[i] & 0xf)*STEP_HZ)+START_HZ) temp_stream.append(HANDSHAKE_END_HZ) temp_stream.append(HANDSHAKE_END_HZ) p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate =44100, output = True) duration = 0.5 # for i in range(len(n:ewbyte_stream)): samples = (np.sin(2*np.pi*np.arange(44100*duration)*(temp_stream[i]/44100))).astype(np.float32) stream.write(samples) stream.stop_stream() stream.close() p.terminate() else: print("don't have my_number")
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): bit_chunks, byte_stream = extract_packet(packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") try: index = byte_stream.index("201502007") except: index = -1 if (index > -1): stream = bit_chunks[0:index * 2] + bit_chunks[index * 2 + 18:-8] rs = [] for target in RSCodec(4).encode(byte_stream[0:index] + byte_stream[index + 9:])[-4:]: rs.append(int(target / 16)) rs.append(target & 15) stream = [12] + stream + rs + [20] make_sounds(stream) display(byte_stream) except ReedSolomonError as e: pass # print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") if ID in byte_stream: global result_stream #print(byte_stream) result_stream = byte_stream.replace(ID, '') result_stream = result_stream.strip() rs = RSCodec(4) result_stream = rs.encode(result_stream) print(result_stream) play_linux() display(byte_stream) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def generate(n, k=12, mnemonic=Mnemonic("english")): """Generate a mnemonic phrase with the specified level of error correction. Phrases include t=(n-k) "error correcting" words, allowing the correction of up to t invalid words in a phrase, and up to floor(t/2) words that are wrong, but still valid BIP-39 words. Arguments: n (int): Total number of words in the phrase. k (int): Number of words chosen at random. mnemonic (Mnemonic): Instance of Mnemonic to use. """ ok, error = validate_n_k(n, k) if not ok: raise ValueError(error) coder = RSCodec(nsize=n, nsym=(n-k), c_exp=BIP39_SYMBOL_SIZE) for i in itertools.count(): bits = random_bits(k*BIP39_SYMBOL_SIZE) symbols = bits_to_symbols(bits, BIP39_SYMBOL_SIZE) coded = coder.encode(symbols) phrase = symbols_to_mnemonic(coded, mnemonic) if not mnemonic.check(phrase): continue return phrase
def rsdecode(rscode, msglen): ''' msg:rs二进制码 ''' ecc = RSCodec(96) length = len(rscode) padmsglen = (msglen // 7 + 1) * 7 rslen = padmsglen + 96 * 8 temp = [] for i in range(0, padmsglen, 7): temp.append(int(rscode[i:i + 7], 2)) for i in range(padmsglen, rslen, 8): temp.append(int(rscode[i:i + 8], 2)) temp = bytearray(temp) try: rscode = ecc.decode(temp) rscode = ''.join(format(x, '08b') for x in rscode) finally: if len(rscode) == length: print('too many bits errors!') return rscode[:msglen] else: temp = '' for i in range(0, padmsglen // 7 * 8, 8): temp += rscode[i + 1:i + 8] return temp[:msglen]
def __init__(self): self.rsc = RSCodec(10) # default to be 10 self.delimiter = b"|:|:|" # type bytes self.checksum = 0 # type String self.length = str(0) self.seqNo = 0 self.msg = 0
def extract_packet(freqs): # listen_linux 함수에서 쓰임 freqs = freqs[::2] ## 2개씩 끊어서 가져옴 bit_chunks = [int(round((f - START_HZ) / STEP_HZ)) for f in freqs] bit_chunks = [c for c in bit_chunks[1:] if 0 <= c < (2**BITS)] byte_stream = bytearray(decode_bitchunks(BITS, bit_chunks)) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") if "201502049" in byte_stream: except_byte_stream = byte_stream.replace("201502049", "") del freqs[20:-8] with noalsaerr(): p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=True) for freq in freqs: samples = (np.sin(2 * np.pi * np.arange(44100 * 0.4) * freq / 44100)).astype(np.float32) stream.write(samples) stream.stop_stream() stream.close() p.terminate() except ReedSolomonError as e: #pass print("{}: {}".format(e, byte_stream)) return except_byte_stream
def recover(phrase, k=12, mnemonic=Mnemonic("english")): """Attempts to recover the original mnemonic phrase from a mnemonic phrase with errors. Infers the value of n from the number of words in the phrase. If words are missing or unknown, include an arbitrary character in its place. (e.g. '_') Arguments: phrase (str): Mnemonic phrase with errors to fix. k (int): Number of words chosen at random. mnemonic (Mnemonic): Instance of Mnemonic to use. """ symbols = mnemonic_to_symbols(phrase, mnemonic) ok, error = validate_n_k(len(symbols), k) if not ok: raise ValueError(error) coder = RSCodec(nsize=len(symbols), nsym=(len(symbols)-k), c_exp=BIP39_SYMBOL_SIZE) erasures = [i for i, s in enumerate(symbols) if s < 0] recovered, _, _ = coder.decode(symbols, erase_pos=erasures) coded = coder.encode(recovered) phrase = symbols_to_mnemonic(coded, mnemonic) if not mnemonic.check(phrase): raise ValueError("error-corrected phrase does not have a valid checksum") return phrase
def decodeWithReedSolo(encodedata): if len(encodedata) > 255: return b'', False, 255 # print(encodedata) # if len(encodedata) > 255: # c = math.ceil(len(encodedata) / 2) # print(c) # if c > 255: # c = 255 # byte2, check2, err2 = decodeWithReedSolo(encodedata[c:]) # byte1, check1, err1 = decodeWithReedSolo(encodedata[:c]) # if (check2[0] and check1[0]): # print(check2) # return byte1 + byte2, check1, err1 + err2 # else: # ecc_len = math.ceil(len(encodedata) / (1+errorPercent) * errorPercent) # return b'', False, ecc_len // 2 + 1 ecc_len = math.ceil(len(encodedata) / (1 + errorPercent) * errorPercent) # print(ecc_len) rsc = RSCodec(math.ceil(ecc_len)) check = rsc.check(encodedata) try: decoded_msg, decoded_msgecc, errata_pos = rsc.decode(encodedata) check = rsc.check(decoded_msgecc) return decoded_msg, check, len(errata_pos) except: return b'', check, ecc_len // 2 + 1
def __init__(self, callsign): self.sequenceId = 0 callsignLen = 6 if len(callsign) > 6 else len(callsign) self.callsign = bytes( callsign[:callsignLen].upper() + ' ' * (6 - len(callsign)), 'utf-8') self.rs = RSCodec(16)
def encodeWithReedSolo(bytedata, length=0): if len(bytedata) > 182 or length > 256: return b'' ecc_len = 0 if length == 0: # if len(bytedata) > 182: # c = math.ceil(len(bytedata) / 2) # if c > 182: # c = 182 # return encodeWithReedSolo(bytedata[:c]) + encodeWithReedSolo(bytedata[c:]) ecc_len = math.ceil(len(bytedata) * errorPercent) else: # if length > 255: # c = math.ceil(length / 2) # print(c) # if c > 255: # c = 255 # return encodeWithReedSolo(bytedata[:c]) + encodeWithReedSolo(bytedata[c:]) print('use length ' + str(length)) ecc_len = math.ceil(int(length) / (1 + errorPercent) * errorPercent) bytedata += os.urandom(math.floor(length - ecc_len - len(bytedata))) print('error: ' + str(ecc_len)) print('random: ' + str(math.floor(length - ecc_len - len(bytedata)))) print('data: ' + str(len(bytedata))) rsc = RSCodec(ecc_len) encodedata = rsc.encode(bytedata) print('ENCODED') print(len(encodedata)) return encodedata
def __init__(self, PACKEGE_SIZE, NUMBER_OF_ERRORS, packeg_q, size_results=10, packeg_n=16): # create logger self.logger = logging.getLogger('add_reed') self.logger.setLevel(logging.INFO) self.PACKEGE_SIZE = PACKEGE_SIZE self.NUMBER_OF_ERRORS = NUMBER_OF_ERRORS self.rsc = RSCodec(NUMBER_OF_ERRORS) #give information about how much the reed will be able to fix #maxerrors, maxerasures = self.rsc.maxerrata(verbose=True) #self.logger.info("This codec can correct up to"+maxerrors+" errors and"+ maxerasures+" erasures independently") self.packeg_q = packeg_q self.packeg_proportion = { "normal": packeg_n, "reed5": self.check_len_reed(NUMBER_OF_ERRORS, packeg_n) } self.reed5_q = queue.Queue(maxsize=size_results) super(AddReed5, self).__init__()
def decode(quart_coded_data): quart_coded_data = quart_coded_data[4:-4:] binary_coded_data = '' for byte in quart_coded_data: if byte == '0': binary_coded_data += '00' elif byte == '1': binary_coded_data += '01' elif byte == '2': binary_coded_data += '10' elif byte == '3': binary_coded_data += '11' else: raise ValueError coded_data = [] for bit_chunk in range(0, len(binary_coded_data), 8): chunk_data = '' for bit_ind in range(8): chunk_data += binary_coded_data[bit_chunk + bit_ind] value = int(chunk_data, 2) coded_data.append(value) coded_data = bytes(coded_data) rsc = RSCodec(10) decoded_data = rsc.decode(coded_data)[0].decode() return decoded_data
def __init__(self, max_payload, ec_bytes, seed = 1895746671, mother = "bior3.1", sparsity = 0.7): self.mother = mother self.sparsity = sparsity self.rscodec = RSCodec(ec_bytes) self.max_payload = max_payload self.total_bits = (max_payload + ec_bytes) * 8 self.seed = seed
def reed_solomon_decode(txt: typing.Union[bytes, str, bytearray], number_repair_symbols: int = 2) -> bytes: global rscodec, number_r_symbols if rscodec is None or number_r_symbols != number_repair_symbols: rscodec = RSCodec(number_repair_symbols) number_r_symbols = number_repair_symbols return bytes(rscodec.decode(txt))
def __init__(self, packet_seq_num, telemetry_packet_type, current_batch_num, current_chunk_num, chunk): self.rsc = RSCodec(16) # 16 ecc symbols self.chunk = chunk packet_data = self._create_chunk_packet_data(telemetry_packet_type, current_batch_num, current_chunk_num, chunk) super().__init__(packet_seq_num, packet_data)
def main(): for i in range(0, 256): postit = np.tile(np.uint8([255]), (postit_height, postit_width, 1)) #draw location dot for count in range(0, 8): location_dot_array = [1] + [ 0 for j in range(0, location_dot_num - 1) ] for j in range(0, len(location_dot_array) - 2): if count & 2**j != 0: location_dot_array[j + 1] = 1 if count < 3: draw_location_dot(postit, location_dot_array, horizon_x_buffer + count * horizon_space, horizon_y_buffer, True) elif count < 6: draw_location_dot( postit, location_dot_array, horizon_x_buffer + (count - 3) * horizon_space, postit_height - horizon_y_buffer - location_height, True) elif count == 6: draw_location_dot(postit, location_dot_array, horizon_y_buffer, postit_height / 2 - location_width / 2, False) elif count == 7: draw_location_dot( postit, location_dot_array, postit_width - horizon_y_buffer - location_height, postit_height / 2 - location_width / 2, False) #need reed solomon rs = RSCodec(14) rs_result = rs.encode([i]) #make bit array bit_array_all = [] for number in rs_result: #print number bit_array = [0 for j in range(0, bit_num)] for j in range(0, bit_num - 1): if number & 2**j != 0: bit_array[j] = 1 bit_array[bit_num - 1] = bit_array[0] bit_array_all.append(bit_array) #draw bit array draw_all_bit(bit_array_all, postit) #outer rectangle cv2.rectangle(postit, (0, 0), (postit_width - 1, postit_height - 1), 0, 1) #cv2.imshow("result", postit) #cv2.waitKey(0) filename = "./datas/postit/postit" + str(i) + ".jpg" cv2.imwrite(filename, postit)
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) # chanel 1 use mic.setrate(44100) # frame_rate 44100/s mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) # print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) if in_packet and match(dom, HANDSHAKE_END_HZ): print("end") byte_stream = extract_packet(packet) try: # 4 bytes byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) # reed solo error check byte_stream = byte_stream.decode("utf-8") if STUDENT_ID in byte_stream: byte_stream = byte_stream.replace(STUDENT_ID, "").strip() display(byte_stream) byte_stream = RSCodec(FEC_BYTES).encode(byte_stream) sleep(1) speaking_linux(byte_stream) sleep(1) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True print("start HandShake")
def remove_reed5(self, s1,missing_pack_list): rsc = RSCodec(self.NUMBER_OF_ERRORS) try: s2 = rsc.decode(s1,erase_pos=missing_pack_list) return (s2[0]) except: return (None)
def __init__(self, file_in, alpha, stop=None, rs=0, c_dist=0.1, delta=0.5, scanner=None): # alpha is the redundency level # stop is whether we have a limit on the number of oligos # chunk_size and file_size are in bytes # rs is the number of bytes for reed-solomon error correcting code over gf(2^8). # c_dist is a parameter of the degree distribution # delta is a parameter of the degree distribution # np: should we use numpy random number generator? Faster, but incompatible for previous versions # max_homopolymer: the largest homopolymer allowed # gc: the allowable range of gc +- 50% # data: self.file_in = file_in self.chunk_size = len(file_in[0]) self.num_chunks = len(file_in) # reduancy: self.alpha = alpha self.stop = stop self.final = self.calc_stop() # random mnumber generator self.lfsr = lfsr( lfsr32s(), lfsr32p() ) # starting an lfsr with a certain state and a polynomial for 32bits. self.lfsr_l = len('{0:b}'.format( lfsr32p())) - 1 # calculate the length of lsfr in bits self.seed = self.lfsr.__next__() self.PRNG = PRNG(K=self.num_chunks, delta=delta, c=c_dist, np=np) # creating the solition distribution object self.PRNG.set_seed(self.seed) # error correcting code: self.rs = rs # the number of symbols (bytes) to add self.rs_obj = RSCodec(self.rs) # initalizing an reed solomon object # biological screens: self.scanner = scanner if self.scanner == None: self.scanner = Scanner() self.tries = 0 # number of times we tried to create a droplet self.good = 0 # droplets that were screened successfully. self.oligo_l = self.calc_oligo_length() # store the generated droplets self.dna_df = None self.dna_dl = []
def test_long(self): rs = RSCodec(10) msg = bytearray("a" * 10000, "utf8") enc = rs.encode(msg) dec = rs.decode(enc) self.assertEqual(dec, msg) enc[177] = 99 enc[2212] = 88 dec2 = rs.decode(enc) self.assertEqual(dec2, msg)
def test_correction(self): rs = RSCodec(10) msg = bytearray("hello world " * 10, "utf8") enc = rs.encode(msg) self.assertEqual(rs.decode(enc), msg) for i in [27, -3, -9, 7, 0]: enc[i] = 99 self.assertEqual(rs.decode(enc), msg) enc[82] = 99 self.assertRaises(ReedSolomonError, rs.decode, enc)
def encode(string, coding): #encode the text in bytes in_bytes = string.encode("utf-8") #compress the bytes compressed = zlib.compress(in_bytes, 9) # if coding!=0, add error correcting code if(coding): rs = RSCodec(coding) compressed = rs.encode(compressed) return compressed
def decode(compressed, coding): #correct errors if coding!=0 if(coding): rs = RSCodec(coding) compressed = rs.decode(compressed) #decompress the bytes in_bytes = zlib.decompress(compressed) #decode the text in bytes string = in_bytes.decode("utf-8") return string
def decode(self, text) -> typing.Tuple[int, bytes]: norepair_symbols: bytes = xor_mask(struct.unpack("<I", text[:4])[0]) text = text[4:] if self.rscodec is None: self.rscodec = RSCodec(int(norepair_symbols)) decoded = self.rscodec.decode(text) i: int = struct.unpack("<I", decoded[:4])[0] i: int = xor_mask(i) data: bytes = decoded[4:] return i, data