def change(self, target_value: int, duration: int = 0, start_value: int = None, abort_new=False): log.info( f'changing brightness to {target_value}, with duration of {duration}' ) if abort_new and self.running: return self.wait_for_stop() self.running = True asyncio.run(bulb.update()) if duration == 0: # change immediately self.perceived = target_value self.set_brightness() self.running = False return elif start_value is not None: self.perceived = start_value self.set_brightness() time.sleep(1) self.transition(target_value, duration) self.running = False
def get_run_uuid(post, API_KEY, api_url): """ Function for posting job :param post: :param API_KEY: :param api_url: :return: job run_uuid """ post_url = api_url + '/job/?api_key=' + API_KEY resp = requests.post(post_url, json=post) run_id = None if not resp.ok: log.error("Status code {}. {}".format(resp.status_code, resp.content)) else: log.info("Response OK from {}.".format(post_url)) run_id_dict = json.loads(resp.text) try: run_id = run_id_dict['run_uuid'] except KeyError: msg = "Response from {} did not contain run_uuid.".format(post_url) log.error(msg) return run_id
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 encoding(self, information: List[int]) -> List[int]: log.info("Encoding package {0} of Hamming _coder".format(information)) list_encoding_information: list = information list_encoding_information.reverse() if len(list_encoding_information) < self.lengthInformation: for x in range(self.lengthInformation - len(list_encoding_information)): list_encoding_information.append(0) list_encoding_information.reverse() code: list = [] step: int = 0 # Add checks bits for count in range(self.lengthTotal): # Check that number enter in set of number (2^n), where n is natural number if math.log2(count + 1) != int( math.log2(count + 1)) or step >= self.lengthAdditional: code.append([ list_encoding_information[count - int(math.log2(count)) - 1] ]) else: code.append([0]) step += 1 answer = [x[0] for x in code] code = np.transpose(np.array(code)) backup_info = list((np.dot(code, self._matrixTransformation) % 2)[0]) for x in range(self.lengthAdditional): answer[(1 << x) - 1] = backup_info[x] return answer
def change(self, target_value: int, duration: int, start_value: int = None, abort_new=False): log.info( f'changing color temp to {target_value}, with duration of {duration}' ) if abort_new and self.running: return self.wait_for_stop() self.running = True asyncio.run(bulb.update()) if duration == 0: self.percent = target_value self.running = False return elif start_value is not None: self.percent = target_value time.sleep(1) self.transition(target_value, duration) self.running = False
def get_api_results(post, API_KEY, api_url, results_file='results.json', run_id=None): """ Function for posting job and polling results end-point :param post: :param results_file: :param API_KEY: :param api_url: :return: results dictionary / API response """ if run_id is None: run_id = get_run_uuid(post, API_KEY=API_KEY, api_url=api_url) if run_id is not None: results_url = api_url + '/job/<run_uuid>/results/?api_key=' + API_KEY results = poller(url=results_url.replace('<run_uuid>', run_id)) with open(results_file, 'w') as fp: json.dump(obj=results, fp=fp) log.info("Saved results to {}".format(results_file)) else: results = None log.error("Unable to get results: no run_uuid from POST.") return results
def add_load_profile_inputs(flat_dict, nested_dict, path_to_load_files="../inputs/load_profiles"): """ If flat_dict has a "load_file" key (i.e. same column in csv file), then a custom load profile is added to the inputs (which is used by API even if other optional inputs are filled in, such as doe_reference_name and annual_kwh) :param flat_dict: inputs from site(s) data csv file :param nested_dict: nested_dict that has already passed through make_nested_dict (filled in single value inputs) :return: None """ if "load_file" in flat_dict.keys(): if not pd.isnull(flat_dict["load_file"] ): # case for some sites having custom load profiles fp = os.path.join(path_to_load_files, flat_dict["load_file"]) load_profile = pd.read_csv(fp, header=None, squeeze=True).tolist() load_profile = [float(v) for v in load_profile ] # numpy floats are not JSON serializable assert len(load_profile) in [8760, 17520, 35040] nested_dict['Scenario']['Site']['LoadProfile'][ 'loads_kw'] = load_profile else: log.info("Using built-in profile for Site number {}.".format( flat_dict['site_number']))
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 get_transfer_one_step(self, information: List[int]) -> TransferStatistic: transfer_statistic = Codec.TransferStatistic() current_information_state: List[int] = information.copy() log.info("Transfer package - {0}".format(current_information_state)) normalization_information: List[int] = self._coder.try_normalization( current_information_state) try: current_information_state = self._coder.encoding( normalization_information) if self._interleaver: current_information_state = self._interleaver.shuffle( current_information_state) compare_information: list = current_information_state current_information_state = self._do_noise( information=current_information_state, noise_probability=self.noiseProbability, ) transfer_statistic.based_correct_bits, transfer_statistic.based_error_bits = self._get_change_state( source_state=compare_information, current_state=current_information_state) if self._interleaver: current_information_state = self._interleaver.reestablish( current_information_state) current_information_state = self._coder.decoding( current_information_state) except CodingException: log.info("During decoding package {0} founded unrepairable".format( current_information_state)) self._information = "During decoding package founded unrepairable\n" except: # TODO the same that and method below log.info("During decoding package {0} founded unrepairable".format( current_information_state)) self._information = "During decoding package founded unrepairable\n" else: if current_information_state == normalization_information: log.info("Package {0} был успешно передан".format(information)) self._information = "Package был успешно передан\n" else: log.error( "Package {0} был повреждён при передаче передан и ошибку не удалось обнаружить" .format(current_information_state)) self._information = "Package при передаче был повреждён и не подлежит " \ "востановлению\n" # Calculate count decoded bits current_step_success_bits = self._get_different_information( current_information_state, normalization_information) transfer_statistic.quantity_successful_bits += current_step_success_bits transfer_statistic.quantity_error_bits += len( normalization_information) - current_step_success_bits transfer_statistic.current_information_state = current_information_state return transfer_statistic
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 decoding(self, information: List[int]) -> List[int]: """ Decoding of convolution coder :param information: List[int] :return: List[int] """ log.info( "Decode package {0} by convolution decoder".format(information)) info_divided_into_steps = self.__divide_into_steps(information) # Fill first step value last_step = [[0, []]] + [[self.__MAX_STEPS, []] for x in range(2**self._countRegisters - 1)] for iterator in info_divided_into_steps: now_step = [[self.__MAX_STEPS, []] for x in range(2**self._countRegisters)] number: int = 0 for info_about_vertex in last_step: vertex_step: int = self._graph[number][0][ 0] # вершина перехода distance: int = get_hamming_distance(iterator, self._graph[number][0][1]) if now_step[vertex_step][0] > last_step[number][0] + distance: now_step[vertex_step] = [ info_about_vertex[0] + distance, info_about_vertex[1] + [0] ] vertex_step: int = self._graph[number][1][ 0] # вершина перехода distance: int = get_hamming_distance(iterator, self._graph[number][1][1]) if now_step[vertex_step][0] > last_step[number][0] + distance: now_step[vertex_step] = [ info_about_vertex[0] + distance, info_about_vertex[1] + [1] ] number += 1 last_step = now_step min_answer: list = [] min_cost: int = self.__MAX_STEPS for iterator in last_step: if min_cost > iterator[0]: min_cost = iterator[0] min_answer = iterator[1] return min_answer
def encoding(self, information: list) -> list: """ TODO :param information: :return: """ log.info("Encode package {0} by convolution coder".format(information)) answer: list = [] # текущая вершина current_vertex: int = 0 for nowBit in information: answer.append(self._graph[current_vertex][nowBit][1]) current_vertex = self._graph[current_vertex][nowBit][0] # Transform [[][]...] to [] answer = [y for x in answer for y in x] return answer
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 poller(url, poll_interval=2): """ Function for polling the REopt API results URL until status is not "Optimizing..." :param url: results url to poll :param poll_interval: seconds :return: dictionary response (once status is not "Optimizing...") """ key_error_count = 0 key_error_threshold = 3 status = "Optimizing..." log.info("Polling {} for results with interval of {}s...".format( url, poll_interval)) while True: resp = requests.get(url=url, verify=False) resp_dict = json.loads(resp.content) try: status = resp_dict['outputs']['Scenario']['status'] except KeyError: key_error_count += 1 log.info('KeyError count: {}'.format(key_error_count)) if key_error_count > key_error_threshold: log.info( 'Breaking polling loop due to KeyError count threshold of {} exceeded.' .format(key_error_threshold)) break if status != "Optimizing...": break else: time.sleep(poll_interval) return resp_dict
def encoding(self, information: list): log.info("Fountain LT-_coder start coding of package {0}".format( information)) combination_blocks: list = [] information = [0] * abs(len(information) - self.lengthInformation ) + information # добавление 0 битов вначало for x in range(0, len(information), self._sizeBlock): combination_blocks.append( bit_list_to_int( information[x:min(x + self._sizeBlock, len(information))])) answer: list = [] for x in range(self._countCodingBlocks): value: int = 0 count: int = 0 for y in int_to_bit_list(self._generationBlocks[x], self._countBlocks): if y == 1: value ^= combination_blocks[count] count += 1 answer.append(int_to_bit_list(value, self._sizeBlock)) return [y for x in answer for y in x]
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
# coding=utf-8 from src.GUI.controller.main_controller import MainController from src.config.config_processor import ConfigProcessor from src.endpoint.console.app_parser import AppParser from src.endpoint.console.console_processor import ConsoleProcessor from src.endpoint.console.enum_app_mode import EnumAppMode from src.helper.error.exception.application_exception import ApplicationException from src.logger import log if __name__ == '__main__': ConfigProcessor().parse_config() try: log.info("Start program") if AppParser().app_mode == EnumAppMode.GUI: log.info("GUI mode") controller = MainController() elif AppParser().app_mode == EnumAppMode.CONSOLE: log.info("Console mode") ConsoleProcessor().transfer() log.info("End program") except Exception as error: print(error) log.critical("Unhandled exception") except: # noinspection PyBroadException print(-1) log.critical("Unhandled exception") else: raise ApplicationException("Cannot be import this as module ({0})".format(__file__))
def late(vlamp=vlc.nvl): log.info('launching late profile') vlamp.brightness.change(1, 1800, abort_new=True)
def bot_app_start(token): bot = telepot.DelegatorBot(token, [ pave_event_space()(per_chat_id(), create_open, HutPizza, timeout=300), ]) log.info("Bot started..........") MessageLoop(bot).run_as_thread()
def transfer_one_step(self, information: List[int]) -> TransferStatistic: transfer_statistic = Codec.TransferStatistic() # Разбиение на Package if self._coder.isDivIntoPackage: block_list = chanel.Chanel().divide_on_blocks( information=information, block_len=self._coder.lengthInformation) else: block_list = [information.copy()] for block in block_list: current_information: List[int] = block.copy() log.info("Transfer bits - {0}".format(current_information)) status: EnumBitTransferResult = EnumBitTransferResult.SUCCESS normalization_information: List[ int] = self._coder.try_normalization(current_information) try: current_information = self._coder.encoding( normalization_information) if self._interleaver: current_information = self._interleaver.shuffle( current_information) help_information = current_information compare_information: list = current_information current_information = self._do_noise( information=current_information, noise_probability=self.noiseProbability, ) transfer_statistic.based_correct_bits, transfer_statistic.based_error_bits = self._get_change_state( source_state=compare_information, current_state=current_information) if help_information != current_information: status = EnumBitTransferResult.REPAIR if self._interleaver: current_information = self._interleaver.reestablish( current_information) current_information = self._coder.decoding(current_information) except CodingException: status = EnumBitTransferResult.ERROR log.info( "During decoding package {0} founded cannot repair error". format(current_information)) self._information = "Package corrupted amd cannot be repair\n" else: if current_information == normalization_information: if status != EnumBitTransferResult.REPAIR: status = EnumBitTransferResult.SUCCESS log.info("Package {0} transferred successfully".format( information)) self._information = "Package transferred successfully\n" else: status = EnumBitTransferResult.SHADOW log.error( "Package {0} corrupted and impossible to repair it". format(current_information)) self._information = "Package {0} corrupted and impossible to repair it\n" # calculate changing information current_step_success_bits = self._get_different_information( current_information, normalization_information) transfer_statistic.quantity_successful_bits += current_step_success_bits transfer_statistic.quantity_error_bits += len( normalization_information) - current_step_success_bits transfer_statistic.quantity_changed_bits = transfer_statistic.based_error_bits if status == EnumBitTransferResult.ERROR: transfer_statistic.result_status = EnumPackageTransferResult.ERROR elif status == EnumBitTransferResult.SHADOW: transfer_statistic.result_status = EnumPackageTransferResult.SHADOW elif status == EnumBitTransferResult.REPAIR \ and transfer_statistic.result_status != EnumPackageTransferResult.ERROR \ and transfer_statistic.result_status != EnumPackageTransferResult.SHADOW: transfer_statistic.result_status = EnumPackageTransferResult.REPAIR else: transfer_statistic.result_status = EnumPackageTransferResult.SUCCESS return transfer_statistic
def sunset(vlamp=vlc.nvl): _, duration = get_sunset() log.info('running sunset profile') vlamp.color_temp.change(0, duration.seconds, abort_new=True)
results_file = 'results_S1.json' API_KEY = 'my_API_KEY' # REPLACE WITH YOUR API KEY root_url = 'https://developer.nrel.gov/api/reopt' post_url = root_url + '/v1/job/?api_key=' + API_KEY results_url = root_url + '/v1/job/<run_uuid>/results/?api_key=' + API_KEY post = json.load(open('Scenario_POST1.json')) resp = requests.post(post_url, json=post) if not resp.ok: log.error("Status code {}. {}".format(resp.status_code, resp.content)) else: log.info("Response OK from {}.".format(post_url)) run_id_dict = json.loads(resp.text) try: run_id = run_id_dict['run_uuid'] except KeyError: msg = "Response from {} did not contain run_uuid.".format(post_url) log.error(msg) raise KeyError(msg) results = poller(url=results_url.replace('<run_uuid>', run_id)) with open(results_file, 'w') as fp: json.dump(obj=results, fp=fp) log.info("Saved results to {}".format(results_file))
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