def __init__(self, L, M, N, R, M_grid, pm, pc, pop_size, max_gen, file_path_name, Dth, k1, w1, w2, maxdis, GA_step, VF_step, seed_number, alpha1, alpha2, alpha3): ''' :param L: 场景变长,Km :param M: 基站总数 :param N: 待选数 :param R: 基站半径 :param M_grid: 栅格数 :param pm: 变异概率 :param pc: 交叉概率 :param pop_size: 种群大小 :param max_gen: 最大迭代次数 :param Dth: 两个点的距离等于这个时既无引力又无斥力 :param k1: 感知距离系数 :param w1: 引力系数 :param w2: 斥力系数 :param maxdis: 单次移动最大距离 :param GA_step: 每GA_step步进行虚拟力引导 :param VF_step: 每VF_step步离散化操作 ''' self.L = L self.M = M self.N = N self.R = R self.M_grid = M_grid self.pm = pm self.pc = pc self.pop_size = pop_size self.max_gen = max_gen self.scence = scence(L, M, N, R, M_grid) self.Dth = Dth self.k1 = k1 self.w1 = w1 self.w2 = w2 self.maxdis = maxdis self.GA_step = GA_step self.VF_step = VF_step self.Rs = k1 * R self.alpha1 = alpha1 self.alpha2 = alpha2 self.alpha3 = alpha3 self.kdtree = kdtree(self.scence.sum_sites) para_dict = {'L':L, 'M':M, 'N':N, 'R':R, 'M_grid':M_grid, 'pm':pm, 'pc':pc, 'pop_size':pop_size, 'max_gen':max_gen, 'Dth':Dth, 'k1':k1, 'w1':w1, 'w2':w2, 'maxdis':maxdis, 'GA_step':GA_step, 'VF_step':VF_step, 'seed_number':seed_number, 'alpha1':alpha1, 'alpha2':alpha2, 'alpha3':alpha3} self.record = record(file_path_name) self.record.write_scence_para(para_dict) self.pop = [] self.bests = [0] * max_gen self.g_best = 0
def orderTree(sortedNodes, tree): global SIZE, LIST median = ceil(len(sortedNodes) / 2) - 1 # get the root by being in the middle of x-order tree = kdtree(sortedNodes[median]) orderByLevel(tree.root, sortedNodes[0:median], False, 1) # search in both sides orderByLevel(tree.root, sortedNodes[median + 1:], True, 1) #printInorder(tree.root) return tree
def databaseType(db_type: int, points): """ Returns db object depended on db type """ if db_type == 0: return pointcloud(points) elif db_type == 1: return eqlcells(points) elif db_type == 2: return kdtree(points, False, 10)
def load_favicons(self): try: self.favicons = cPickle.load(open(KDTREE_PICKLE)) except IOError: self.favicons = [] for file in os.listdir(self.favicon_path): try: r,g,b = Image.open('%s/%s' % (DIR,file)).resize((1,1), Image.ANTIALIAS).convert('RGB').load()[0,0] self.favicons.append(kdtree.P(file, self.yuv((r,g,b)))) except IOError: print 'skipping', file continue self.favicons = kdtree.kdtree(self.favicons) cPickle.dump(self.favicons, open(KDTREE_PICKLE, 'w+'))
def databaseType(db_type: int, points): """ Creates database from points according to id given and points :param points: ndarray, points xyz nx3 :param db_type: 0 = pointcloud, 1 = equalcells, 2 = kdtree :return: Database object """ if db_type == 0: return pointcloud(points) elif db_type == 1: return eqlcells(points) elif db_type == 2: return kdtree(points, False, 10)
def getkdtree(winlist, lay): # begin "normalize positions" ''' The kdtree function only accept values between 0 and 1. ''' tolerance = 0.0 t = tolerance dy = 10 sw, sh = 2000 * 10, 1000 * 10 normalized = [[(x + t) / sw, (y + dy + t) / sh, (x + w - t) / sw, (y + dy + h - t) / sh] for x, y, w, h in lay] # end "normalize positions" # begin "generate k-d tree" origin_lay = [[x, y, x + w, y + h] for x, y, w, h in lay] from kdtree import kdtree _tree, _map = kdtree(zip(normalized, winlist, origin_lay)) # end "generate k-d tree" # begin "reload old root" ''' wmctrl cannot resize some applications precisely, like gnome-terminal. The side effect is that the overall window size decreases. Reloading old root node position somehow helps prevent these windows shrink too much over time. When the k-d tree is regularized, the size of the root node will be passed to leaves. ''' p1 = _tree.position p2 = PERSISTENT_DATA.get('overall_position', None) if not None == p2: x0, y0, x1, y1 = p2 p2 = [max(1, x0), max(1, y0), min(x1, int(MaxWidthStr)), min(y1, int(MaxHeightStr))] if None == p2: PERSISTENT_DATA['overall_position'] = [i for i in p1] elif p1[0] < p2[0] or p1[1] < p2[1] or p1[2] > p2[2] or p1[3] > p2[3]: PERSISTENT_DATA['overall_position'] = [i for i in p1] else: # Root nodes pass #_tree.position = [i for i in p2] #_tree.children[0].position = [i for i in p2] #_tree.children[0].children[0].position = [i for i in p2] # end "reload old root" return _tree, _map
def main(): all_stations = get_stations() tree = kdtree(all_stations) sugg_stations_num = int(input()) for _ in range(sugg_stations_num): sugg_station_input = input().rstrip().split() sugg_station_name = sugg_station_input[0] sugg_station_x = int(sugg_station_input[1]) sugg_station_y = int(sugg_station_input[2]) sugg_station = (sugg_station_name, (sugg_station_x, sugg_station_y)) # print('knn ', knn(all_stations, sugg_station)) # print('nn_search ', nn_search(tree, sugg_station)) # print('knn_with_multiprocessing ', knn_with_multiprocessing(all_stations, sugg_station)) nearest_station_name, distance = knn_with_multiprocessing( all_stations, sugg_station) print(sugg_station_name, nearest_station_name)
def fp(self, r, elementpair=None): from kdtree import kdtree res = 0.01 if elementpair is None: lcs = self.listOfCartCoorDomain(r) lc = self.listOfCartCoor() else: lcs = self.listOfCartCoorDomain(r, elementpair[0]) lc = self.listOfCartCoor(elementpair[1]) #from math import log #N = len(lcs); q = len(lc) #print N, q # If the number of query, q, is too small # it does not worth to construct the kdtree, 3 dimensional (k = 3) # kNlogN > qN -> logN > q/k #if 3*log(N) > q: # return self.fp_bf(r) kd = kdtree(lcs) tmp = [] for c in lc: tmp = tmp + kd.rangeSearch(c, r)[1] tmp = map(lambda a: res*int(a/res), tmp) return sorted(tmp)
#!/usr/bin/env python2.4 import sys import kdtree from math import * # def dist(p,q): # """Squared distance between p and q.""" # d = 0 # for i in range(len(p)): # d += (p[i]-q[i])**2 # return sqrt( d ) inf = float( "inf" ) k = kdtree.kdtree() points = [] points_to_labels = dict() wildcard_points = list() mapping = {} for line in open( sys.argv[1] ): fields = line.split() mapping[ fields[0] ] = fields[1] for line in sys.stdin: if line.startswith( '#' ): continue fields = line.split() label = fields[0] count = fields[1]
def kd_tree(): try: from kdtree import kdtree from kdnode import kdnode print("Create Kd tree") global xs; global ys; global points; points = [] for i in range(len(xs)): newpoint = point( xs[i], ys[i] ); points.append(newpoint); maxbinsz = int( input("Enter max bin size (integer): ") ); emax = 100; tree = kdtree(maxbinsz, emax); tree.timer = 0.05; ## Plotting ## minx, miny, maxx, maxy = -2, -2, 12, 12; ## -------- ## root = tree.makeTree( points, minx, miny, maxx, maxy); print("finished") ch = 0; prev = 0; rectangles = 0; while True: print("1. for nearest neighbor"); print("0. Exit"); try: ch = int(input()) except ValueError: print("That's not an int!"); continue; if ch == 1: print("Enter: x y NN"); i = input(); i = i.split(' '); try: query = [float(i[0]), float(i[1])]; except ValueError: print("Could not convert string to float"); continue; if (prev != 0): ## Plotting ## prev.set_color('gray'); prev.set_alpha(0.4); for rect in rectangles: rect.set_color('black'); rect.set_alpha(0.05); ## -------- ## prev, rectangles = tree.queuryNNwrap(query, int(i[2])); print("finished") elif ch == 0: plt.ioff(); points = []; break; except: plt.ioff(); plt.close("all")
def kd_tree(): try: from kdtree import kdtree from kdnode import kdnode print("Create Kd tree") global xs global ys global points points = [] for i in range(len(xs)): newpoint = point(xs[i], ys[i]) points.append(newpoint) maxbinsz = int(input("Enter max bin size (integer): ")) emax = 100 tree = kdtree(maxbinsz, emax) tree.timer = 0.05 ## Plotting ## minx, miny, maxx, maxy = -2, -2, 12, 12 ## -------- ## root = tree.makeTree(points, minx, miny, maxx, maxy) print("finished") ch = 0 prev = 0 rectangles = 0 while True: print("1. for nearest neighbor") print("0. Exit") try: ch = int(input()) except ValueError: print("That's not an int!") continue if ch == 1: print("Enter: x y NN") i = input() i = i.split(' ') try: query = [float(i[0]), float(i[1])] except ValueError: print("Could not convert string to float") continue if (prev != 0): ## Plotting ## prev.set_color('gray') prev.set_alpha(0.4) for rect in rectangles: rect.set_color('black') rect.set_alpha(0.05) ## -------- ## prev, rectangles = tree.queuryNNwrap(query, int(i[2])) print("finished") elif ch == 0: plt.ioff() points = [] break except: plt.ioff() plt.close("all")