def validate_model_params(model_params, input_params): clean_model_params = {} vector_length = utils.to_float(model_params['vector_length']) if vector_length > 0: clean_model_params['vector_length'] = vector_length else: raise ModelError('Длина вектора не может быть ниже 0.') clean_model_params['alpha_x'] = utils.to_float( model_params['alpha_x']) clean_model_params['beta_y'] = utils.to_float( model_params['beta_y']) if input_params['dimensions'] == '3D': clean_model_params['gamma_z'] = utils.to_float( model_params['gamma_z']) # Not needed, but can be useful if power_capacity of a component is # a single integer, not an interval # if model_params['power_capacity'] in CAPACITORS.values(): # clean_model_params['power_capacity'] = map( # int, # re.match( # '(\d+)-(\d+)', model_params['power_capacity']).groups()) team_args = ('base_station', 'point_of_interest', 'p1', 'p2', 'center_shift', 'matrix') for name in team_args: clean_model_params[name] = json.loads(model_params[name]) return clean_model_params
def calc_anchors(self, centroids): """ Calculate anchors with the given centroids. :param centroids: centroid objects :return: string of all generated anchors rounded to 2 decimals """ anchors = centroids.copy() for i in range(anchors.shape[0]): anchors[i][0] *= utils.to_float( self.WIDTH_IN_CFG_FILE) / self.ANCHOR_DIVISION anchors[i][1] *= utils.to_float( self.HEIGHT_IN_CFG_FILE) / self.ANCHOR_DIVISION # sort anchors widths = anchors[:, 0] sorted_indices = np.argsort(widths) # write all anchor chords into a string anchors_str = '' for i in sorted_indices[:-1]: anchors_str += ('%0.2f,%0.2f, ' % (anchors[i, 0], anchors[i, 1])) # add last coords without a comma at the end anchors_str += ( '%0.2f,%0.2f' % (anchors[sorted_indices[-1:], 0], anchors[sorted_indices[-1:], 1])) return anchors_str
def parse_progress(self): month_cols = self.activity_month_cols planned_expenditure = [ utils.to_float(self.sheet.cell("%s%s" % (col, self.row + self.planned_expenditure_row))) * 1000 for col in month_cols ] planned_progress = [ utils.to_float(self.sheet.cell("%s%s" % (col, self.row + self.planned_progress_row))) for col in month_cols ] actual_expenditure = [ utils.to_float(self.sheet.cell("%s%s" % (col, self.row + self.actual_expenditure_row))) * 1000 for col in month_cols ] actual_progress = [ utils.to_float(self.sheet.cell("%s%s" % (col, self.row + self.actual_progress_row))) for col in month_cols ] progress = [] for (yy, mm), pe, pp, ae, ap in zip(fmonths, planned_expenditure, planned_progress, actual_expenditure, actual_progress): progress.append({ "year" : yy, "month" : mm, "planned_expenditure" : pe, "planned_progress" : pp, "actual_expenditure" : ae, "actual_progress" : ap, }) return progress
def action_go(self): height = self.monitor.get_value(VAR.PROPOSED_HEIGHT) angle = self.monitor.get_value(VAR.PROPOSED_ANGLE) if settings.ENABLE_MOVE_OT is False: target_height = "Height (PV: %s): <b>%.3f</b><br><br>" % ( PV.SET_HEIGHT, to_float(height)) target_angle = "Angle (PV: %s): <b>%.3f</b>" % (PV.SET_ANGLE, to_float(angle)) msg = "<b>Optics Table move disabled in settings.py</b><br><br>" + \ "The calculated target positions are:<br><br>" + \ target_height + target_angle self.dialog(msg) return self.monitor.put(PV.ACTIVE_ANGLE, 1) self.monitor.put(PV.ACTIVE_HEIGHT, 1) self.monitor.put(PV.SET_HEIGHT, to_float(height)) self.monitor.put(PV.SET_ANGLE, to_float(angle)) self.monitor.put(PV.MOVE, 1) self._timer_queue.append((None, 0)) self._timer_queue.append((PV.MOVE, 0))
def validate_model_params(model_params, input_params): clean_model_params = {} vector_length = utils.to_float(model_params['vector_length']) if vector_length > 0: clean_model_params['vector_length'] = vector_length else: raise ModelError('Длина вектора не может быть ниже 0.') clean_model_params['alpha_x'] = utils.to_float(model_params['alpha_x']) clean_model_params['beta_y'] = utils.to_float(model_params['beta_y']) if input_params['dimensions'] == '3D': clean_model_params['gamma_z'] = utils.to_float( model_params['gamma_z']) # Not needed, but can be useful if power_capacity of a component is # a single integer, not an interval # if model_params['power_capacity'] in CAPACITORS.values(): # clean_model_params['power_capacity'] = map( # int, # re.match( # '(\d+)-(\d+)', model_params['power_capacity']).groups()) team_args = ('base_station', 'point_of_interest', 'p1', 'p2', 'center_shift', 'matrix') for name in team_args: clean_model_params[name] = json.loads(model_params[name]) return clean_model_params
def action_align_to_current(self): height = self.monitor.get_value(PV.CUR_HEIGHT) angle = self.monitor.get_value(PV.CUR_ANGLE) extension = self.monitor.get_value(PV.CUR_EXTENSION) self.monitor.put(VAR.CUR_HEIGHT, to_float(height)) self.monitor.put(VAR.CUR_ANGLE, to_float(angle)) self.monitor.put(VAR.CUR_EXTENSION, to_float(extension))
def validate_model_params(self, model_params): if utils.to_float( model_params['carbon_dioxide_absorption']) < 0: raise ModelError( 'Рассчетное значение удельного поглощения углекислого газа' ' не может быть ниже 0.') if utils.to_float( model_params['oxygen_allocation']) < 0: raise ModelError( 'Рассчетное значение удельного выделения кислорода' ' не может быть ниже 0.') if utils.to_float( model_params['electricity_amount']) < 0: raise ModelError( 'Рассчетное значение необходимой электроэнергии' ' не может быть ниже 0.') if utils.to_float(model_params['peroxide_weight']) < 0: raise ModelError( 'Рассчетное значение массы пероксида не может быть ниже 0.') return { 'peroxide_name': model_params['peroxide_name'], 'peroxide_weight': utils.to_float( model_params['peroxide_weight']), 'carbon_dioxide_absorption': utils.to_float( model_params['carbon_dioxide_absorption']), 'oxygen_allocation': utils.to_float( model_params['oxygen_allocation']), 'electricity_amount': utils.to_float( model_params['electricity_amount']), 'peroxide_impurities': json.loads( model_params['peroxide_impurities'].replace("'", '"')), 'oxygen_volume_required': utils.to_float( model_params['oxygen_volume_required']) }
def transformed_data(data): N = data["N"] T = data["T"] x = data["x"] y = data["y"] xbar = data["xbar"] x_minus_xbar = torch.zeros(T) for t in range(1, T + 1): x_minus_xbar[t - 1] = to_float((x[t - 1] - xbar)) data["x_minus_xbar"] = x_minus_xbar y_linear = torch.zeros((N * T)) for n in range(1, N + 1): for t in range(1, T + 1): y_linear[(((n - 1) * T) + t) - 1] = to_float(y[n - 1][t - 1]) data["y_linear"] = y_linear
def run_pyro(site_values, data, model, transformed_data, n_samples, params): # import model, transformed_data functions (if exists) from pyro module assert model is not None, "model couldn't be imported" variablize_params(params) log_pdfs = [] n_log_probs = None for j in range(n_samples): if n_samples > 1: sample_site_values = {v: site_values[v][j] for v in site_values} else: sample_site_values = {v: float(site_values[v]) if site_values[v].shape == () else site_values[v][0] for v in site_values} #print(sample_site_values) process_2d_sites(sample_site_values) variablize_params(sample_site_values) model_trace = poutine.trace(poutine.condition(model, data=sample_site_values), graph_type="flat").get_trace(data, params) log_p = model_trace.log_pdf() if n_log_probs is None: n_log_probs = get_num_log_probs(model_trace) else: assert n_log_probs == get_num_log_probs(model_trace) #print(log_p.data.numpy()) log_pdfs.append(to_float(log_p)) return log_pdfs, n_log_probs
def apply_scale_filter(obj_img, scale_filter): """ Apply scale filter with given scale_filter object parameters. :param obj_img: image containing cropped object :param scale_filter: object containing scale parameters :return: obj_img: image with scaled object """ if scale_filter.min == scale_filter.max: factor = utils.to_float(scale_filter.min) / 100 else: factor = utils.to_float( random.randint(int(scale_filter.min), int(scale_filter.max))) / 100 logging.info(" => scale object image with factor %3.2f" % factor) obj_img = img_processing.scale_img(obj_img, factor) return obj_img
def on_save(self): try: speeds = [ to_float(x.text()) for x in [self.e1_edit, self.e2_edit, self.e3_edit, self.e4_edit] ] print('Speeds are', speeds) except: QtWidgets.QMessageBox.warning(self, "Ошибка", "Некорректный формат!") else: print(speeds) if any([ float(speeds[0]) > max_extruder_round, float(speeds[1]) > max_first_head_round, float(speeds[2]) > max_second_head_round, float(speeds[3]) > max_reciever_round ]): QtWidgets.QMessageBox.warning(self, "Ошибка", "Превышены ограничения!") else: self.open_button.setEnabled(False) self.save_button.setEnabled(False) self.warn('Загружаем в PyBoard') pyboard.config_value = [x for i in speeds for x in i] print('Config value is ', pyboard.config_value) pyboard.arg = int(self.choosen_file()) pyboard.cmd = 4 save_thread = threading.Thread(target=self.wait_for_save) save_thread.daemon = True save_thread.start()
def read_file(filename=None): """Función que lee el archivo utilizado como base de datos.""" # cabecera del archivo. header = None # leemos el contenido del archivo en bytes. lines = Path(filename or 'school_data.csv').read_bytes() # recorremos las líneas del archivos, previa decodificación del mismo de # bytes a string. for line in lines.decode().splitlines(): # convertimos el string en una lista, usando el caracter `;` como # separador. line_data = line.split(';') # si la variable `header` es igual a `None`, le asignamos el valor de # la primer línea y continuamos. if header is None: header = line_data continue # agregamos al diccionario las asignaturas, donde la clave es el nombre # de la asignatura y el valor una lista con las notas de cada trimestre. data[line_data[0]] = [to_float(x) for x in line_data[1:]]
def extract_arc(self, arc_string): """ Extract arc information and format it such that it is ready to be saved as object attributes """ start_time, end_time, subword_info, neg_log_score = to_float(arc_string.split()) start_time_s = round(start_time / TIME_SCALE_FACTOR, DECIMAL_PLACES) end_time_s = round(end_time / TIME_SCALE_FACTOR, DECIMAL_PLACES) return start_time_s, end_time_s, subword_info, neg_log_score
def handle_timer(self): while True: # self.log("timer running") time.sleep(TIMER_INTERVAL_SEC) self.timer_lock.acquire() done_list = [] for item in self.timer_action_list: # print "process item:", item target_pv = item[0] target_value = item[1] step_size = item[2] current_value = to_float(self.monitor.get_value(target_pv, 0)) new_value = current_value + step_size if step_size < 0: if new_value <= target_value: done_list.append(item) new_value = target_value else: if new_value >= target_value: done_list.append(item) new_value = target_value self.monitor.put(target_pv, new_value) self.timer_action_list = [item for item in self.timer_action_list \ if item not in done_list] self.timer_lock.release()
def validate_input_params(self, input_params): oxygen_volume = utils.to_float(input_params['oxygen_volume']) if oxygen_volume < 0: raise ModelError('Требуемый объем кислорода не может быть ' 'меньше 0.') return { 'oxygen_volume': oxygen_volume }
def parse_mega_pixels(text): """Parse Mega Pixels from text""" match=reutils.get_match(MEGA_PIXEL_REGEX, text.upper()) if match is not None: mp=utils.to_float(match[0]) return mp return None
def parse_zoom(text): """Parse Zoom from text""" match=reutils.get_match(ZOOM_REGEX, text.upper()) if match is not None: size=utils.to_float(match) return size return None
def timer_add_action(self, target_pv, target_value, duration_sec): print "TIMER ACTION ADD CALLED FOR PV -------->", target_pv, target_value current_value = self.monitor.get_value(target_pv) diff = to_float(target_value) - (current_value) steps = to_float(duration_sec) / to_float(TIMER_INTERVAL_SEC) step_size = diff / steps self.timer_lock.acquire() # Get rid of any existing entries for this PV self.timer_action_list = [item for item in self.timer_action_list \ if item[0] != target_pv] self.timer_action_list.append((target_pv, target_value, step_size)) self.timer_lock.release()
def parse_screen_size(text): """Parse ScreenSize from text""" match=reutils.get_match(SCREEN_SIZE_REGEX, text.upper()) if match is not None: size=utils.to_float(match[0]) return size return None
def action_go(self): """ Move the current cam pos to the proposed position """ height = self.monitor.get_value(VAR.CUR_HEIGHT) angle = self.monitor.get_value(VAR.CUR_ANGLE) extension = self.monitor.get_value(VAR.CFG_EXTENSION) if settings.ENABLE_MOVE_CP is False: target_height = "Height (PV: %s): <b>%.3f</b><br><br>" % ( PV.SET_HEIGHT, to_float(height)) target_angle = "Angle (PV: %s): <b>%.3f</b><br><br>" % ( PV.SET_ANGLE, to_float(angle)) target_ext = "Extension (PV: %s): <b>%.3f</b><br><br>" % ( PV.SET_EXTENSION, to_float(extension)) msg = "<b>Camera Positioner move disabled in settings.py</b><br><br>" + \ "The calculated target positions are:<br><br>" + \ target_height + target_angle + target_ext self.dialog(msg) return self.monitor.put(PV.ACTIVE_ANGLE, 1) self.monitor.put(PV.ACTIVE_HEIGHT, 1) self.monitor.put(PV.ACTIVE_EXTENSION, 1) self.monitor.put(VAR.CUR_EXTENSION, to_float(extension)) self.monitor.put(PV.SET_HEIGHT, to_float(height)) self.monitor.put(PV.SET_ANGLE, to_float(angle)) self.monitor.put(PV.SET_EXTENSION, to_float(extension)) self.monitor.put(PV.MOVE, 1) self._timer_queue.append((None, 0)) self._timer_queue.append((PV.MOVE, 0))
def put_float(self, pv_name, value, source='unknown'): try: validated = to_float(value) self.monitor.put(pv_name, validated) return True except Exception, e: self.log("Non float value '%s' from %s to %s" % (repr(value), source, pv_name))
def parse_storage_size(text): """Parse Storage Size from text""" match=reutils.get_match(STORAGE_SIZE_PREGEX, text.upper()) if match is not None: size=utils.to_float(match[0]) unit=match[1] if unit in STORAGE_SIZE_MULTIPLIERS: return size*STORAGE_SIZE_MULTIPLIERS[unit] return None
def change_bcg(img, brightness=0, contrast=0, gamma=0.0): """ Change brightness, contrast and gamma of the given image. :param img: image, which BCG values should be changed :param brightness: new value for brightness :param contrast: new value for contrast :param gamma: new value for gamma :return: img_converted: result image with changed BCG values """ brightness = utils.to_int(brightness) contrast = utils.to_int(contrast) gamma = utils.to_float(gamma) # split BGR image to separate arrays if img.shape[2] > 3: b_img, g_img, r_img, alpha = cv2.split(img) else: b_img, g_img, r_img = cv2.split(img) # manipulate each channel if brightness != 0: b_img = cv2.LUT(b_img, brightness_conversion_lut(brightness)) g_img = cv2.LUT(g_img, brightness_conversion_lut(brightness)) r_img = cv2.LUT(r_img, brightness_conversion_lut(brightness)) if contrast != 0: b_img = cv2.LUT(b_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) g_img = cv2.LUT(g_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) r_img = cv2.LUT(r_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) if gamma != 0.0: b_img = cv2.LUT(b_img, gamma_conversion_lut(gamma*2)) g_img = cv2.LUT(g_img, gamma_conversion_lut(gamma*2)) r_img = cv2.LUT(r_img, gamma_conversion_lut(gamma*2)) # merge channels to colored picture img_converted = merge_bgr_channels(b_img, g_img, r_img) # add alpha channel if existent if img.shape[2] > 3: img_converted = cv2.merge((img_converted, img[:, :, 3])) return img_converted
def action_align_target_to_beam(self, target_angle_pv, target_height_pv): """ Align the "target" (beam or detector line of sight) to the beam """ # First get angle of the beam beam_angle = self.monitor.get_value(CORE_VAR.BEAM_ANGLE_PROPOSED) beam_disp = self.monitor.get_value(CORE_VAR.BEAM_VDISP_PROPOSED) if None in [beam_angle, beam_disp]: raise ValueError( "Cannot align camera positioner.<br>Beam position unknown.") # What is the laser angle" target_angle = to_float(self.monitor.get_value(target_angle_pv)) stage_angle = beam_angle - target_angle self.monitor.put(VAR.CUR_ANGLE, stage_angle) # Next we must set extension extension = to_float(self.monitor.get_value(VAR.CFG_EXTENSION)) self.monitor.put(VAR.CUR_EXTENSION, extension) stage_height = self.monitor.get_value(VAR.CUR_HEIGHT) target_height = self.monitor.get_value(target_height_pv) # Now get the line start/stop coordinates sx, sz, fx, fz = self.compute_line_position(stage_height, stage_angle, extension, target_height, target_angle) target_line = LineGeneric(sx, sz, fx, fz) target_height_at_mrt = target_line.get_height(settings.X_MM_MRT) sx = settings.BEAM_ORIGIN_X sz = settings.BEAM_ORIGIN_Z + beam_disp fx = sx + math.cos(to_rad(beam_angle)) fz = sz + math.sin(to_rad(beam_angle)) beam_line = LineGeneric(sx, sz, fx, fz) beam_height_at_mrt = beam_line.get_height(settings.X_MM_MRT) height_diff = beam_height_at_mrt - target_height_at_mrt stage_height += height_diff self.monitor.put(VAR.CUR_HEIGHT, stage_height)
def validate_model_params(self, model_params): blend = model_params['oxidizer'], model_params['fuel'] if blend not in FUEL_RECIPES: raise ModelError("Выбранная вами топливная смесь непригодна" " для использования в ракетном двигателе.") if utils.to_float(model_params['combustion_heat']) < 0: raise ModelError("Рассчетное значение теплоты сгорания" " не может быть ниже 0.") if utils.to_float(model_params['radicals_amount']) < 0: raise ModelError( "Рассчетное значение образования свободных радикалов" " не может быть ниже 0.") return { 'oxidizer': model_params['oxidizer'], 'fuel': model_params['fuel'], 'combustion_heat': utils.to_float(model_params['combustion_heat']), 'radicals_amount': utils.to_float(model_params['radicals_amount']) }
def apply_overlay_filter(overlay_filter, img): """ Apply overlay filter with given overlay_filter parameters. :param overlay_filter: object containing overlay parameters :param img: passed image on which overlay filter should be applied :return: img: processed image overlayed with another image """ # get overlay image if overlay_filter.path_type == 0: # random image out of overlay_img_path overlay_img_path_list = utils.list_directory( overlay_filter.overlay_img_path, file_ext_list=['.jpg', '.png']) random_overlay_idx = random.randint(0, len(overlay_img_path_list) - 1) overlay_img_filename = overlay_img_path_list[random_overlay_idx] overlay_img_path = os.path.abspath(overlay_filter.overlay_img_path + overlay_img_filename) elif overlay_filter.path_type == 1: # overlay image path specified in overlay_filter.overlay_img_path overlay_img_path = overlay_filter.overlay_img_path else: logging.error("ERROR: Unknown path type (%s) of overlay filter" % overlay_filter.path_type) sys.exit(-1) # prepare intensity intensity = utils.to_float(overlay_filter.intensity / 100) # read in overlapping image overlay_img = img_processing.import_image(overlay_img_path) overlay_img = img_processing.resize_aspect_ratio_crop_image( overlay_img, img.shape[1], img.shape[0]) # filter if overlay_filter.filter == 0: # multiply img = img_processing.multiply_images(img, overlay_img, intensity) elif overlay_filter.filter == 1: # color img = img_processing.color_filter(img, overlay_img, intensity) elif overlay_filter.filter == 2: # brighten img = img_processing.brighten_filter(img, overlay_img, intensity) elif overlay_filter.filter == 3: # darken img = img_processing.darken_filter(img, overlay_img, intensity) else: logging.error("ERROR: Unknown filter (%s) of overlay filter" % overlay_filter.filter) sys.exit(-1) target_list = ['fore- and background', 'foreground', 'background'] filter_list = ['multiply', 'color', 'brighten', 'darken'] logging.info( " => apply overlay filter \'%s\' on %s with overlay image \'%s\'" % (filter_list[overlay_filter.filter], target_list[overlay_filter.target], overlay_img_path)) return img
def validate_model_params(self, model_params): blend = model_params['oxidizer'], model_params['fuel'] if blend not in FUEL_RECIPES: raise ModelError( "Выбранная вами топливная смесь непригодна" " для использования в ракетном двигателе.") if utils.to_float(model_params['combustion_heat']) < 0: raise ModelError( "Рассчетное значение теплоты сгорания" " не может быть ниже 0.") if utils.to_float(model_params['radicals_amount']) < 0: raise ModelError( "Рассчетное значение образования свободных радикалов" " не может быть ниже 0.") return { 'oxidizer': model_params['oxidizer'], 'fuel': model_params['fuel'], 'combustion_heat': utils.to_float(model_params['combustion_heat']), 'radicals_amount': utils.to_float(model_params['radicals_amount']) }
def validate_components(self, components): water_quality = utils.to_float(components['water_quality']) # !!!IMPORTANT!!! # I assume that water_quality is in [0;100] diapason. # If it is in [0;1] just comment next line and change # the ModelError text. water_quality /= 100 if not (0 < water_quality < 1): raise ModelError( 'Качество воды должно лежать в диапазоне [0;100] процентов.') return {'water_quality': water_quality}
def check_aligned(self, pv_name): aligned = True try: val1 = self.monitor.get_value(VAR.PROPOSED_ANGLE) val2 = self.monitor.get_value(PV.ACT_ANGLE) if abs(to_float(val1) - to_float(val2)) > 0.01: raise ValueError("angle not aligned") val1 = self.monitor.get_value(VAR.PROPOSED_HEIGHT) val2 = self.monitor.get_value(PV.ACT_HEIGHT) if abs(to_float(val1) - to_float(val2)) > 0.01: raise ValueError("height not aligned") except Exception, e: # print str(e) aligned = False
def check_aligned(self, pv_name): # print "CP check_aligned() called" aligned = True try: val1 = self.monitor.get_value(VAR.CUR_EXTENSION) val2 = self.monitor.get_value(PV.CUR_EXTENSION) if abs(to_float(val1) - to_float(val2)) > 0.01: raise ValueError("extension not aligned") val1 = self.monitor.get_value(VAR.CUR_HEIGHT) val2 = self.monitor.get_value(PV.CUR_HEIGHT) if abs(to_float(val1) - to_float(val2)) > 0.01: raise ValueError("height not aligned") val1 = self.monitor.get_value(VAR.CUR_ANGLE) val2 = self.monitor.get_value(PV.CUR_ANGLE) if abs(to_float(val1) - to_float(val2)) > 0.01: raise ValueError("angle not aligned") except Exception, e: # print str(e) aligned = False
def apply_translate_filter(translate_filter): """ Apply translate filter with given translate_filter object parameters. :param translate_filter: object containing translate parameters :return: x_offset_factor, y_offset_factor: x and y translation values """ if translate_filter.x_min == translate_filter.x_max: x_offset_factor = utils.to_float(translate_filter.x_min) / 100 else: x_offset_factor = utils.to_float( random.randint(translate_filter.x_min, translate_filter.x_max)) / 100 if translate_filter.y_min == translate_filter.y_max: y_offset_factor = utils.to_float(translate_filter.y_min) / 100 else: y_offset_factor = utils.to_float( random.randint(translate_filter.y_min, translate_filter.y_max)) / 100 logging.info(" => translate by x: %s and y: %s" % (x_offset_factor, y_offset_factor)) return x_offset_factor, y_offset_factor
def change_contrast(img, contrast=0): contrast = utils.to_int(contrast) # split BGR image to separate arrays if img.shape[2] > 3: b_img, g_img, r_img, alpha = cv2.split(img) else: b_img, g_img, r_img = cv2.split(img) if contrast != 0: b_img = cv2.LUT(b_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) g_img = cv2.LUT(g_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) r_img = cv2.LUT(r_img, contrast_conversion_lut(utils.to_float(contrast+100)/100, 100)) # merge channels to colored picture img_converted = merge_bgr_channels(b_img, g_img, r_img) # add alpha channel if existent if img.shape[2] > 3: img_converted = cv2.merge((img_converted, img[:, :, 3])) return img_converted
def validate_model_params(self, model_params): orbit_radius = utils.to_float(model_params['orbit_radius']) if orbit_radius <= 0: raise ModelError('Проектный радиус орбиты должен быть больше 0.') pos_crit_accel = utils.to_float(model_params['pos_crit_accel']) if pos_crit_accel <= 0: raise ModelError('Критическое нормальное положительное ускорение ' 'должно быть больше 0.') neg_crit_accel = utils.to_float(model_params['neg_crit_accel']) if neg_crit_accel <= 0: raise ModelError('Критическое нормальное отрицательное ускорение ' 'должно быть больше 0.') permissible_variation = utils.to_int('model_params') return { 'orbit_radius': orbit_radius, 'pos_crit_accel': pos_crit_accel, 'neg_crit_accel': neg_crit_accel, 'permissible_variation': permissible_variation }
def apply_clip_filter(obj_img, clip_filter): """ Apply clip filter with given clip_filter object parameters. :param obj_img: image containing cropped object :param clip_filter: object containing clip parameters :return: obj_img: image with clipped object """ if clip_filter.x_min == clip_filter.x_max: x_factor = utils.to_float(clip_filter.x_min / 100) else: x_factor = utils.to_float( (random.randint(clip_filter.x_min, clip_filter.x_max)) / 100) if clip_filter.y_min == clip_filter.y_max: y_factor = utils.to_float(clip_filter.y_min / 100) else: y_factor = utils.to_float( (random.randint(clip_filter.y_min, clip_filter.y_max)) / 100) obj_img = img_processing.clip_img(obj_img, x_factor, y_factor) return obj_img
def pre_production_without_control(self, model_params): ''' model_params: psi - in degrees u - in degrees phi - in degrees ''' clean_model_params = {} for key, val in model_params.items(): if key == 'single_solution': clean_model_params[key] = (val == 'True') elif key in ('psi', 'u', 'phi'): clean_model_params[key] = utils.to_float(val) elif key == 'u_domain': pass else: clean_model_params[key] = numpy.matrix(val).T player_angles = [ clean_model_params['psi'], clean_model_params['u'], clean_model_params['phi'] ] random.seed(self.team_specific_num) rotation_packs = ROTATION_PACKS[:] first_rotation_pack, second_rotation_pack = random.shuffle( rotation_packs)[:2] random.seed() real_points = [ clean_model_params['user_point'], clean_model_params['first_key'], clean_model_params['second_key'] ] first_package = Package(first_rotation_pack, real_points=real_points) max_angle_diff, work_correctness = self._max_angle_diff( player_angles, first_package.rotation_pack['rotation_angles']) quality = 100 - 10 * max_angle_diff if quality < 0: quality = 0 interm_params = ({ 'critical_error_handling': 'low', 'work_correctness': work_correctness }, { 'quality': quality }) return interm_params
def pre_production_without_control(self, model_params): ''' model_params: psi - in degrees u - in degrees phi - in degrees ''' clean_model_params = {} for key, val in model_params.items(): if key == 'single_solution': clean_model_params[key] = (val == 'True') elif key in ('psi', 'u', 'phi'): clean_model_params[key] = utils.to_float(val) elif key == 'u_domain': pass else: clean_model_params[key] = numpy.matrix(val).T player_angles = [ clean_model_params['psi'], clean_model_params['u'], clean_model_params['phi']] random.seed(self.team_specific_num) rotation_packs = ROTATION_PACKS[:] first_rotation_pack, second_rotation_pack = random.shuffle( rotation_packs)[:2] random.seed() real_points = [ clean_model_params['user_point'], clean_model_params['first_key'], clean_model_params['second_key']] first_package = Package(first_rotation_pack, real_points=real_points) max_angle_diff, work_correctness = self._max_angle_diff( player_angles, first_package.rotation_pack['rotation_angles']) quality = 100 - 10 * max_angle_diff if quality < 0: quality = 0 interm_params = ( { 'critical_error_handling': 'low', 'work_correctness': work_correctness}, {'quality': quality}) return interm_params
def validate_model_params(self, model_params): orbit_radius = utils.to_float(model_params['orbit_radius']) if orbit_radius <= 0: raise ModelError('Проектный радиус орбиты должен быть больше 0.') pos_crit_accel = utils.to_float(model_params['pos_crit_accel']) if pos_crit_accel <= 0: raise ModelError( 'Критическое нормальное положительное ускорение ' 'должно быть больше 0.') neg_crit_accel = utils.to_float(model_params['neg_crit_accel']) if neg_crit_accel <= 0: raise ModelError( 'Критическое нормальное отрицательное ускорение ' 'должно быть больше 0.') permissible_variation = utils.to_int('model_params') return { 'orbit_radius': orbit_radius, 'pos_crit_accel': pos_crit_accel, 'neg_crit_accel': neg_crit_accel, 'permissible_variation': permissible_variation}
def model(data, params): N = data["N"] T = data["T"] x = data["x"] y = data["y"] xbar = data["xbar"] x_minus_xbar = data["x_minus_xbar"] y_linear = data["y_linear"] alpha = params["alpha"] beta = params["beta"] mu_alpha = params["mu_alpha"] mu_beta = params["mu_beta"] sigmasq_y = params["sigmasq_y"] sigmasq_alpha = params["sigmasq_alpha"] sigmasq_beta = params["sigmasq_beta"] # { pred = torch.zeros((N * T)) for n in range(1, N + 1): for t in range(1, T + 1): pred[(((n - 1) * T) + t) - 1] = to_float( _call_func( "fma", [beta[n - 1], x_minus_xbar[t - 1], alpha[n - 1]])) mu_alpha = _pyro_sample(mu_alpha, "mu_alpha", "normal", (to_variable(0), to_variable(100))) mu_beta = _pyro_sample(mu_beta, "mu_beta", "normal", (to_variable(0), to_variable(100))) sigmasq_y = _pyro_sample(sigmasq_y, "sigmasq_y", "inv_gamma", (to_variable(0.001), to_variable(0.001))) sigmasq_alpha = _pyro_sample(sigmasq_alpha, "sigmasq_alpha", "inv_gamma", (to_variable(0.001), to_variable(0.001))) sigmasq_beta = _pyro_sample(sigmasq_beta, "sigmasq_beta", "inv_gamma", (to_variable(0.001), to_variable(0.001))) sigma_alpha = _call_func("sqrt", [sigmasq_alpha]) alpha = _pyro_sample(alpha, "alpha", "normal", (mu_alpha, sigma_alpha)) sigma_beta = _call_func("sqrt", [sigmasq_beta]) beta = _pyro_sample(beta, "beta", "normal", (mu_beta, sigma_beta)) sigma_y = _call_func("sqrt", [sigmasq_y]) y_linear = _pyro_sample(y_linear, "y_linear", "normal", (pred, sigma_y), obs=y_linear)
def format_value(self, var_name, value): print "FORMAT VALUE CALLED FOR VAR %s VAL %s" % (var_name, value) data = self.editMap.get(var_name) fmt = data[1] if fmt is None: # Must be a string try: display = unicode(value).strip() except: display = unicode("") else: print "THIS IS THE FMT", fmt, value # display = fmt.format(value) try: value = to_float(value) display = fmt.format(value) except Exception, e: print "Error formatting float", str(e), var_name, value display = unicode("")
def change_gamma(img, gamma=0.0): gamma = utils.to_float(gamma) # split BGR image to separate arrays if img.shape[2] > 3: b_img, g_img, r_img, alpha = cv2.split(img) else: b_img, g_img, r_img = cv2.split(img) if gamma != 0.0: b_img = cv2.LUT(b_img, gamma_conversion_lut(gamma*2)) g_img = cv2.LUT(g_img, gamma_conversion_lut(gamma*2)) r_img = cv2.LUT(r_img, gamma_conversion_lut(gamma*2)) # merge channels to colored picture img_converted = merge_bgr_channels(b_img, g_img, r_img) # add alpha channel if existent if img.shape[2] > 3: img_converted = cv2.merge((img_converted, img[:, :, 3])) return img_converted
def salt_and_pepper_noise(img, amount=0.005): """ Add salt and pepper noise to the given image in the given amount. :param img: image which needs to be overlayed by noise :param amount: intensity of noise :return: image overlayed by noise """ amount = utils.to_float(amount) # Ratio of salt and pepper s_vs_p = 0.5 # Salt num_salt = np.ceil(amount * img.size * s_vs_p) coords = [np.random.randint(0, i - 1, utils.to_int(num_salt)) for i in img.shape] img[coords[0], coords[1], :3] = 255 # only write on channels 0-2, not on alpha channel # Pepper num_pepper = np.ceil(amount * img.size * (1. - s_vs_p)) coords = [np.random.randint(0, i - 1, utils.to_int(num_pepper)) for i in img.shape] img[coords[0], coords[1], :3] = 0 # only write on channels 0-2, not on alpha channel return img
def expenditure_to_date_current(self): col = self.findcell("Expenditure 2013/14") return utils.to_float(self.sheet.cellxy(col, self.row)) * 1000
def allocated_budget(self): col = self.findcell("Allocated Budget 2013/14") return utils.to_float(self.sheet.cellxy(col, self.row)) * 1000
def prev_year_expenditure(self): col = self.findcell("Total Expenditure (Previous Financial Year)") return utils.to_float(self.sheet.cellxy(col, self.row)) * 1000
def total_anticipated_cost(self): col = self.findcell("Total Anticipated Project Cost") return utils.to_float(self.sheet.cellxy(col, self.row)) * 1000
def expenditure_to_date(self): return utils.to_float(self.sheet.cell("K%s" % self.row)) * 1000
def allocated_budget(self): return utils.to_float(self.sheet.cell("G%s" % self.row)) * 1000
def prev_year_expenditure(self): return utils.to_float(self.sheet.cell("F%s" % self.row)) * 1000
def total_anticipated_cost(self): return utils.to_float(self.sheet.cell("E%s" % self.row)) * 1000
def pre_production_with_control(self, model_params): ''' model_params: first_package: psi - in degrees u - in degrees phi - in degrees single_solution - True / False second_package: psi - in degrees u - in degrees phi - in degrees single_solution - True / False ''' clean_model_params = {'first_package': {}, 'second_package': {}} for pack_name, pack_dict in clean_model_params.items(): for key, val in model_params[pack_name].items(): if key == 'single_solution': pack_dict[key] = (val == 'True') elif key in ('psi', 'u', 'phi'): pack_dict[key] = utils.to_float(val) elif key == 'u_domain': pass else: pack_dict[key] = numpy.matrix(val).T first_pack_answers = clean_model_params['first_package'] second_pack_answers = clean_model_params['second_package'] if not first_pack_answers['single_solution']: return ( {'critical_error_handling': 'low', 'work_correctness': 'Not enough'}, {'quality': 0}) if (first_pack_answers['single_solution'] and not second_pack_answers['single_solution']): short_model_params = model_params['first_package'] short_model_params.pop('single_solution') answer = self.pre_production_without_control(short_model_params) if answer['work_correctness'] == 'OK': answer['critical_error_handling'] = 'high' return answer random.seed(self.team_specific_num) rotation_packs = ROTATION_PACKS[:] first_rotation_pack, second_rotation_pack = random.shuffle( rotation_packs)[:2] random.seed() first_real_points = [ clean_model_params['first_package']['user_point'], clean_model_params['first_package']['first_key'], clean_model_params['first_package']['second_key']] second_real_points = [ clean_model_params['second_package']['user_point'], clean_model_params['second_package']['first_key'], clean_model_params['second_package']['second_key']] first_package = Package(first_rotation_pack, real_points=first_real_points) second_package = Package(second_rotation_pack, real_points=second_real_points) player_angles = [ first_pack_answers['psi'], first_pack_answers['u'], first_pack_answers['phi'], second_pack_answers['psi'], second_pack_answers['u'], second_pack_answers['phi']] computed_angles = ( first_package.rotation_pack['rotation_angles'] + second_package.rotation_pack['rotation_angles']) max_angle_diff, work_correctness = self._max_angle_diff( player_angles, computed_angles) quality = 100 - 10 * max_angle_diff if max_angle_diff < 11: critical_error_handling = 'high' quality += 15 else: critical_error_handling = 'low' if quality > 100: quality = 100 if quality < 0: quality = 0 open_interm_params = { 'critical_error_handling': critical_error_handling, 'work_correctness': work_correctness} if max_angle_diff < 11: open_interm_params['super-bonus'] = True return (open_interm_params, {'quality': quality})
def read_data_xml(xml_path): """ Extract all information for image generation out of an XML file at the given path. This concerns general information and filter chain information, where each of them get stored into a seperate object. :param xml_path: path to XML file :return: general_struct: object containing general information filter_chain_list: object containing filter chains """ try: tree = ET.ElementTree(file=xml_path) except FileNotFoundError: utils.logging.error("Error: Die Datei '%s' existiert nicht" % xml_path) sys.exit() data = tree.getroot() general_struct = objects.GeneralSettings() filter_chain_list = [] for child in data: # get the general information if child.tag == "general": for child2 in child: if child2.tag == "obj_path": general_struct.object_path = utils.to_str(child2.text) elif child2.tag == "bg_path": general_struct.background_path = utils.to_str(child2.text) elif child2.tag == "output_path": general_struct.output_path = utils.to_str(child2.text) elif child2.tag == "output_height": general_struct.output_height = utils.to_int(child2.text) elif child2.tag == "output_width": general_struct.output_width = utils.to_int(child2.text) elif child2.tag == "similar_path": pass elif child2.tag == "overlap_path": pass else: unknown_element(child2.tag, child.tag) # find all filters elif child.tag == "filter": # iterate through all settings by the given number for x in range(utils.to_int(child.get("num"))): # create a new filter filter_chain_struct = objects.FilterChainSettings() # extract range containing number of objects which should be placed onto each generated image if child.get("num_obj_per_img") is not None: filter_chain_struct.num_obj_per_img = child.get( "num_obj_per_img") for child2 in child: if child2.tag == "background": filter_chain_struct.background = objects.BackgroundFilter( utils.to_str(child2.get("type")), utils.to_str(child2.text)) elif child2.tag == "translate": filter_chain_struct.translate = objects.TranslateFilter( utils.to_str(child2.find('x').text), utils.to_str(child2.find('y').text)) elif child2.tag == "rotate": filter_chain_struct.rotate = objects.RotateFilter( utils.to_str(child2.text)) elif child2.tag == "scale": filter_chain_struct.scale = objects.ScaleFilter( utils.to_str(child2.text)) elif child2.tag == "clip": x_clip = utils.to_str( child2.find('x').text) if child2.find( 'x') is not None else '0:0' y_clip = utils.to_str( child2.find('y').text) if child2.find( 'y') is not None else '0:0' filter_chain_struct.clip = objects.ClipFilter( x_clip, y_clip) elif child2.tag == "noise": filter_chain_struct.noise = objects.NoiseFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "hue": filter_chain_struct.hue = objects.HueFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "saturation": filter_chain_struct.saturation = objects.SaturationFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "value": filter_chain_struct.value = objects.ValueFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "brightness": filter_chain_struct.brightness = objects.BrightnessFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "contrast": filter_chain_struct.contrast = objects.ContrastFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "gamma": filter_chain_struct.gamma = objects.GammaFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "blur": filter_chain_struct.blur = objects.BlurFilter( utils.to_str(child2.get("target")), utils.to_str(child2.text)) elif child2.tag == "add_obj": # collect filters for add_obj translate = objects.TranslateFilter( utils.to_str( child2.find("translate").find('x').text), utils.to_str( child2.find("translate").find( 'y').text)) if child2.find( "translate" ) is not None else objects.TranslateFilter( '50:50', '50:50') scale = objects.ScaleFilter( utils.to_str(child2.find("scale").text) ) if child2.find("scale") is not None else None rotate = objects.RotateFilter( utils.to_str(child2.find("rotate").text) ) if child2.find("rotate") is not None else None if child2.find("clip") is not None: clip_x_range = utils.to_str( child2.find("clip").find( 'x').text) if child2.find("clip").find( 'x') is not None else '0:0' clip_y_range = utils.to_str( child2.find("clip").find( 'y').text) if child2.find("clip").find( 'y') is not None else '0:0' clip = objects.ClipFilter(clip_x_range, clip_y_range) else: clip = None noise = objects.NoiseFilter( "1", utils.to_str(child2.find("noise").text) ) if child2.find("noise") is not None else None hue = objects.HueFilter( "1", utils.to_str(child2.find("hue").text) ) if child2.find("hue") is not None else None saturation = objects.SaturationFilter( "1", utils.to_str(child2.find("saturation").text) ) if child2.find("saturation") is not None else None value = objects.ValueFilter( "1", utils.to_str(child2.find("value").text) ) if child2.find("value") is not None else None brightness = objects.BrightnessFilter( "1", utils.to_str(child2.find("brightness").text) ) if child2.find("brightness") is not None else None contrast = objects.ContrastFilter( "1", utils.to_str(child2.find("contrast").text) ) if child2.find("contrast") is not None else None gamma = objects.GammaFilter( "1", utils.to_str(child2.find("gamma").text) ) if child2.find("gamma") is not None else None blur = objects.BlurFilter( "1", utils.to_str(child2.find("blur").text) ) if child2.find("blur") is not None else None overlay = objects.OverlayFilter( utils.to_str(child2.find("overlay").get("filter")), "1", utils.to_float( child2.find("overlay").get("intensity")), utils.to_str( child2.find("overlay").find( "overlay_img_path").get("path_type")), utils.to_str( child2.find("overlay").find( "overlay_img_path").text)) if child2.find( "overlay") is not None else None filter_chain_struct.add_obj = objects.AddObjectFilter( num_obj_range_str=utils.to_str(child2.get("num")), path_type=utils.to_str( child2.find("add_obj_img_path").get( "path_type")), add_obj_path=utils.to_str( child2.find("add_obj_img_path").text), translate=translate, scale=scale, rotate=rotate, clip=clip, noise=noise, hue=hue, saturation=saturation, value=value, brightness=brightness, contrast=contrast, gamma=gamma, blur=blur, overlay=overlay) elif child2.tag == "overlap": scale = objects.ScaleFilter( utils.to_str(child2.find("scale").text) ) if child2.find("scale") is not None else None rotate = objects.RotateFilter( utils.to_str(child2.find("rotate").text) ) if child2.find("rotate") is not None else None noise = objects.NoiseFilter( "1", utils.to_str(child2.find("noise").text) ) if child2.find("noise") is not None else None hue = objects.HueFilter( "1", utils.to_str(child2.find("hue").text) ) if child2.find("hue") is not None else None saturation = objects.SaturationFilter( "1", utils.to_str(child2.find("saturation").text) ) if child2.find("saturation") is not None else None value = objects.ValueFilter( "1", utils.to_str(child2.find("value").text) ) if child2.find("value") is not None else None brightness = objects.BrightnessFilter( "1", utils.to_str(child2.find("brightness").text) ) if child2.find("brightness") is not None else None contrast = objects.ContrastFilter( "1", utils.to_str(child2.find("contrast").text) ) if child2.find("contrast") is not None else None gamma = objects.GammaFilter( "1", utils.to_str(child2.find("gamma").text) ) if child2.find("gamma") is not None else None blur = objects.BlurFilter( "1", utils.to_str(child2.find("blur").text) ) if child2.find("blur") is not None else None overlay = objects.OverlayFilter( utils.to_str(child2.find("overlay").get("filter")), "1", utils.to_float( child2.find("overlay").get("intensity")), utils.to_str( child2.find("overlay").find( "overlay_img_path").get("path_type")), utils.to_str( child2.find("overlay").find( "overlay_img_path").text)) if child2.find( "overlay") is not None else None filter_chain_struct.overlap = objects.OverlapFilter( type=utils.to_str(child2.get("type")), path_type=utils.to_str( child2.find("overlap_img_path").get( "path_type")), overlap_img_path=utils.to_str( child2.find("overlap_img_path").text), x_pct_range=utils.to_str( child2.find("x_percentage").text), y_pct_range=utils.to_str( child2.find("y_percentage").text), scale=scale, rotate=rotate, noise=noise, hue=hue, saturation=saturation, value=value, brightness=brightness, contrast=contrast, gamma=gamma, blur=blur, overlay=overlay) elif child2.tag == "overlay": filter_chain_struct.overlay = objects.OverlayFilter( utils.to_str(child2.get("filter")), utils.to_str(child2.get("target")), utils.to_float(child2.get("intensity")), utils.to_str( child2.find("overlay_img_path").get( "path_type")), utils.to_str(child2.find("overlay_img_path").text)) elif child2.tag == "resolution": filter_chain_struct.resolution = objects.ResolutionFilter( utils.to_str(child2.find('x').text), utils.to_str(child2.find('y').text)) else: unknown_element(child2.tag, child.tag) # append filter to list filter_chain_list.append(filter_chain_struct) else: unknown_element(child.tag, data) utils.logging.info("XML-Parser: object path: %s", os.path.abspath(general_struct.object_path)) utils.logging.info("XML-Parser: background path: %s", os.path.abspath(general_struct.background_path)) utils.logging.info("XML-Parser: output path: %s", os.path.abspath(general_struct.output_path)) utils.logging.info("XML-Parser: found %d filter chain(s)\n", len(filter_chain_list)) return general_struct, filter_chain_list
""" electronics.py Module to help with parsing of properties of typical electronic gadgets available in the market e.g. Tables, Flash Drives, Camera etc """ import reutils import parsers import utils import basic from parsers import parser K = utils.to_float('1024.0') ONE = utils.to_float('1.0') STORAGE_SIZE_PREGEX = '\\b([0-9,.]+) ?([K, M, G, T]B)[ ,.]' STORAGE_SIZE_UNIT_REGEX = '[K, M, G, T]B' SCREEN_SIZE_REGEX = '(\\d+\\.?\\d*) ?(INCH|")' MEGA_PIXEL_REGEX = '(\\d+\\.?\\d*)[ ,-]?(MP|MEGAPIXEL)' CONNECTORS_REGEX_MAP = { 'USB 1': 'USB[ |-]?1', 'USB 2.0': 'USB[ |-]?2(.0)?', 'USB 3.0': 'USB[ |-]?3(.0)?'} ZOOM_REGEX = '(\\d+\\.?\\d*)[x|X]' STORAGE_SIZE_MULTIPLIERS = { 'KB': ONE/(K*K), 'MB': ONE/K,