Best Python code snippet using avocado_python
som.py
Source:som.py  
1import sys2from csv import reader3import pygame4import math5import numpy as np6import matplotlib.pyplot as plt7# import random8hexColor = pygame.Color('#61A4BC')9title_color = pygame.Color('black')10rows = 911MATRIX_SIZE = 912MIDDLE_ROW_IDX = 413MIN_ROW_SIZE = 514EPOCHS = 1015radius = 2016colors = ['#91BAD6', '#73A5C6', '#528AAE', '#2E5984', '#1E3F66']17# parse the file received as an argument18def get_input(filePath):19    csvRows = []20    # read CSV file21    with open(filePath) as inputFile:22        csv_reader = reader(inputFile)23        header = next(csv_reader)24        # read each row25        for row in csv_reader:26            title = row[0]27            del row[0]28            csvRows.append([title, [int(val) for val in row]])29    return header, csvRows30# euclidean distance31def euclidean_dist(x1, x2):32    return np.linalg.norm(x1-x2)33# The function receives an input vector and returns the index of the vector closest to it in som,34# and the distance between them35def get_closest_idx_vector(input_vector, matrix):36    min_val = float('inf')37    min_x, min_y = 0, 038    for i in range(MATRIX_SIZE):39        for j in range(MATRIX_SIZE):40            if matrix[i][j] is not None:41                dist = euclidean_dist(input_vector, matrix[i][j])42                # update closest details43                if dist < min_val:44                    min_val = dist45                    min_x, min_y = i, j46    return min_x, min_y, min_val47# initialize random vector, the vector size is the size of the input vectors48def initialize_random_vector(vector_len):49    random_range = 1500050    vector = np.random.randint(0, random_range, vector_len)51    return vector52# Initialize a matrix with 61 random vectors depending on the hexagonal shape,53# so that the other cells in the matrix have none54def initialize_matrix(vector_len):55    matrix = [[None for _ in range(MATRIX_SIZE)] for _ in range(MATRIX_SIZE)]56    # The top of the hexagon57    for i in range(MIDDLE_ROW_IDX + 1):58        for j in range(MIN_ROW_SIZE + i):59            matrix[i][j] = initialize_random_vector(vector_len)60    iteration = 161    # The bottom of the hexagon62    for i in range(MIDDLE_ROW_IDX + 1, MATRIX_SIZE):63        for j in range(MATRIX_SIZE - iteration):64            matrix[i][j] = initialize_random_vector(vector_len)65        iteration += 166    return matrix67# The function gets an index of hexagon and returns the indexes of the neighbors68def get_neighbors(i, j, matrix):69    neighbors = []70    # invalid index71    if not (0 <= i < MATRIX_SIZE) or not (0 <= j < MATRIX_SIZE) or matrix[i][j] is None:72        return neighbors73    # left neighbor74    if j + 1 < MATRIX_SIZE and matrix[i][j + 1] is not None:75        neighbors.append((i, j + 1))76    # right neighbor77    if j - 1 >= 0:78        neighbors.append((i, j - 1))79    # The top of the hexagon80    if i < MIDDLE_ROW_IDX:81        # top left neighbor82        if i - 1 >= 0 and j - 1 >= 0:83            neighbors.append((i - 1, j - 1))84        # top right neighbor85        if i - 1 >= 0 and matrix[i - 1][j] is not None:86            neighbors.append((i - 1, j))87        # bottom left neighbor88        if i + 1 < MATRIX_SIZE and matrix[i + 1][j] is not None:89            neighbors.append((i + 1, j))90        # bottom right neighbor91        if i + 1 < MATRIX_SIZE and j + 1 < MATRIX_SIZE and matrix[i + 1][j + 1] is not None:92            neighbors.append((i + 1, j + 1))93    # The middle row of the hexagon94    elif i == MIDDLE_ROW_IDX:95        # top left neighbor96        if i - 1 >= 0 and j - 1 >= 0:97            neighbors.append((i - 1, j - 1))98        # top right neighbor99        if i - 1 >= 0 and matrix[i - 1][j] is not None:100            neighbors.append((i - 1, j))101        # bottom left neighbor102        if i + 1 < MATRIX_SIZE and j - 1 >= 0 and matrix[i + 1][j - 1] is not None:103            neighbors.append((i + 1, j - 1))104        # bottom right neighbor105        if i + 1 < MATRIX_SIZE and matrix[i + 1][j] is not None:106            neighbors.append((i + 1, j))107    # The bottom of the hexagon108    else:109        # top left neighbor110        if i - 1 >= 0:111            neighbors.append((i - 1, j))112        # top right neighbor113        if i - 1 >= 0 and j + 1 < MATRIX_SIZE and matrix[i - 1][j + 1] is not None:114            neighbors.append((i - 1, j + 1))115        # bottom left neighbor116        if i + 1 < MATRIX_SIZE and j - 1 >= 0 and matrix[i + 1][j - 1] is not None:117            neighbors.append((i + 1, j - 1))118        # bottom right neighbor119        if i + 1 < MATRIX_SIZE and matrix[i + 1][j] is not None:120            neighbors.append((i + 1, j))121    return neighbors122# The function draws an regular polygon for drawing hexagons123def draw_regular_polygon(surface, color, vertex_count, radius, position, width=0):124    n, r = vertex_count, radius125    x, y = position126    pygame.draw.polygon(surface, color, [127        (x + r * math.cos(math.pi / 2 + 2 * math.pi * i / n), y + r * math.sin(math.pi / 2 + 2 * math.pi * i / n))128        for i in range(n)129    ], width)130    pygame.display.update()131# show hexagon map on screen132def show_screen(map_input_vectors, input_vectors):133    pygame.init()134    screen = pygame.display.set_mode([750, 500])135    screen.fill('white')136    running = True137    while running:138        for event in pygame.event.get():139            if event.type == pygame.QUIT:140                running = False141        graphic(map_input_vectors, input_vectors, screen)142# Hexagonal drawing in a particular index received as input143def draw_hexagon_by_index(i, j, color, screen):144    y, x_start = 0, 0145    # init location by index146    if i == 0:147        x_start, y = 300, 100148    elif i == 1:149        x_start, y = 280, 130150    elif i == 2:151        x_start, y = 260, 160152    elif i == 3:153        x_start, y = 240, 190154    elif i == 4:155        x_start, y = 220, 220156    elif i == 5:157        x_start, y = 240, 250158    elif i == 6:159        x_start, y = 260, 280160    elif i == 7:161        x_start, y = 280, 310162    elif i == 8:163        x_start, y = 300, 340164    # draw hexagon165    draw_regular_polygon(screen, color, 6, radius, (x_start + j * 40, y))166# The function returns the socioeconomic average of vectors mapped to hexagon167def get_avg(indexes, input_vectors):168    # if the list is empty, returns -1 (to paint the appropriate hexagon in black)169    if len(indexes) == 0:170        return -1171    sum_economy = 0172    # calculate the average173    for index in indexes:174        sum_economy += input_vectors[index][0]175    return sum_economy / len(indexes)176# The function returns the hexagonal color corresponding to the socioeconomic mean of hexagonal vectors177def get_color(avg):178    if avg == -1:179        return pygame.Color('black')180    if 0 <= avg <= 2:181        return colors[0]182    elif 2 < avg <= 4:183        return colors[1]184    elif 4 < avg <= 6:185        return colors[2]186    elif 6 < avg <= 8:187        return colors[3]188    elif 8 < avg <= 10:189        return colors[4]190# Drawing 61 hexagons as map191def graphic(map_input_vectors, input_vectors, screen):192    num_of_hexagon = 5193    add = True194    for i in range(rows):195        for j in range(num_of_hexagon):196            indexes = map_input_vectors[i][j]197            avg = get_avg(indexes, input_vectors)198            draw_hexagon_by_index(i, j, get_color(avg), screen)199        # determine the number of hexagons in each row200        if num_of_hexagon == 8 and add:201            num_of_hexagon += 1202            add = False203        elif add:204            num_of_hexagon += 1205        else:206            num_of_hexagon -= 1207# Update the som vector to bring it closer to the input vector208def update_vector(input_vector, som_vector, update_percentage):209    # go over every cell and cell and update the value according to the distance210    for i in range(len(input_vector)):211        if input_vector[i] > som_vector[i]:212            dist = input_vector[i] - som_vector[i]213            som_vector[i] += update_percentage * dist214        else:215            dist = som_vector[i] - input_vector[i]216            som_vector[i] -= update_percentage * dist217    return som_vector218# The som algorithm219def som_algorithm(input_vectors, matrix):220    for i in range(EPOCHS):221        for vector in input_vectors:222            # Getting the closet vector223            x, y, dist = get_closest_idx_vector(vector, matrix)224            updated_indexes = []225            # Update the closest vector with an update percentage of 0.8226            update_percentage = 0.8227            updated_vector = update_vector(vector, matrix[x][y], update_percentage)228            matrix[x][y] = updated_vector229            updated_indexes.append((x, y))230            # Getting the neighbors of the closest vector231            neighbors = get_neighbors(x, y, matrix)232            # Update the neighbors of the closest vector with an update percentage of 0.3233            update_percentage = 0.3234            neighbors_deg2 = []235            for n in neighbors:236                if n not in updated_indexes:237                    updated_indexes.append(n)238                    updated_vector = update_vector(vector, matrix[n[0]][n[1]], update_percentage)239                    matrix[n[0]][n[1]] = updated_vector240                    # save the neighbors of the neighbors in a list241                    neighbors_deg2.append(get_neighbors(n[0], n[1], matrix))242            flat_list_neighbors = [x for xs in neighbors_deg2 for x in xs]243            # Update the neighbors of the neighbors of the closest vector with an update percentage of 0.1244            update_percentage = 0.1245            for n in flat_list_neighbors:246                if n not in updated_indexes:247                    updated_indexes.append(n)248                    updated_vector = update_vector(vector, matrix[n[0]][n[1]], update_percentage)249                    matrix[n[0]][n[1]] = updated_vector250    # Creating a map so that in each cell we save the indexes of the vectors251    # that closest to the appropriate vector in the hexagon grid252    sum_distances = 0253    map_input_vectors = [[[] for _ in range(MATRIX_SIZE)] for _ in range(MATRIX_SIZE)]254    for i in range(len(input_vectors)):255        x, y, dist = get_closest_idx_vector(input_vectors[i], matrix)256        map_input_vectors[x][y].append(i)257        sum_distances += dist258    return map_input_vectors, sum_distances / len(input_vectors)259# Get a list of cities mapped to index i, j260def get_cities(i, j, titles, map_input_vectors):261    indexes = map_input_vectors[i][j]262    cities = []263    for index in indexes:264        cities.append(titles[index])265    return cities266# Run the algorithm several times and choose the best solution267def multiple_runs_som(vector_length, input_vectors):268    iterations_num = 10269    best_map = []270    best_matrix = []271    min_dist = float('inf')272    distances = []273    for i in range(iterations_num):274        # run som algorithm with a new random grid275        mtx = initialize_matrix(vector_length)276        map_input_vectors, avg_dist = som_algorithm(input_vectors, mtx)277        distances.append(avg_dist)278        # save best solution279        if avg_dist < min_dist:280            min_dist = avg_dist281            best_matrix = mtx282            best_map = map_input_vectors283    return best_map, best_matrix, distances284# add labels to bar chart285def add_value_label(x_list, y_list):286    for i in range(len(x_list)):287        plt.text(i, y_list[i].round(2), y_list[i].round(2), ha="center")288# Displays a graph for the averages of the distances in the various solutions289def distances_graph(distances):290    iterations = list(range(len(distances)))291    values = list(distances)292    plt.figure(figsize=(10, 5))293    # creating the bar plot294    plt.bar(iterations, values, color='maroon', width=0.4)295    add_value_label(iterations, values)296    plt.xlabel("Solution number")297    plt.ylabel("Average distances")298    plt.title("Average distances in each solution")299    plt.show()300def main():301    header, csvRows = get_input(sys.argv[1])302    vector_length = len(csvRows[0][1])303    # Mixing the input rows -- test for Section C in the exercise304    # random.shuffle(csvRows)305    # Sorting the rows by the economic index -- test for Section C in the exercise306    # csvRows = sorted(csvRows, key=lambda x: x[1][0])307    input_vectors = []308    titles = []309    # save the input vectors and the titles in arrays310    for row in csvRows:311        input_vectors.append(row[1])312        titles.append(row[0])313    # run the algorithm 10 times and get the best solution314    map_input_vectors, mtx, distances_for_graph = multiple_runs_som(vector_length, input_vectors)315    # display graph316    distances_graph(distances_for_graph)317    # show hexagon map318    show_screen(map_input_vectors, input_vectors)319    # print the cities mapped to each hexagon320    for i in range(MATRIX_SIZE):321        for j in range(MATRIX_SIZE):322            if mtx[i][j] is not None:323                print(i, j, " : ", get_cities(i, j, titles, map_input_vectors))324if __name__ == '__main__':...backend_of_ui.py
Source:backend_of_ui.py  
...204        print("back to UI")205        print(val)206        self.count = val207        self.totalfaces.setText(str(int(val))+' faces detected in video')208    def update_percentage(self,percentage):209        self.progressBar.setValue(percentage)210class ThreadClass(QtCore.QThread):211    update_progressbar = pyqtSignal(float)212    def __init__(self,temp, parent=None):213        super(ThreadClass,self).__init__(parent)214        self.temp = temp215    def run(self):216        count = vid_frame_cap.extract_to_folder(self.temp)217        print("thread complete")218        self.update_progressbar.emit(count)219class videorecog(QtCore.QThread):220    update_videorecog = pyqtSignal(str)221    update_percentage = pyqtSignal(int)222    def __init__(self,files, parent=None):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
