async def set_brightness(self): if self.lamp_access: # if not bulb.is_on: # log.debug('Lamp is off, turning on.') # await bulb.turn_on() # await bulb.update() turn_off = False if self.brightness.perceived == 0: self.brightness.perceived = 1 turn_off = True log.debug(f'Changing brightness to {self.brightness.perceived}.') try: await bulb.set_brightness(self.brightness.actual) except Exception as e: log.exception(e) self.brightness.should_stop = True if turn_off: log.info('Brightness was set to 0, turning lamp off.') await asyncio.sleep(0.5) await bulb.turn_off() else: log.debug(f'{self.name} has no lamp access.')
def _create_cache_folder(): if _cache_folder_exists(): debug("cache folder already exists") return debug("creating cache folder") os.makedirs(CACHE_FOLDER_NAME)
def __init__( self, coder: Optional[AbstractCoder], noise_probability: Union[int, float], count_cyclical: Optional[int], duplex: Optional[bool], interleaver: Optional[Interleaver.Interleaver], noise_mode: EnumNoiseMode, noise_package_length: int, noise_package_period: int, ): log.debug("Create chanel") self._noiseMode = noise_mode self._noisePackageLength = noise_package_length self._noisePackagePeriod = noise_package_period self._coder: AbstractCoder = coder if noise_probability is not None: self.noiseProbability = noise_probability if count_cyclical is not None: self._countCyclical = count_cyclical if duplex is not None: self.duplex = duplex if interleaver is not None: self._interleaver = interleaver log.debug("Chanel created")
def transition(self, target_value: int, duration: int): log.debug('transitioning') diff = target_value - self.perceived if diff == 0: return # return when theres no change to make amount_of_steps, step_size = self.get_steps(duration, diff) single_sleep_dur = helpers.calc_sleep_dur(duration, amount_of_steps) steps = helpers.calc_steps(diff, amount_of_steps, step_size, self.perceived, target_value) log.info(f'{steps=}') log.info( f'{self.perceived=} {target_value=} {amount_of_steps=} {single_sleep_dur=}' ) # transition for step in steps: self.perceived = step self.set_brightness() time.sleep(single_sleep_dur) if self.should_stop: self.should_stop = False break
def __init__(self, length_information: int): log.debug("Create of Hamming _coder") # sum (2**(n-1)-1) from 1 to n must be >= length_information for correct check for iterator in range(1, length_information): if 2**iterator - iterator - 1 >= length_information: self.lengthAdditional = iterator break self.lengthInformation = length_information self.lengthTotal = self.lengthInformation + self.lengthAdditional self._matrixTransformation = [] for iterator in range(self.lengthAdditional): matrix_row: list = [] flag = True # Count nullable symbols count_null_symbols = (1 << iterator) - 1 for y in range((2**iterator) - 1): matrix_row.append(0) while count_null_symbols < self.lengthTotal: for y in range(2**iterator): matrix_row.append(1) if flag else matrix_row.append(0) count_null_symbols += 1 if count_null_symbols >= self.lengthTotal: break flag: bool = not flag self._matrixTransformation.append(matrix_row) # noinspection PyTypeChecker self._matrixTransformation = np.transpose( np.array(self._matrixTransformation))
def _create_database(): debug("creating database") if _db_exists(): debug("database already exists") return _create_table()
def __init__(self, size_block: int, count_coding_blocks: int, length_information: int): log.debug("Creation of fountain _coder with parameters: {0}, {1}, {2}". format(size_block, count_coding_blocks, length_information)) self.lengthInformation = length_information self._sizeBlock = size_block self._generationBlocks = [] self._countCodingBlocks = count_coding_blocks # целочисленное деление с округлением вверх self._countBlocks = ((length_information - 1) // self._sizeBlock) + 1 # генератор случайных чисел random_generator: random.Random = random.Random(random.random() * 50) # Генерация блоков сочетаний set_combination_blocks: set = set() while len(set_combination_blocks) < self._countCodingBlocks: if 2**self._countBlocks - 1 == len(set_combination_blocks): raise SettingException( message="Error occurs during creation Fountain _coder") set_combination_blocks.add( random_generator.getrandbits(self._countBlocks)) set_combination_blocks -= {0} self._generationBlocks: list = list(set_combination_blocks) self.lengthInformation = length_information self.lengthAdditional = size_block * count_coding_blocks - length_information self.lengthTotal = self.lengthInformation + self.lengthAdditional
def _create_folder(): debug("creating .intpy folder") if _folder_exists(): debug(".intpy folder already exists") return os.makedirs(FOLDER_NAME) ctypes.windll.kernel32.SetFileAttributesW(FOLDER_NAME, HIDDEN)
def __init__(self, information_length: int, polynomial: int): log.debug("Create cyclical _coder") self.lengthInformation = information_length self.lengthAdditional = int(math.log2(polynomial)) self.lengthTotal = self.lengthInformation + self.lengthAdditional self._polynomial = plm.Polynomial(int_to_bit_list(polynomial, rev=True))
def _create_table(): debug("creating table") conn = sqlite3.connect('.intpy/intpy.db') stmt = "CREATE TABLE IF NOT EXISTS CACHE (\ id INTEGER PRIMARY KEY AUTOINCREMENT,\ cache_file TEXT UNIQUE\ );" conn.execute(stmt) conn.close()
def __init__(self, controller): log.debug("Create main window") super(MainWindow, self).__init__() self.controller = controller uic.loadUi(r'./src/GUI/UI/window.ui', self) setup_main_window_coder(controller, self) setup_main_window_second_coder(controller, self) self.countTestEdit.valueChanged.connect( self.controller.testParams.set_count_test) self.countTestEdit.valueChanged.emit(self.countTestEdit.value()) self.informationEdit.textChanged.connect( self.controller.testParams.set_test_info) self.informationEdit.textChanged.emit(self.informationEdit.text()) globalSignals.stepFinished.connect(self.singleProgress.setValue) globalSignals.autoStepFinished.connect(self.autoProgress.setValue) # Disable buttons where start globalSignals.startTesting.connect( self.startSingleFirstCoderButton.setDisabled) globalSignals.startTesting.connect( self.startTestsFirstCoderButton.setDisabled) globalSignals.startTesting.connect( self.startSingleCascadeCoderButton.setDisabled) globalSignals.startTesting.connect( self.startTestsCascadeCoderButton.setDisabled) # Enable buttons where finish testing globalSignals.ended.connect( lambda: self.startSingleFirstCoderButton.setEnabled(True)) globalSignals.ended.connect( lambda: self.startTestsFirstCoderButton.setEnabled(True)) globalSignals.ended.connect( lambda: self.startSingleCascadeCoderButton.setEnabled(True)) globalSignals.ended.connect( lambda: self.startTestsCascadeCoderButton.setEnabled(True)) self.startSingleFirstCoderButton.clicked.connect( self.controller.testParams.start_first_single_test) self.startTestsFirstCoderButton.clicked.connect( self.controller.testParams.start_first_test_cycle) self.startSingleCascadeCoderButton.clicked.connect( self.controller.testParams.start_cascade_single_test) self.startTestsCascadeCoderButton.clicked.connect( self.controller.testParams.start_cascade_test_cycle) setup_main_window_noise(controller=controller, window=self) self.show()
def run(self): # noinspection PyBroadException try: if self._flg_auto: statistic = StatisticCollector( flgCascade=False, firstCoder=self._currentCoder, secondCoder=None, testResult=self._auto_test(), lengthFirstInterleaver=self._length_interleaver, lengthSecondInterleaver=None, beginNoise=self._start_t, endNoise=self._finish_t, quantityStepsInCycle=self._quantity_steps, noisePeriod=self._noisePackagePeriod, noiseLength=self._noisePackageLength, ) # Graphic should showing only for Cycle of the test globalSignals.ended.emit() if ConfigProcessor().config.graphic_setting.flg_enabled: GraphicController().draw_graphic(statistic) else: statistic = StatisticCollector( flgCascade=False, firstCoder=self._currentCoder, secondCoder=None, testResult=[self._single_test()], lengthFirstInterleaver=self._length_interleaver, lengthSecondInterleaver=None, beginNoise=self._start_t, endNoise=self._finish_t, quantityStepsInCycle=self._quantity_steps, noisePeriod=self._noisePackagePeriod, noiseLength=self._noisePackageLength, ) globalSignals.ended.emit() globalSignals.stepFinished.emit(int(self._MAX_PERCENT)) # DB Action if ConfigProcessor().config.db_setting.flg_used: TestResultSerializer().serialize_to_db(statistic) TestResultSerializer().serialize_to_json(statistic) log.debug("End of test cycle") except ApplicationException as application_exception: globalSignals.ended.emit() globalSignals.notCorrect.emit(application_exception, ) except Exception as err: globalSignals.ended.emit() log.error(str(Exception)) globalSignals.notCorrect.emit(ApplicationException())
def _single_test(self) -> TestResult: """ Method provide functionality for processing single test case :return: TestResult """ progress: float = self._MIN_PERCENT step: float = self._MAX_PERCENT / self._countTest information: list = int_to_bit_list(self._information) case_result_list: List[CaseResult] = [] global_test_statistic: SingleCoderTestThread.GlobalTestStatistic = SingleCoderTestThread.GlobalTestStatistic() log.debug("Test cycle begin") for number_of_test in range(self._countTest): transfer_statistic: Codec.TransferStatistic = self.channel.transfer_one_step(information) if transfer_statistic.result_status == EnumPackageTransferResult.SUCCESS: global_test_statistic.quantity_successful_package += 1 elif transfer_statistic.result_status == EnumPackageTransferResult.REPAIR: global_test_statistic.quantity_repair_package += 1 elif transfer_statistic.result_status == EnumPackageTransferResult.ERROR: global_test_statistic.quantity_error_package += 1 else: global_test_statistic.quantity_shadow_package += 1 global_test_statistic.quantity_correct_bits += transfer_statistic.quantity_successful_bits global_test_statistic.quantity_error_bits += transfer_statistic.quantity_error_bits global_test_statistic.based_correct_bits += transfer_statistic.based_correct_bits global_test_statistic.based_error_bits += transfer_statistic.based_error_bits progress += step globalSignals.stepFinished.emit(int(progress)) case_result_list.append(CaseResult( successfulBits=transfer_statistic.quantity_successful_bits, repairBits=transfer_statistic.quantity_repair_bits, changedBits=transfer_statistic.quantity_changed_bits, errorBits=transfer_statistic.quantity_error_bits )) return TestResult( list_case_result=case_result_list, first_coder=self._currentCoder, second_coder=None, noise_type=self._noiseMode, noise=self.channel.noiseProbability, flg_cascade=True, successful_packages=global_test_statistic.quantity_successful_package, repair_packages=global_test_statistic.quantity_repair_package, changed_packages=global_test_statistic.quantity_repair_package, error_packages=global_test_statistic.quantity_error_package, quantity_correct_bits=global_test_statistic.quantity_correct_bits, quantity_error_bits=global_test_statistic.quantity_error_bits, based_correct_bits=global_test_statistic.based_correct_bits, based_error_bits=global_test_statistic.based_error_bits )
async def set_color_temp(self): if self.lamp_access: # if not bulb.is_on: # await bulb.turn_on() # await bulb.update() log.info(f'Changing color temperature to {self.color_temp.kelvin}.') try: await bulb.set_color_temp(self.color_temp.kelvin) except Exception as e: log.exception(e) self.brightness.should_stop = True else: log.debug(f'{self.name} has no lamp access.')
def __init__(self, list_polynomials: List[int], count_input: int, count_output: int, count_register: int): log.debug("Create convolution _coder") self._countInput = count_input self._countOutput = count_output self._countRegisters = count_register self._countPolynomials = len(list_polynomials) self._listPolynomials = list_polynomials self.lengthTotal = self._countOutput self.lengthInformation = self._countInput self.lengthAdditional = self.lengthTotal - self.lengthInformation self._graph = self._get_graph()
def _auto_test(self) -> List[TestResult]: log.debug("Auto-test button pressed") step: float = SimpleCalculationForTransferProcess.calc_noise_of_steps_different( start=self._start_t, finish=self._finish_t, quantity_steps=self._quantity_steps ) progress: int = 0 sum_result_of_single_test: List[TestResult] = [] for iterator in [self._start_t + iterator * step for iterator in range(self._quantity_steps)]: progress += int(self._MAX_PERCENT / self._quantity_steps) self.channel.noiseProbability = self._MAX_PERCENT * (1 / (iterator + 1)) sum_result_of_single_test.append(self._single_test()) globalSignals.autoStepFinished.emit(int(progress)) globalSignals.autoStepFinished.emit(int(self._MAX_PERCENT)) globalSignals.autoStepFinished.emit(int(self._MAX_PERCENT)) return sum_result_of_single_test
def reestablish(self, information: List[int]) -> List[int]: log.debug("Used Un Interleaver for package {0}".format(information)) answer: List[int] = [0] * len(information) # noinspection PyBroadException try: # целочисленное деление с округлением вверх res_div: int = math.ceil(len(information) / self.lengthSmashing) for x in range(self.lengthSmashing): for y in range(res_div): if len(information) > x * res_div + y: answer[x + y * self.lengthSmashing] = information[x * res_div + y] except IndexError: if len(information) % self.lengthSmashing != 0: raise ParametersParseException( message=ParametersParseException.INTERLEAVER_SETTING.message, long_message=ParametersParseException.INTERLEAVER_SETTING.long_message, ) return answer
def set_default(d, k): """ Try to set a default value from nested_input_definitions. If there is no default value, delete the key (k) :param d: dictionary :param k: key :return: None """ try: if k not in ['tilt']: d[k] = d[k]['default'] else: # tilt default is "Site latitude" and is set to such in the api del d[k] except KeyError as e: if 'default' in e.args: log.debug("No default value exists for {}.".format(k)) del d[k] else: raise e
def gen_interference(self, information: list, straight: float = None) -> list: """ Генерация помех с задданной вероятностью :param information: list Информация, представленная в виде массива битов :param straight: Optional[float] Вероятность помех принимает значения от 0.00 до 100.00, может быть опушенна, в таком случае будет использоваться значение шума заданное в канале :return: Искажённую информацию, представленную в виде массива битов """ if straight is None: straight = self.__straight log.debug("Noise with probably {0}".format(straight)) random_generator: random.Random = random.Random( random.random() * 50) # генератор случайных чисел count_change_bit: int = int(len(information) * straight / 100) # кол-во ошибок на канале if count_change_bit == 0 and straight != 0: # если ошибок не ноль, то увеличиваем до 1 count_change_bit = 0 # множество битов которые будут измененны changes_bits: set = set() # собираем множество неповторяющихся битов while len(changes_bits) < count_change_bit: changes_bits.add(random_generator.randint(0, len(information) - 1)) # преобразуем в список changes_bits: list = list(changes_bits) answer: list = information.copy() # инвертирование битов for bit_value in changes_bits: answer[bit_value] ^= 1 log.debug( "During transport package noise changed package to {0}".format( answer)) return answer
def shuffle(self, information: List[int]) -> List[int]: log.debug("Used interleaver for package {0}".format(information)) answer: List[int] = [] try: for x in range(self.lengthSmashing): is_end: bool = False counter: int = 0 while not is_end: if (counter * self.lengthSmashing + x) < len(information): answer.append(information[counter * self.lengthSmashing + x]) else: is_end = True counter += 1 except IndexError: if len(information) % self.lengthSmashing != 0: raise ParametersParseException( message=ParametersParseException.INTERLEAVER_SETTING.message, long_message=ParametersParseException.INTERLEAVER_SETTING.long_message, ) return answer
def set_default(nested_dict, flat_dict, k, piped_key): """ Try to set a default value from nested_input_definitions. If there is no default value, set to None :param d: dictionary :param k: key :return: None """ if piped_key.startswith("Scenario"): piped_key = piped_key.lstrip("Scenario|") try: if k not in ['tilt']: flat_dict[piped_key] = nested_dict[k]['default'] else: # tilt default is "Site latitude" and is set to such in the api flat_dict[piped_key] = None except KeyError as e: if 'default' in e.args: log.debug( "No default value exists for {}. Set value to None".format(k)) flat_dict[piped_key] = None else: raise e
def _do_step(self, information_bit: int) -> list: """ Method contain functionality for generation _graph of :param information_bit: :return: """ log.debug("Step coding convolution - {0}".format(information_bit)) self._register <<= 1 # зануление старшего бита self._register &= (1 << (self._countRegisters + 1)) - 1 self._register += information_bit answer = [] power = 0 for count in range(self._countPolynomials): added_bit = 0 for x in int_to_bit_list(self._listPolynomials[count] & self._register): added_bit ^= x answer.append(added_bit % 2) power += 1 return answer
def transition(self, target_percent: int, duration: int): target_kelvin = self.convert_to_kelvin(target_percent) diff = target_kelvin - self.kelvin if diff == 0: return # return when theres no change to make #region calc step_size step_size = (diff * SINGLE_CHANGE_DUR) / duration if abs(step_size) < 100: step_size = 100 if step_size > 0 else -100 step_size = self.round_to_nearest_100(step_size) #endregion amount_of_steps = math.ceil(diff / step_size) single_sleep_dur = helpers.calc_sleep_dur(duration, amount_of_steps) steps = helpers.calc_steps(diff, amount_of_steps, step_size, self.kelvin, target_kelvin) log.debug(f'{step_size=}') log.info( f'{self.kelvin=} {target_kelvin=} {duration=} {amount_of_steps=} {single_sleep_dur=}' ) # transition for step in steps: self.kelvin = step time.sleep(single_sleep_dur) if self.should_stop: self.should_stop = False break
def decoding(self, information: List[int]) -> List[int]: log.info("Decoding package {0} of Hamming _coder".format(information)) code = np.transpose(np.array([[x] for x in information])) answer: list = [] try: status: list = list( (np.dot(code, self._matrixTransformation) % 2)[0]) except ValueError: # Impossible decoding. Not valid package length return information status.reverse() status_int_form: int = bit_list_to_int(status) if status_int_form != 0: log.debug("Error(s) detected") if len(code[0]) > status_int_form - 1: code[0][status_int_form - 1] = (code[0][status_int_form - 1] + 1) % 2 old_status = status_int_form status_int_form = bit_list_to_int( num=list((np.dot(code, self._matrixTransformation) % 2)[0])) if status_int_form != 0: log.debug( "Impossible correction this package. But errors found") log.debug("Successfully repair bit in position {0}".format( old_status)) else: log.debug("Impossible correction this package") count: int = 0 step: int = 0 for iterator in code[0]: if math.log2(count + 1) != int(math.log2(count + 1)) \ or step >= self.lengthAdditional: answer.append(iterator) else: step += 1 count += 1 return answer
def init_env(f): debug("cheking if intpy environment exists") if _env_exists(): debug("environment already exists") return f debug("creating intpy environment") _create_folder() _create_cache_folder() _create_database() return f
def gen_package_interference(self, information: list, length_of_block: int, straight: float = None, flg_split_package: bool = False) -> list: """ Генерация помех с задданной вероятностью :param flg_split_package: Нужен ли хотя бы один правильный символ между пакетами ошибок пакете :param information: list Информация, представленная в виде массива битов :param length_of_block: Длина блока информации :param straight: Optional[float] Вероятность помех принимает значения от 0.00 до 100.00, может быть опушенна, в таком случае будет использоваться значение шума заданное в канале :return: Искажённую информацию, представленную в виде массива битов """ if straight is None: straight = self.__straight log.debug("Length of package = {1}, noise probability{0}".format( straight, length_of_block)) begin_package_straight: float = straight / length_of_block # count error package of chanel count_error_package: int = int( len(information) * begin_package_straight) if flg_split_package: if count_error_package * length_of_block + count_error_package - 1 >= len( information): raise ChanelException( message=ChanelException.PACKET_LENGTH_EXCEEDED.message, long_message=ChanelException.PACKET_LENGTH_EXCEEDED. long_message) else: if count_error_package * length_of_block >= len(information): raise ChanelException( message=ChanelException.PACKET_LENGTH_EXCEEDED.message, long_message=ChanelException.PACKET_LENGTH_EXCEEDED. long_message) # random generator random_generator: random.Random = random.Random(random.random() * 50) count_free_bits: int = len( information) - count_error_package * length_of_block # mask of changed bits changes_bits: list = [] for iterator in range(count_error_package): if flg_split_package: # we should save bits for split package: count_free_bits - count of package - current step - 1 count_save_bits: int = count_error_package - iterator - 1 count_pass_bits = random_generator.randint( 1, count_free_bits - count_save_bits) changes_bits += count_pass_bits * [0] changes_bits += length_of_block * [1] else: count_pass_bits = random_generator.randint(0, count_free_bits) if count_pass_bits != 0: changes_bits += count_pass_bits * [0] changes_bits += length_of_block * [1] # We should degrease count free bits count_free_bits -= count_pass_bits result: list = information.copy() # inversion of bits for iterator in range(len(changes_bits)): result[iterator] ^= changes_bits[iterator] log.debug( "During transport package noise changed package to {0}".format( result)) return result
def decoding(self, information: list): """ Декодер LT-фонтанного кода с заранее установленным генератором случайных чисел :param information: list Закодированная информация, представленная в виде массива битов :return: list Декодированная информация, представленная в виде массива битов """ log.info( "Fountain LT-decoder decoding of package {0}".format(information)) decoded_set_list: list = [ set(bit_list_to_int_list(int_to_bit_list(x, self._sizeBlock))) for x in self._generationBlocks ] decoded_set_list.append(set()) # костыль, чтобы работало is_kill: bool = False # Divided into blocks status: list = [False for x in range(self._countBlocks)] status.append(True) # One block should be always true block_int_values: List[int] = [] for num_of_block in range(0, len(information), self._sizeBlock): help_data: list = [] for num_of_bit in range(self._sizeBlock): if (num_of_block + num_of_bit) < len(information): help_data.append(information[num_of_block + num_of_bit]) block_int_values.append(bit_list_to_int(help_data)) block_int_values.append(0) # One block should be always 0 answer: list = [0] * self._countCodingBlocks while not is_kill and {True} != set(status): is_kill = True for iterator_f in range(len(decoded_set_list)): for iterator_s in range(len(decoded_set_list)): difference = decoded_set_list[ iterator_f] - decoded_set_list[iterator_s] if len(difference) == 1 and ( decoded_set_list[iterator_s] - decoded_set_list[iterator_f]) == set(): is_kill = False status[list(difference)[0]] = True answer[list(difference)[0]] = block_int_values[ iterator_f] ^ block_int_values[iterator_s] for z in range(len(decoded_set_list)): if list(difference)[0] in decoded_set_list[z]: block_int_values[z] ^= answer[list(difference) [0]] decoded_set_list[ z] = decoded_set_list[z] - difference if set(status) != {True}: log.debug( "Lacks of blocks for decoding package with fountain _coder") raise CodingException( message=CodingException.LACKS_OF_BLOCKS_FOR_DECODING.message, long_message=CodingException.LACKS_OF_BLOCKS_FOR_DECODING. long_message) # Form result in digital format answer = answer[:ceil(self.lengthInformation / self._sizeBlock)] answer.reverse() answer = [int_to_bit_list(x, self._sizeBlock) for x in answer[:-1]] + [int_to_bit_list(answer[-1])] # Unpacking answer answer = [y for x in answer for y in x] answer = answer[:self.lengthInformation] if len(answer) < self.lengthInformation: answer += [0] * (self.lengthInformation - len(answer)) return answer
def run(self): log.debug('Thread running') pass
def addToQueue(self, value): log.debug('Add to queue: %s', value) self.inQ.put(value)
def __init__(self): super().__init__() self.setup() log.debug('Thread initiated')