Exemplo n.º 1
0
def grasp(hyper_params : HyperParams, clusters : clt.Clusters) -> (float, float):
    
    init_time : float = time.time()
    current_time : float = 0

    result : float = 0
    best_solutions : set = set([])
    solutions_added : int = 0

    iterations : int = 0

    while iterations < hyper_params.num_iter:
        
        clusters.initialize_state()
        # Use local search to create a new solution:
        local : float = local_search(clusters, clusters.sse)
        # If can fit in the best solutions, push to it to list of best solutions
        if solutions_added < hyper_params.num_best_solutions:
            best_solutions.add(local)
            solutions_added += 1
        else:
            less_best : float = max(best_solutions)
            if local < less_best:
                best_solutions.remove(less_best)
                best_solutions.add(local)
        # Set current state to best state
        result = min(best_solutions)

        iterations += 1
        current_time = time.time()
        if current_time - init_time >= 1:
            break

    return (result, current_time - init_time)
Exemplo n.º 2
0
def checkRange():
    """
	Post: Function tests the scores to see if they are between 0-100
	"""
    data = generateClusters(50, 3, 1, 3)
    myClusters = Clusters(data, 2)
    scores = myClusters.orderedScores
    l = len(scores)

    count = 0
    try:
        for i in range(l):
            if (scores[i] <= 100 and scores[i] >= 0):
                count += 1
        Clusters(data, 2)
    except count == 150:
        return False
    return True
Exemplo n.º 3
0
def checkEmpty():
    """
	Post: Function tests if generateClusters function is given 0 clusters
	"""
    try:
        data = generateClusters(50, 3, 1, 0)
        Clusters(data, 1)
    except ValueError:
        return True
    return False
Exemplo n.º 4
0
def checkNegative():
    """
	Post: Function tests when k < 0
	"""
    data = generateClusters(50, 3, 1, 3)
    try:
        Clusters(data, -5)
    except ValueError:
        return True
    return False
Exemplo n.º 5
0
def checkZero():
    """
	Post: Function tests when k = 0
	"""
    data = generateClusters(50, 3, 1, 3)
    try:
        Clusters(data, 0)
    except ValueError:
        return True
    return False
Exemplo n.º 6
0
def simulated_annealing(hyper_params : HyperParams, clusters : clt.Clusters) -> (float, float):

    current_temp : float = hyper_params.init_temp
    
    init_time : float = time.time()
    elapsed_time : float = time.time()

    clusters.initialize_state()
    smallest : float = clusters.sse

    while current_temp > hyper_params.final_temp:

        iterations : int = 0
        while iterations < hyper_params.num_iter:

            # Disturbing the state:
            clusters.disturb()

            # Comparing the costs of the current state and the disturbed state:
            delta : float = clusters.disturbed_sse - clusters.sse

            if delta < 0 or random.random() < math.exp(-delta / current_temp):
                if clusters.disturbed_sse < smallest:
                    smallest = clusters.disturbed_sse
                clusters.accept_disturbed()

            iterations += 1
            elapsed_time = time.time()

            if elapsed_time - init_time >= 1:
                break

        # Updating the temperature:
        current_temp *= hyper_params.alpha

        elapsed_time = time.time()

        if elapsed_time - init_time >= 1:
            break

    return (smallest, elapsed_time - init_time)
Exemplo n.º 7
0
def exampleCluster(data, k):  # testing kmeans
    """
	Makes example of cluster and graphs it with its respective dimension.
	"""
    plt.style.use(["dark_background"])
    plt.rc("grid", linestyle="--", color="white", alpha=0.5)
    plt.rc("axes", axisbelow=True)

    clusters = Clusters(data, k)
    print("Completed!\n")
    clusters.printInfo()
    print()

    centroids = clusters.keys()

    d = clusters.orderedData
    threshold = 0.7  # change this value to change
    a, b = d[:int(threshold * len(d))], d[int(threshold * len(d)):]

    colors = {
        0: "green",
        1: "red",
        2: "orange",
        3: "purple",
        4: "cyan",
        5: "magenta",
        6: "pink",
        7: "yellow",
    }

    if (data.shape[1] < 4):
        print("Plotting...")
    if data.shape[1] == 2:
        plt.figure()
        plt.grid()
        plt.plot(centroids[:, 0],
                 centroids[:, 1],
                 '*',
                 c="blue",
                 mec="white",
                 ms=20,
                 zorder=3,
                 label="final")
        plt.legend(loc="upper right")

        c = 0
        for centroid in clusters:
            data = clusters[centroid]
            plt.plot(data[:, 0],
                     data[:, 1],
                     'o',
                     c=colors[c],
                     mec="white",
                     ms=7.5,
                     zorder=1)
            c += 1

        plt.xlabel("x")
        plt.ylabel("y")

        plt.figure()
        plt.grid()
        plt.xlabel("x")
        plt.ylabel("y")
        plt.plot(centroids[:, 0],
                 centroids[:, 1],
                 '*',
                 c="green",
                 mec="white",
                 ms=15,
                 zorder=3,
                 label="final")
        plt.plot(clusters.center[0],
                 clusters.center[1],
                 's',
                 c="purple",
                 mec="white",
                 ms=15,
                 zorder=1)
        plt.plot(a[:, 0],
                 a[:, 1],
                 'o',
                 c="blue",
                 mec="white",
                 ms=7.5,
                 zorder=1)
        plt.plot(b[:, 0], b[:, 1], 'o', c="red", mec="white", ms=7.5, zorder=1)

    elif data.shape[1] == 3:
        plt.figure()
        ax = plt.axes(projection="3d")
        ax.scatter3D(centroids[:, 0],
                     centroids[:, 1],
                     centroids[:, 2],
                     '*',
                     c="blue",
                     zorder=3,
                     label="final")

        c = 0
        for centroid in clusters:
            data = clusters[centroid]
            ax.scatter3D(data[:, 0],
                         data[:, 1],
                         data[:, 2],
                         c=colors[c],
                         zorder=1)
            c += 1

        plt.figure()
        ax = plt.axes(projection="3d")
        ax.scatter3D(0, 0, 0, '*', c="green", zorder=1)
        ax.scatter3D(a[:, 0], a[:, 1], a[:, 2], 'o', c="blue", zorder=1)
        ax.scatter3D(b[:, 0], b[:, 1], b[:, 2], 'o', c="red", zorder=1)

    if data.shape[1] > 3:
        for i, centroid in enumerate(clusters):
            data = clusters[centroid]
            print("Cluster " + str(i) + ": " + str(len(data)))

    if data.shape[1] <= 3:
        plt.show()

    print("Done!")
Exemplo n.º 8
0
def local_search(clusters : clt.Clusters, current_value : float) -> float:
    clusters.disturb()
    if (clusters.disturbed_sse <= current_value):
        return local_search(clusters, clusters.disturbed_sse)
    else:
        return current_value
Exemplo n.º 9
0
def get_robot_position(ts, camera):
    try:
        prev_ts = ts
        ts, blobs_list = camera.get_blobs()
        LED_positions = []
        LED_position_buffer = []
        LED_colors_buffer = []
        blob_size_buffer = []
        frame_times = list(zip(list(range(10)), list(range(10))))
        if ts != prev_ts:
            for blob in blobs_list:
                # A blob contains one lED position
                x_coord = blob[0]
                y_coord = blob[1]
                color = blob[2]
                radius = blob[3]
                LED_position_buffer.append([x_coord / 2, y_coord / 2])
                LED_colors_buffer.append(color)
                blob_size_buffer.append(int(radius / sqrt(pi) / 2) * 2)
                LED_positions = np.array(LED_position_buffer)
                LED_colors = np.array(LED_colors_buffer)
                blob_sizes = np.array(blob_size_buffer)
            if len(LED_positions) > 5:
                # Find the closest neighbors of each LED_positions
                neigh = NearestNeighbors(
                    n_neighbors=4, algorithm='ball_tree').fit(LED_positions)
                distances, indices = neigh.kneighbors(LED_positions)
                index_true = []
                index_false = []
                for i in range(len(distances)):
                    if indices[i][0] in index_false:
                        continue
                    bad_group = []
                    for j in range(1, 4):
                        if distances[i][j] < 6:
                            bad_group.append(indices[i][j])
                    index_true += [indices[i][0]]
                    index_false += bad_group

                LED_positions = LED_positions[list(set(index_true))]
                if len(LED_positions) > 3:
                    LED_colors = LED_colors[list(set(index_true))]
                    blob_sizes = blob_sizes[list(set(index_true))]
                    nbrs = NearestNeighbors(
                        n_neighbors=3, algorithm='kd_tree').fit(LED_positions)
                    indices = nbrs.kneighbors(LED_positions,
                                              return_distance=False)
                    # Group LEDs in order to create ebugs
                    valid_LEDs, LED_colors, blob_sizes, valid_cluster_index = Clusters(
                        LED_positions, indices, LED_colors, blob_sizes)
                    centers = []
                    LEDs_per_Ebug = []
                    LEDColor_per_Ebug = []
                    BlobSize_per_Ebug = []
                    radius = []
                    visited = []
                    ID = []
                    for i in valid_cluster_index:
                        if i in visited:
                            continue
                        visited.append(i)
                        buf_LEDs = valid_LEDs[np.where(
                            valid_cluster_index == i)]
                        circle_LEDs = CL.circle(buf_LEDs)
                        center = np.array(list(map(int, circle_LEDs.LS())))
                        bad_est = False
                        centers.append(center)
                        LEDs_per_Ebug.append(buf_LEDs)
                        radius.append(int(circle_LEDs.calc_R(*center).mean()))
                        LEDColor_per_Ebug.append(
                            LED_colors[np.where(valid_cluster_index == i)])
                        BlobSize_per_Ebug.append(
                            blob_sizes[np.where(valid_cluster_index == i)])
                    for i in range(len(radius)):
                        color_seq, blob_seq = CL.GetSequence(
                            LEDs_per_Ebug[i], LEDColor_per_Ebug[i],
                            BlobSize_per_Ebug[i], centers[i], radius[i], 16)
                        EbugID = CL.EbugIdDtection(color_seq,
                                                   LED_DETECTION_THRESHOLD)
                        if EbugID != -1:
                            ID.append(EbugID)
                    ebugs_list = []
                    for i in range(len(ID)):
                        ebug = {
                            "Name": ID[i],
                            "Center": centers[i],
                            "Radius": radius[i]
                        }
                        ebugs_list.append(ebug)
                    print("Ebugs data :", ebugs_list)
                    return ebugs_list
        return None
    except RuntimeError as e:
        print('Error received : ', e)
        pass
Exemplo n.º 10
0
def main(argv):
    """
	Pre: Runs the main code for the backend. This will take in the data from the front end and
	put it into a new dicitonary called newDict.

	Middle: newDict will take each ID as its keys, with each one having a valule of None. From there, the program
	will create a list that contains each ID's attributes and then will assign that list to its corresponding key in newDict.
	Each ID is then given a score based on its attributes attachted to it. The higher the score the more the song is determined
	to not belong to the playlist

	Post: At the end, the backend will give the front a finalDict, that will contain the ID of each song as its keys
	and each will have a value that is its corresponding score
	"""
    print("Running...", flush=True)
    spotify = json.loads(argv[0])
    amount = spotify["Playlist"]
    g = len(amount)
    newDict = {}
    i = 0

    #This for loop creates a new dictionary and will make the keys the ID of the songs and give
    #each key a list of the attributes that match that song
    for i in range(g):
        prop = []
        temp = spotify["Playlist"][i]
        x = temp["ID"]
        newDict[x] = None
        prop.append(temp["danceability"])
        prop.append(temp["energy"])
        prop.append(temp["key"])
        prop.append(temp["tempo"])
        prop.append(temp["valence"])
        newDict[x] = prop

    #Creates a 2d list of the of the lists of attributes that are connected to each song
    newList = []
    for key in newDict:
        newList.append(newDict[key])
    #Plots the centroids on a graph with the other data points
    converted = np.array(newList)
    std = standardized(converted)
    clusters = Clusters(std)
    centroids = clusters.keys()
    clusters.printInfo()

    d, s = clusters.orderedData, clusters.orderedScores

    #Creates a new dictionary called finalDict that, when filled, will have the IDs of the songs as the keys
    #and a score as the value to each key.
    d = d * converted.std(axis=0) + converted.mean(axis=0)

    finalDict = {}
    for i in range(g):
        temp = spotify["Playlist"][i]
        x = temp["ID"]
        finalDict[x] = None

    count = 0
    original = std * converted.std(axis=0) + converted.mean(axis=0)
    for i in range(g):
        for j in range(g):
            if (np.all(original[i] == d[j])):
                temp = spotify["Playlist"][i]
                x = temp["ID"]
                finalDict[x] = s[j]
                count += 1
    print(finalDict, flush=True)
    print("Done!", flush=True)