def config(): CONFIGURATION_METHOD = ["manual", "auto"] while True: configmethod = input("How do you want to configure this session? (manual/auto): ").lower() if not configmethod in CONFIGURATION_METHOD: print("Invalid Input !") else: break if configmethod == "auto": return Coder(AUTO_SETUP['m'], AUTO_SETUP['q'], AUTO_SETUP['polynoms_index']) else: m = int(input("Give the parameter m = n - k (m integer below 6):")) q = int(input("Give the parameter q, cardinal of the finitefield:")) polynoms_index = int(input("Give index of the generator polynomial you want to use (see list in the json file):")) return Coder(m,q,polynoms_index)
def mkstats1_1(lambdas, errfunc=dist_h, paramcoder=(3, 2)): inittime = time() crt_code = Coder(paramcoder[0], paramcoder[1], 0) res = np.zeros((NB_LAMBDA)) for i in range(NB_LAMBDA): crt_res = 0 print("\r{}/{}".format(i, NB_LAMBDA), end=" ", flush=True) for j in range(NB_TEST): crt_dh = DataHandler(testtext, crt_code, lenbinarychar=7) crt_dh.downgradelevel() crt_dh.downgradelevel() crt_dh.ATTACK(param=lambdas[i]) crt_dh.upgradelevel() crt_dh.upgradelevel() crt_res += errfunc(testtext, crt_dh.data) crt_res /= NB_TEST res[i] = crt_res print('Time : {} s'.format(time() - inittime)) return res
def mkstats2(paramcoders=[(3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2)], NB_TIMES=10): res = np.zeros((len(paramcoders))) for i, parcod in enumerate(paramcoders): crt_code = Coder(parcod[0], parcod[1], 0) inittime = time() for j in range(NB_TIMES): crt_dh = DataHandler(testtext, crt_code, lenbinarychar=7) crt_dh.downgradelevel() crt_dh.downgradelevel() crt_dh.ATTACK(param=0.99) crt_dh.upgradelevel() crt_dh.upgradelevel() res[i] = (time() - inittime) / NB_TIMES plt.plot(res) plt.show() return res
#/usr/bin/python import sys from Parser import Parser from Coder import Coder if len(sys.argv) < 3: print 'Please enter input and output filenames' sys.exit(1) else: input_files = sys.argv[1:len(sys.argv)-1] output_file = sys.argv[len(sys.argv)-1:] coder = Coder(output_file[0]) for input_file in input_files: coder.set_filename(input_file) parser = Parser(input_file) while(parser.has_more_commands()): parser.advance() command_type = parser.command_type() if command_type == 'C_PUSH' or command_type == 'C_POP': coder.write_push_pop(command_type, parser.arg1(), int(parser.arg2())) if command_type == 'C_ARITHMETIC': coder.write_arithmetic(parser.arg1())
class ARQSystem: _coder = Coder() def __init__(self, number_of_packets, packet_size, noise_generator, checksum_mode, protocol_name, channel): self.number_of_packets = number_of_packets self.packet_size = packet_size self.noise_generator = noise_generator self.checksum_mode = checksum_mode self.number_of_errors = 0 self.number_of_packets_sent = 0 self.packets = [] self.protocol_name = protocol_name self.channel = channel self.number_of_fake_packages_accepted = 0 self.chance_for_packet_as_string = "" self.chance_for_bit_as_string = "" self.chance_to_series_of_errors_as_string = "" self.chance_to_start_series_of_errors_as_string = "" self.chance_to_end_series_of_errors_as_string = "" def run(self): self._prepare_packets() if self.protocol_name == Protocol.STOP_AND_WAIT: self._stop_and_wait() elif self.protocol_name == Protocol.GO_BACK_N: self._go_back_n() else: raise Exception("Invalid protocol!") def _prepare_packets(self): self.packets.clear() for i in range(0, self.number_of_packets): self.packets.append(BitPacket(self.checksum_mode, self.packet_size)) packet = self.packets[-1] packet.generate_bits() if self.checksum_mode == ChecksumMode.PARITY_BIT: packet.set_checksum(self._coder.designate_parity_bit(packet.get_bits())) elif self.checksum_mode == ChecksumMode.LRC: packet.set_checksum(self._coder.designate_longitudinal_redundancy_check(packet.get_bits())) elif self.checksum_mode == ChecksumMode.VERHOEFF_CODE: packet.set_checksum(self._coder.designate_verhoeff_checksum(packet.get_bits())) else: raise Exception("Invalid protocol!") def _stop_and_wait(self): for packet in self.packets: changed_packet = self.noise_generator.make_noise(packet.get_bits(), packet.get_checksum(), self.channel) response = self._check_packet(changed_packet[0], changed_packet[1]) while not response: self.number_of_errors += 1 changed_packet = self.noise_generator.make_noise(packet.get_bits(), packet.get_checksum(), self.channel) response = self._check_packet(changed_packet[0], changed_packet[1]) def _check_packet(self, bits, checksum): self.number_of_packets_sent += 1 if self.checksum_mode == ChecksumMode.PARITY_BIT: return self._coder.check_parity_bit(bits, checksum) elif self.checksum_mode == ChecksumMode.LRC: return self._coder.check_longitudinal_redundancy_check(bits, checksum) elif self.checksum_mode == ChecksumMode.VERHOEFF_CODE: return self._coder.check_verhoeff_checksum(bits, checksum) else: raise Exception("Invalid checksum mode!") def _go_back_n(self): pass def set_chance_info(self, chance_for_packet, chance_for_bit, chance_to_series_of_errors, chance_to_start_series_of_errors, chance_to_end_series_of_errors): self.chance_for_packet_as_string = str(chance_for_packet) self.chance_for_bit_as_string = str(chance_for_bit) self.chance_to_series_of_errors_as_string = str(chance_to_series_of_errors) self.chance_to_start_series_of_errors_as_string = str(chance_to_start_series_of_errors) self.chance_to_end_series_of_errors_as_string = str(chance_to_end_series_of_errors) def print_results(self, file_name): checksum_mode_as_string = "" checksum_size = 0 if self.checksum_mode == ChecksumMode.PARITY_BIT: checksum_mode_as_string = "bit parzystości" checksum_size = 1 elif self.checksum_mode == ChecksumMode.LRC: checksum_mode_as_string = "lrc" checksum_size = 4 elif self.checksum_mode == ChecksumMode.VERHOEFF_CODE: checksum_mode_as_string = "algorytm Verhoeffa" checksum_size = 4 total_packet_size = self.packet_size + checksum_size channel_as_string = "" ber = str(self.noise_generator.get_number_of_errors() / (self.number_of_packets * total_packet_size)) per = str((self.number_of_errors / self.number_of_packets_sent)) e = str((self.number_of_packets * total_packet_size) / (self.number_of_packets_sent * total_packet_size)) with open(file_name, "w+") as file: file.write("Opis symulacji: \n\n" "Opcje:\n" "Liczba pakietów: " + str(self.number_of_packets) + "\n" "Liczba bitów w pakiecie: " + str(self.packet_size) + "\n" "Algorytm sumy kontrolnej: " + checksum_mode_as_string + "\n" "Kanał: " + channel_as_string + "\n" "Szansa za zmianę pakietu: " + self.chance_for_packet_as_string + "\n" "Szansa za zmianę bitu: " + self.chance_for_bit_as_string + "\n" "Szansa za serię błędów: " + self.chance_to_series_of_errors_as_string + "\n" "Szansa za rozpoczęcie serii błędów: " + self.chance_to_start_series_of_errors_as_string + "\n" "Szansa za zakończenie serii błędów: " + self.chance_to_end_series_of_errors_as_string + "\n" "Wyniki symulacji:\n" "Bitowa stopa błędów (BER): " + ber + "\n" "Pakietowa stopa błędów (PER): " + per + "\n" "Efektywność transimisji (E): " + e + "\n" "Redudancja (całkowita nadmiarowość): ")
class Decoder: def __init__(self, symbolFile, numberFile, coder=None): self.out = '' if (coder == None): self.symbolContent = open(symbolFile).read() self.numberContent = open(numberFile).read() self.statistics = {} self.UpdateStatistics() self.BuildCode() else: self.coder = coder def Run(self): self.UpdateStatistics() def UpdateStatistics(self): symbols = self.symbolContent[:-1].split('†') numbers = self.numberContent[:-1].split('†') for i in range(len(symbols)): self.statistics.update({symbols[i]: int(numbers[i])}) def BuildCode(self): treeBuilder = TreeBuilder(self.statistics) treeBuilder.Run() self.coder = Coder(treeBuilder.GetRoot()[0]) self.coder.Run() def DecodeFile(self, fileToDecode): with open(fileToDecode, encoding="ISO-8859-1") as file: content = bytearray(file.read().encode(encoding="ISO-8859-1")) return (self.Decode(content)) def Decode(self, input): self.out = '' match = '' for idx in range(0, len(input) - 5, 4): binaryString = str((bin(unpack('<i', input[idx:idx + 4])[0]).replace( "-", '').replace("0b", ''))) #paddingLen = 32 - (len(binaryString) % 32) #padding = '0' * paddingLen #binaryString = binaryString + padding for a in binaryString: match += a if match in self.coder.getCodeDict().values(): for el in self.coder.getCodeDict(): if self.coder.getCodeDict()[el] == match: self.out += el match = '' return self.out def DecodeString(self, input): self.out = '' match = '' for sign in input: match += sign if match in self.coder.getCodeDict().values(): for el in self.coder.getCodeDict(): if self.coder.getCodeDict()[el] == match: self.out += el match = '' return self.out def DecodeAllLevelsString(self, input, transNodes={}): self.out = '' match = '' for sign in input: match += sign if match in self.coder.getCodeDict().values(): for element in self.coder.getCodeDict(): if self.coder.getCodeDict()[element] == match: if element in transNodes.keys(): self.RecurencyDecode(element, transNodes) match = '' return self.out def RecurencyDecode(self, input, transNodes): for element in input: if element in transNodes.keys(): self.RecurencyDecode(transNodes[element], transNodes) else: self.out += element
def BuildCode(self): treeBuilder = TreeBuilder(self.statistics) treeBuilder.Run() self.coder = Coder(treeBuilder.GetRoot()[0]) self.coder.Run()
#!/usr/bin/python import sys from Parser import Parser from Coder import Coder from SymbolTable import SymbolTable coder = Coder() stable = SymbolTable() asm_file = None if len(sys.argv) is 0: print 'Please enter a filename as argument' sys.exit(1) else: asm_file = sys.argv[1] # PASS 1 RAM_top = 16 pc = 0 parser = Parser(asm_file) while parser.has_more_commands(): pc += 1 parser.advance() command_type = parser.command_type() if command_type == 'A_COMMAND': symbol = parser.symbol() if not stable.contains(symbol): stable.add_entry(symbol, RAM_top) RAM_top += 1
def Initiate(singleCharDict): treeBuilder = TreeBuilder(singleCharDict) treeBuilder.Run() coder = Coder(treeBuilder.GetRoot()[0]) coder.Run() return coder
def open_image(filename): image = Image.open(filename) image.load() image = numpy.array(image) return image def openImageio(filename): image = imageio.imread(filename) return image kanal = TransmissionChannel() koder = Coder() odbiornik = Receiver() random.seed(420) file_name = 'zdjecie.jpg' myImg = open_image(file_name) plt.figure('Wroclaw Image') plt.imshow(myImg) plt.show() myImgBSC = kanal.pass_bsc(myImg) plt.figure('Binary Symmetric Channel') plt.imshow(myImgBSC) plt.show()