Example #1
0
def nearest_center(centers, point):

    nearest = centers[0]
    for center in centers:
        if dist(center, point) < dist(nearest, point):
            nearest = center

    return centers.index( nearest )
def nearest_center(centers, point):

    nearest = centers[0]
    for center in centers:
        if dist(center, point) < dist(nearest, point):
            nearest = center

    return centers.index(nearest)
Example #3
0
def sort_segments(segments):

	for i in xrange(len(segments)):
		for j in xrange(i,len(segments)):
			if dist(segments[i][2:],segments[i][:2]) >= dist(segments[j][2:],segments[j][:2]):
				tmp  = segments[j]
				segments[j] = segments[i]
				segments[i] = tmp
	return
def sort_segments(segments):

    for i in xrange(len(segments)):
        for j in xrange(i, len(segments)):
            if dist(segments[i][2:], segments[i][:2]) >= dist(
                    segments[j][2:], segments[j][:2]):
                tmp = segments[j]
                segments[j] = segments[i]
                segments[i] = tmp
    return
Example #5
0
def equilateral_triangle(side):

    pixs = []
    cols = []
    t1 = [-side / 2, 0]
    t2 = [side / 2, 0]
    t3 = [0, (sqrt(3) * side) / 2]

    for x in xrange(t1[0], t2[0]):
        for y in xrange(int(t3[1])):
            alt = t3[1]
            if y <= sqrt(3) * x + alt and y <= -sqrt(3) * x + alt:
                # minus y-coordinate - [0,0] is top left and pos. directions are v and >
                pixs.append([x + side, -y + side])
                col = tuple(map(lambda x: int(2.3 * x), [dist([x, y], t1), dist([x, y], t2), dist([x, y], t3)]))

                cols.append(col)
    pixs = pixs_and_cols(pixs, cols)

    return pixs
def equilateral_triangle(side):

    pixs = []
    cols = []
    t1   = [-side / 2, 0]
    t2   = [ side / 2, 0]
    t3   = [ 0, (sqrt(3) * side) / 2]

    for x in xrange(t1[0], t2[0]):
        for y in xrange(int( t3[1] )):
            alt = t3[1]
            if y <= sqrt(3) * x + alt and y <= -sqrt(3) * x + alt:
                # minus y-coordinate - [0,0] is top left and pos. directions are v and >
                pixs.append([x + side,-y + side])
                col = tuple( map( lambda x: int(2.3 * x), [ dist([x, y], t1),\
                                                            dist([x, y], t2),\
                                                            dist([x, y], t3),]))

                cols.append( col )
    pixs = pixs_and_cols(pixs, cols)

    return pixs
def k_means(data, k, sorted_centers=False):

    data = lists_to_pairs(data)
    if sorted_centers:
        data = [[x[0], x[1], dist([0, 0], [x[0], x[1]])] for x in data]
        data.sort(key=operator.itemgetter(2))
        n = len(data) - 1
        tmp_data_A = data[::]
        centers = []
        for i in xrange(k):
            tmp_data_B = tmp_data_A[:n / k]
            centers.append(random.choice(tmp_data_B))
            tmp_data_A = tmp_data_A[n / k:]
    else:
        anchor = find_center(data)
        dif = max(min_max_points(data)[2:]) / k**2
        centers = []
        for i in xrange(k):
            centers.append(
                list(anchor + array([uniform(-dif, dif),
                                     uniform(-dif, dif)])))

    classes = [[] for i in xrange(k)]
    tmp_class = []
    all_centers = list(centers)
    iteration = 0

    while tmp_class != classes:
        tmp_class = list(classes)
        classes = [[] for i in xrange(k)]

        for point in data:
            classes[nearest_center(centers, point)].append(point)

        for i, center in enumerate(centers):
            centers[i] = find_center(classes[i], center)

        iteration += 1
        all_centers.extend(centers)

    return classes, all_centers
Example #8
0
def plot_shifts(centers, k, colors, filename=''):

    iteration = len( centers ) / k - 1
    for i in xrange(k):
        tmp_centers = centers[i::k]
        values = []
        for j in xrange( iteration ):
            values.append( dist(tmp_centers[j], tmp_centers[j + 1]) )
        plt.plot(range(iteration), values, '-s', color=colors[i])

    plt.title('Differences of centroids')
    plt.xlabel('iteration $'+ str(iteration) +'$')
    plt.ylabel('$\Delta C$')
    
    if filename:
        plt.savefig('img/'+ filename +'_shifts.png')
    else:
        plt.show()
    plt.clf()

    return
def plot_shifts(centers, k, colors, filename=''):

    iteration = len(centers) / k - 1
    for i in xrange(k):
        tmp_centers = centers[i::k]
        values = []
        for j in xrange(iteration):
            values.append(dist(tmp_centers[j], tmp_centers[j + 1]))
        plt.plot(range(iteration), values, '-s', color=colors[i])

    plt.title('Differences of centroids')
    plt.xlabel('iteration $' + str(iteration) + '$')
    plt.ylabel('$\Delta C$')

    if filename:
        plt.savefig('img/' + filename + '_shifts.png')
    else:
        plt.show()
    plt.clf()

    return
Example #10
0
def k_means(data, k, sorted_centers=False):

    data        = lists_to_pairs( data )
    if sorted_centers:
        data = [[x[0], x[1], dist([0,0], [x[0],x[1]])] for x in data]
        data.sort(key=operator.itemgetter(2))
        n = len( data ) - 1
        tmp_data_A = data[::]
        centers = []
        for i in xrange(k):
            tmp_data_B = tmp_data_A[:n / k]
            centers.append( random.choice( tmp_data_B ) )
            tmp_data_A = tmp_data_A[n / k:]
    else:        
        anchor      = find_center( data )
        dif         = max( min_max_points( data )[2:]) / k**2
        centers     = []
        for i in xrange(k):
            centers.append(list(anchor + array([uniform(-dif, dif), uniform(-dif, dif)])))

    classes     = [ [] for i in xrange(k) ]
    tmp_class   = []
    all_centers = list(centers)
    iteration   = 0

    while tmp_class != classes:
        tmp_class = list(classes)
        classes   = [ [] for i in xrange(k) ]

        for point in data:
            classes[ nearest_center(centers, point) ].append( point )

        for i, center in enumerate(centers):
            centers[ i ] = find_center( classes[ i ], center )

        iteration += 1
        all_centers.extend( centers )

    return classes, all_centers