def status_flight(callsign): """This function is to get the action of the Pilot but for now I try to show using percent and some ground speeds of the track. I'm pretty sure with more check VARS can better this part""" Q_db = SQL_queries.sql_query('Get_Status', (str(callsign),)) get_status = Q_db.fetchone() status = '-' for row_pilot in get_status: try: Q_db = SQL_queries.sql_query('Get_City', (str(get_status[2]),)) city_orig = Q_db.fetchone() city_orig_point = float(city_orig[1]), float(city_orig[2]) Q_db = SQL_queries.sql_query('Get_City', (str(get_status[3]),)) city_dest = Q_db.fetchone() city_dest_point = float(city_dest[1]), float(city_dest[2]) pilot_position = get_status[8], get_status[9] total_miles = distance.distance(city_orig_point, city_dest_point).miles dist_traveled = distance.distance(city_orig_point, pilot_position).miles percent = (float(dist_traveled) / float(total_miles)) * 100.0 if percent > 105 : status = 'Diverted' return status else: if int(str(get_status[4])) == 0: if (percent >= 0.0) and (percent <= 2.0): status = 'Takeoff' if (percent >= 2.0) and (percent <= 7.0): status = 'Initial Climbing' if (percent >= 7.0) and (percent <= 10.0): status = 'Climbing' if (percent >= 10.0) and (percent <= 80.0): status = 'On Route' if (percent >= 80.0) and (percent <= 90.0): status = 'Descending' if (percent >= 90.0) and (percent <= 97.0): status = 'Initial Approach' if (97.0 <= percent <= 105.0) and (360 >= get_status[6] >= 30): status = 'Final Approach' return status else: if (0 < get_status[6] <= 30) and (percent < 1.0): status = 'Departing' if (get_status[6] > 30) and (get_status[6] < 150) and (percent < 1.0): status = 'Takeoff' if (97.0 <= percent <= 105.0) and (270 >= get_status[6] >= 30): status = 'Landed' if (get_status[6] < 30) and (percent > 99.0): status = 'Taxing to Gate' if (get_status[6] == 0) and (percent > 99.0): status = 'On Blocks' if (get_status[6] == 0) and (percent <= 1.0): status = 'Boarding' if (get_status[6] == 0) and (10.0 <= percent <= 90.0): status = 'Altern Airport' return status except: status = 'Fill Flight Plan' return status
def weighted_initial(self, working_set, mislabeled): print "Total Cluster Centroids Chosen: ", len(self.mislabeled_chosen) print len(mislabeled), " mislabeled emails remaining as possible cluster centroids" if len(mislabeled) == 0: #No more centers to select return (None, None, 'NO_CENTROIDS') else: prob, mislabeled_point = mislabeled.pop(0) # Choose most potent mislabeled email self.mislabeled_chosen.append(mislabeled_point) print "Chose the mislabeled point with z = ", prob data_y, data_x = h.compose_set(working_set) vec_data_x = vectorize_set(data_x) init_email = None init_pos = None label = None if "frequency" in self.distance_opt: min_distance = sys.maxint for i,email_indices in enumerate(vec_data_x): if None not in email_indices: # actual data current_distance = distance(email_indices, mislabeled_point, self.distance_opt) if current_distance < min_distance: init_email = data_x[i] init_pos = i min_distance = current_distance if init_email is None: print "Training emails remaining: ", len(data_x) else: label = data_y[init_pos] print "-> selected cluster centroid with label: ", label, " and distance: ", min_distance, " from mislabeled point" return (label, init_pos, init_email)
def process(points, start): qt = QuadTree(Boundary((0.0, 0.0), 1.0, 1.0), 4) for p in points: qt.add(p) travel_dist = 0 while points: print "%d treats remain..." % len(points) bsize = .02 matching = [] while not matching: boundary = Boundary.centered_on(start, bsize) matching = qt.query(boundary) bsize *= 2 best_pt, best_dist = None, 9999 for match in matching: dist = distance(start, match) if dist < best_dist: best_pt, best_dist = match, dist del points[points.index(best_pt)] qt.remove(best_pt) travel_dist += best_dist start = best_pt return travel_dist
def label(layer_name): f = file(layer_name+".npy", "a+b") A=np.load(f) # tmp=B**2 # A=B/np.sqrt(tmp.sum()) # i=1 # condtion=True # while condtion: # try: # a=np.load(f) # # tmp=a**2 # # a=a/np.sqrt(tmp.sum()) # A=np.vstack((A,a)) # # print """i=%d,""" %(i) # i=i+1; # except: # condtion=False # print "error" i=1 while i<2474: a=np.load(f) A=np.vstack((A,a)) # print """i=%d,""" %(i) i=i+1; print "OK" H=A.shape dim=H[0] # print dim # return A DIS=np.zeros((dim,dim)) i=0 while i<dim: j=0 while j<i: DIS[(i,j)]=distance.distance(A[i],A[j]) # print "i=%d,j=%d" %(i,j) j=j+1 i=i+1 # i=0 # while i<dim: # j=i+1 # while j<dim: # DIS[j,i]=DIS[i,j] # j=j+1 # i=i+1 # print DIS.shape io_dis.write_array(DIS,layer_name)
def send_place(self, osm_id): """Method for sending data to dataengine. Called from OSMHandler when place is ready for sending. Before sending counts distance from current location to place. @param osm_id: id of place @type osm_id: str """ # Send place types in categories self._provider.setProperty(self._plugin_name, "food_and_drink", self._amenity) place = self._places.search(osm_id) if place.is_complete(): # Count distance try: place.set_distance(distance(self._location.getLatitude(), self._location.getLongitude(), place.get_lat(), place.get_lon())) # If place is far away if (float(place.get_distance()) > \ (self._location.getRange() * 1000)): return # Send distance self._provider.setProperty(self._plugin_name, place.get_distance_id(), place.get_distance()) except Exception: pass # Send rest of data # Main name self._provider.setProperty(self._plugin_name, place.get_osm_id_key(), place.get_display_name()) # Type self._provider.setProperty(self._plugin_name, place.get_type_id(), place.get_type()) # Latitude and Longitude self._provider.setProperty(self._plugin_name, place.get_latlng_id(), place.get_latlng()) # Url self._provider.setProperty(self._plugin_name, place.get_url_id(), place.get_url()) # Website if place.get_website(): self._provider.setProperty(self._plugin_name, place.get_website_id(), place.get_website()) # Cuisine if place.get_cuisine(): self._provider.setProperty(self._plugin_name, place.get_cuisine_id(), place.get_cuisine()) # Opening hours if place.get_opening_hours(): self._provider.setProperty(self._plugin_name, place.get_opening_hours_id(), place.get_opening_hours()) self._provider.done(self._plugin_name)
def dist_with_pop(start, pts): best_pt, best_dist, best_idx = None, 9999, None for i, p in enumerate(pts): dist = distance(start, p) if dist < best_dist: best_pt, best_dist, best_idx = p, dist, i del pts[best_idx] return best_pt, best_dist
def update_dist_list(self, t=False): """Updates self.dist_list for the frequency method""" if t: time_1 = time.time() indices = [train[1] for train in self.dist_list] # get array of indices self.dist_list = [(distance(self.vec_data_x[i], self.cluster_word_frequency, self.opt), i) for i in indices] self.dist_list.sort() if t: time_2 = time.time() print 'update_dist_list took: ', h.sec_to_english(time_2 - time_1)
def check_distance(self, id, value): """ check if a business resides in the requested distance radius """ p1 = (self.data[id]["latitude"], self.data[id]["longitude"]) p2 = value[1] if distance(p1, p2) <= value[0]: return True else: return False
def assign_clusters(population, centroids): """ Cluster assignment step. """ for x in population: # calculate distance to each centroid distances = [distance(x.value, centroid) for centroid in centroids] # select the index (cluster id) of the closest cluster cluster, min_distance = min(enumerate(distances), key=itemgetter(1)) # assign the object to that cluster x.cluster = cluster return population
def distance_array(self, separate): """Returns a list containing the distances from each email to the center.""" if separate: # if true, all emails must be same type (spam or ham) as centroid dist_list = [] for x in range(len(self.data_y)): if self.data_y[x] == self.label and x != self.clustroid: # same type, no duplicate dist_list.append((distance(self.vec_data_x[x], self.cluster_word_frequency, self.opt), x)) dist_list.sort() # sorts tuples by first element default, the distance print "\n ----------------Generated Distance Array----------------\n" print "Distance: ", [email[0] for email in dist_list[:5]] print "Indices: ", [email[1] for email in dist_list[:5]] return dist_list
def calcScore(s, os, evaler): assert( len(s) != 0 ) rs = [] scores = [0,0,0,0,0,0] for (t, score, wid, n) in s: if score == -1: score = -2 scores[n] += score if n==1 and wid != 0: w = t[0] if w != "$": rs.append(w) if len(os) <= wid-1: scores[0] += len(w) else: scores[0] += distance.distance(w, os[wid-1]) return (linComb(scores, evaler)/len(os), scores, rs)
def totalcost(blogwords, costf, medoids_idx) : size = len(blogwords) total_cost = 0.0 medoids = {} for idx in medoids_idx : medoids[idx] = [] for i in range(size) : choice = None min_cost = 2.1 for m in medoids : tmp = distances_cache.get((m,i),None) if tmp == None : tmp = distance.distance(blogwords[m],blogwords[i]) distances_cache[(m,i)] = tmp if tmp < min_cost : choice = m min_cost = tmp medoids[choice].append(i) total_cost += min_cost return total_cost, medoids
def kmeans(blogwords, k) : min_max_per_word = [ [min([row[i] for row in blogwords]), max([row[i] for row in blogwords])] for i in range(len(blogwords[0]))] # generate k clusters randomly clusters = [] for i in range(k) : cluster = [] for min_, max_ in min_max_per_word : cluster.append(random.random() * (max_ - min_) + min_) clusters.append(cluster) #lables = [] matchs = [ [] for i in range(k)] lastmatchs = [ [] for i in range(k)] rounds = 100 while rounds > 0 : matchs = [ [] for i in range(k)] print 'round \t',rounds for i in range(len(blogwords)) : bestmatch_cluster = None min_distance = 2.1 for j in range(k) : dis = distance.distance(clusters[j], blogwords[i]) if dis < min_distance : min_distance = dis bestmatch_cluster = j matchs[bestmatch_cluster].append(i) print_matchs(matchs) print_matchs(lastmatchs) if matchs == lastmatchs : break lastmatchs = [[ item for item in matchs[i] ] for i in range(k)] #move the centroids to the average of their members for j in range(k) : avg = [0.0 for i in range(len(blogwords[0])) ] for m in matchs[j] : vec = blogwords[m] for i in range(len(blogwords[0])) : avg[i] += vec[i] avg = [ item / len(blogwords[0]) for item in avg] clusters[j] = avg rounds -= 1
def getScore(n): text = nltk.corpus.brown.sents() ss = [] wss = [] for i in xrange(n): s = [] while len(s) <= 2 or s[0][0] > "a" or s[-1] != ".": s = text[int(random.uniform(0, len(text)))] ss.append(s) ws = list(s) w = [] while len(w) <= 1 or "." in w: j = int(random.uniform(0, len(ws) - 1)) w = list(ws[j]) k = int(random.uniform(0, len(w))) c = chr(int(random.uniform(ord("a"), ord("z") + 1))) w[k] = c ws[j] = "".join(w) # print c, s[j], ws[j] assert len(s[j]) == len(ws[j]) wss.append(ws) ss = unsentences(ss) wss = unsentences(wss) css = spell.correct(wss) ss = splitSentence(ss) wss = splitSentence(wss) css = splitSentence(css) dd = 0 for (s, ws, cs) in map(None, ss, wss, css): print unwords(s) print unwords(ws) print unwords(cs) d = distance.distance(s, cs) print d print if d > 0: dd += 1 return float(dd) / n
def find( req, lat, lng ): lat = float( lat ) lng = float( lng ) bestRow = None reader = csv.reader( open( 'BenAndJerryGeo.csv', 'rb' ) ) head = reader.next() for row in reader: rlat = row[16] rlng = row[17] if rlat == '' or rlat == '***FAIL***': continue miles = distance.distance( (lat,lng), (float(rlat),float(rlng) ) ).miles if bestRow == None or bestMiles > miles: bestRow = row bestMiles = miles json = sj.dumps({ 'address': bestRow[15], 'distance': bestMiles, 'lat': float(bestRow[16]), 'lng': float(bestRow[17]) }, separators=( ',', ':' ) ) return json
def compare(fn1, fn2): f1 = open(fn1, "r") f2 = open(fn2, "r") p1 = [1] p2 = [1] d = 0 l1 = 0 l2 = 0 ns = 0 while p1 != [] and p2 != []: p1 = readparagraph(f1) p2 = readparagraph(f2) for (s1, s2) in map(None, p1, p2): ns += 1 #print s1 #print s2 dd = 0 di = 0 if s1 == None: dd = 1.0 l2 += len(s2) elif s2 == None: dd = 1.0 l1 += len(s1) else: l1 += len(s1) l2 += len(s2) dd = float(distance.distance(s1,s2))/len(s1) di = float(abs(len(s1) - len(s2))) / (len(s1) + len(s2)) d += dd #print dd, di, l1, l2 #print #if di > 0.5: # return d return (float(d)/ns, l1, l2)
def hcluster(blogwords,blognames) : biclusters = [ bicluster(vec = blogwords[i], id = i ) for i in range(len(blogwords)) ] distances = {} flag = None; currentclusted = -1 while(len(biclusters) > 1) : min_val = 2; biclusters_len = len(biclusters) for i in range(biclusters_len-1) : for j in range(i + 1, biclusters_len) : if distances.get((biclusters[i].id,biclusters[j].id)) == None: distances[(biclusters[i].id,biclusters[j].id)] = distance.distance(biclusters[i].vec,biclusters[j].vec) d = distances[(biclusters[i].id,biclusters[j].id)] if d < min_val : min_val = d flag = (i,j) bic1,bic2 = flag newvec = [(biclusters[bic1].vec[i] + biclusters[bic2].vec[i])/2 for i in range(len(biclusters[bic1].vec))] newbic = bicluster(newvec, left=biclusters[bic1], right=biclusters[bic2], distance=min_val, id = currentclusted) currentclusted -= 1 del biclusters[bic2] del biclusters[bic1] biclusters.append(newbic) return biclusters[0]
def test_one(): assert distance(0,0,1,1) == pytest.approx(1.41421, 0.00001)
def _diameter_append(self, candidate): return max([distance(candidate.value, x.value) for x in self.cluster])
f1 = open(sys.argv[1] + '_tfidf.pickle', 'r') while 1: try: all_scores.append(pickle.load(f1)) except EOFError: break f1.close() #compute new histograms with weights for idx, hist in enumerate(histograms): #TFIDF weighing hist = hist * all_scores[idx] path = sys.argv[1] im_list = imtools.get_imlist(path) dist_function = dist.distance('chisquared') temp_dist = [] all_dist = [] #print dist_function for idx, h1 in enumerate(histograms): f1 = open(sys.argv[1] + '_comparison.pickle', mode='a+b') for h2 in histograms: vector_distance = dist_function.compute_distance(h1, h2) temp_dist.append(vector_distance) cPickle.dump(temp_dist, f1) temp_dist = [] f1.close()
def area2(xc, yc, xp, yp): return area.area(distance.distance(xc, yc, xp, yp))
from distance import distance, mirror from mst import mst from time import time n = 125 m = [] for i in range(n): for j in range(n): m.append((i, j)) t = time() m = distance(m) print(time() - t) t = time() g = mst(m) l = 0 for e in g: l += m[e[0]][e[1]] print g print l print(time() - t)
def test_1(self): res = distance(0, 0, 1, 1) self.assertEqual(res, 2**0.5)
def test_distance(): '''Test whether the distance function works correctly.''' assert close(distance(1.0, 0.0, 1.0, 0.0), 0.0), 'Identical points fail.' assert close(distance(0.0, 0.0, 1.0, 0.0), 1.0), 'Unit distance fails.'
def distance_to_center(document): return distance(document.vector, self.centroid)
def test_zero(self): res = distance(0, 0, 0, 0) self.assertEqual(res, 0)
width = int(frame.shape[1] * percent / 100) height = int(frame.shape[0] * percent / 100) dim = (width, height) return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA) #top,bottom,left,right=500,550,390,800 top, bottom, left, right = 270, 350, 10, 470 centerx = (left + right) // 2 font = cv2.FONT_HERSHEY_SIMPLEX video = cv2.VideoCapture(0) forwardDrive() while True: print 'DISTANCE :', distance() if distance() < 16.0: reverseDrive() sleep(4) k = checkpath() if (k == 1): forwardDrive() elif (k == -1): forwardDrive() else: pass ret, img = video.read() if not ret: continue img = rescale_frame(img, percent=75)
def status_flight(callsign): """This function is to get the action of the Pilot but for now I try to show using percent and some ground speeds of the track. I'm pretty sure with more check VARS can better this part""" Q_db = SQL_queries.sql_query('Get_Status', (str(callsign), )) get_status = Q_db.fetchone() status = '-' for row_pilot in get_status: try: Q_db = SQL_queries.sql_query('Get_City', (str(get_status[2]), )) city_orig = Q_db.fetchone() city_orig_point = float(city_orig[1]), float(city_orig[2]) Q_db = SQL_queries.sql_query('Get_City', (str(get_status[3]), )) city_dest = Q_db.fetchone() city_dest_point = float(city_dest[1]), float(city_dest[2]) pilot_position = get_status[8], get_status[9] total_miles = distance.distance(city_orig_point, city_dest_point).miles dist_traveled = distance.distance(city_orig_point, pilot_position).miles percent = (float(dist_traveled) / float(total_miles)) * 100.0 if percent > 105: status = 'Diverted' return status else: if int(str(get_status[4])) == 0: if (percent >= 0.0) and (percent <= 2.0): status = 'Takeoff' if (percent >= 2.0) and (percent <= 7.0): status = 'Initial Climbing' if (percent >= 7.0) and (percent <= 10.0): status = 'Climbing' if (percent >= 10.0) and (percent <= 80.0): status = 'On Route' if (percent >= 80.0) and (percent <= 90.0): status = 'Descending' if (percent >= 90.0) and (percent <= 97.0): status = 'Initial Approach' if (97.0 <= percent <= 105.0) and (360 >= get_status[6] >= 30): status = 'Final Approach' return status else: if (0 < get_status[6] <= 30) and (percent < 1.0): status = 'Departing' if (get_status[6] > 30) and (get_status[6] < 150) and (percent < 1.0): status = 'Takeoff' if (97.0 <= percent <= 105.0) and (270 >= get_status[6] >= 30): status = 'Landed' if (get_status[6] < 30) and (percent > 99.0): status = 'Taxing to Gate' if (get_status[6] == 0) and (percent > 99.0): status = 'On Blocks' if (get_status[6] == 0) and (percent <= 1.0): status = 'Boarding' if (get_status[6] == 0) and (10.0 <= percent <= 90.0): status = 'Altern Airport' return status except: status = 'Fill Flight Plan' return status
# array that recording which kind of each point is included in kind_array = np.zeros(shape=(local_array.shape[0], local_array.shape[1] + 1)) kind_array[:, :-1] = local_array # clustering loop step = 0 while step < 10000: # broadcast centroid position c_pos = comm.Bcast(c_pos, root=0) # centroid position of next iteration new_c_pos = c_pos # calculation kind of each point by minimize the distance of point and corresponding centroid for ind, point in enumerate(local_array): min_distance = distance(point, c_pos[0]) kind = 0 for i in range(1, k): if min_distance > distance(point, c_pos[i]): kind = i min_distance = distance(point, c_pos[i]) kind_array[ind, -1] = kind point_num[kind] += 1 new_c_pos[kind] += point # reduce summation all_c_pos = comm.reduce(new_c_pos, root=0, op=MPI.SUM) all_point_num = comm.reduce(new_c_pos, root=0, op=MPI.SUM) if mype == 0: for i in range(k):
stg = City("Stg", 48.7758459, 9.1829321, 22) #Stuttgart ber = City("Ber", 52.521918, 13.413215, 21) #Berlin ham = City("Ham", 53.551085, 9.993682, 24) #Hamburg nür = City("Nür", 49.452030, 11.076750, 22) #Nürnberg fra = City("Fra", 50.110922, 8.682127, 23) #Frankfurt düs = City("Düs", 51.2277411, 6.7734556, 20) #Düsseldorf köl = City("Köl", 50.941278, 6.958281, 10) #Köln alleCities = [stg, ber, ham, nür, fra, düs,köl] for i in range(0,len(alleCities)): for j in range(0, len(alleCities)): c1 = alleCities[i] c2 = alleCities[j] dist = distance(c1, c2) if dist != 0: print("Der A. von %s zu %s beträgt %.1fkm" %(c1.name,c2.name,dist) ) class Meneken: def __init__(self, toDo, start, ziel, name): self.done = [] self.toDo = toDo self.distanceDone = 0 self.start = start self.ziel = ziel self.standort = start self.name = name self.sleeps = 0 def info(self): print("Hi wir bims %s, bims grad in %s, reisen von %s nach %s.W. bims schon %.1f viel km gerannt,hams %d mal übernachtet"
def is_garage_open(): return int(round(distance.distance(), 0)) < 20
audio.speak('Wooooo') motor.forward() time.sleep(.5) motor.backward() audio.speak('Great Job') time.sleep(.5) motor.forward() motor.ctrl(0) audio.speak('Much Win') quit() else: audio.speak("only found " + str(len(cards)) + " number of cards") quit() print cards while distance.distance() < 88: motor.backward() time.sleep(.05) print "stop" motor.ctrl(0) audio.speak("analyzing the dealer cards.") time.sleep(2) dealer_cards = card_img.get_cards(1) if dealer_cards: audio.speak('the dealer has a ') audio.speak_card(dealer_cards[0]) else: audio.speak('I did not find any cards for the dealer') quit()
from itertools import permutations coor_permutations = list(permutations(coor)) b = 0 least_distance_path = 0 min_distance = 10000000000 for a in range(0, len(coor_permutations)): dist = 0 d = 1 for c in range(size - 1): x1 = coor_permutations[a][c][0] y1 = coor_permutations[a][c][1] x2 = coor_permutations[a][c+1][0] y2 = coor_permutations[a][c+1][1] dist += distance.distance(x1, y1, x2, y2) if d == size - 1: x1 = coor_permutations[a][c+1][0] y1 = coor_permutations[a][c+1][1] x2 = coor_permutations[a][0][0] y2 = coor_permutations[a][0][1] dist += distance.distance(x1, y1, x2, y2) d += 1 if dist < min_distance: min_distance = dist least_distance_path = b b += 1 print(min_distance) for z in range(0, len(coor_permutations[least_distance_path])): print(coor_permutations[least_distance_path][z])
def circle_area(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp))
def animate_to(self, x, y): distance_to_left = distance(self.coords_left, (x, y)) distance_to_right = distance(self.coords_right, (x, y)) while True: pass
from distance import distance print(distance(1, 100))
def test_2(self): res = distance(0, 0, 3, 4) self.assertEqual(res, 5)
'warsaw': .07} # transform location unsorted dict to an ordered dict (needed for construcing... # following distance dict) location = OrderedDict(sorted(location.items(), key=lambda t: t[0])) demand = OrderedDict(sorted(demand.items(), key=lambda t: t[0])) # transform location to list (in alphabetical order) location_tuple = [] for keys, values in location.iteritems(): location_tuple.append(values) # caluclate distance for each city to every other city dist = defaultdict(list) for keys, values in location.iteritems(): for i in range(0,8): dist[keys].append(distance(values[0], values[1], location_tuple[i][0], location_tuple[i][1])) plotgrid(location, cities, demand) # supply = transport(dist, losses)
def status(self, callsign): self.callsign = callsign Q_db = SQL_queries.sql_query('Get_Pilot_data', (str(callsign), )) info = Q_db.fetchall() ImageFlags = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../flags') ImageAirlines = os.path.join( os.path.dirname(os.path.abspath(__file__)), '../airlines') ImageRatings = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../ratings') if info[0][19] == 'FOLME': pass else: try: Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][5]), )) flagCodeOrig = Q_db.fetchone() flagCodePath_orig = (ImageFlags + '/%s.png') % flagCodeOrig Pixmap = QPixmap(flagCodePath_orig) self.ui.DepartureImage.setPixmap(Pixmap) Q_db = SQL_queries.sql_query('Get_Airport_Location', (str(info[0][5]), )) city_orig = Q_db.fetchone() self.ui.DepartureText.setText( str(city_orig[0].encode('latin-1'))) city_orig_point = city_orig[1], city_orig[2] except: self.ui.DepartureText.setText('Pending...') city_orig_point = None try: Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][6]), )) flagCodeDest = Q_db.fetchone() flagCodePath_dest = (ImageFlags + '/%s.png') % flagCodeDest Pixmap = QPixmap(flagCodePath_dest) self.ui.DestinationImage.setPixmap(Pixmap) Q_db = SQL_queries.sql_query('Get_Airport_Location', (str(info[0][6]), )) city_dest = Q_db.fetchone() self.ui.DestinationText.setText(str( city_dest[0].encode('latin-1'))) city_dest_point = city_dest[1], city_dest[2] except: self.ui.DestinationText.setText('Pending...') city_dest_point = None self.ui.vidText.setText(str(info[0][0])) try: code_airline = callsign[:3] airlineCodePath = (ImageAirlines + '/%s.gif') % code_airline if os.path.exists(airlineCodePath) is True: Pixmap = QPixmap(airlineCodePath) airline = QLabel(self) self.ui.airline_image.setPixmap(Pixmap) else: Q_db = SQL_queries.sql_query('Get_Airline', str(callsign[:3])) airline_code = Q_db.fetchone() self.ui.airline_image.setText(str(airline_code[0])) except: pass self.ui.callsign_text.setText(callsign) self.ui.PilotNameText.setText(str(info[0][1][:-4].encode('latin-1'))) self.ui.RouteText.setText(str(info[0][9])) self.ui.GroundSpeedNumber.setText(str(info[0][3])) self.ui.AltitudeNumber.setText(str(info[0][2])) self.ui.PobText.setText(str(info[0][8])) self.ui.TransponderText.setText(str(info[0][11])) self.ui.GSFiledText.setText(str(info[0][17])) self.ui.FLText.setText(str(info[0][7])) Q_db = SQL_queries.sql_query('Get_Airport_from_ICAO', (str(info[0][15]), )) altern_city_1 = Q_db.fetchone() Q_db = SQL_queries.sql_query('Get_Airport_from_ICAO', (str(info[0][16]), )) altern_city_2 = Q_db.fetchone() if altern_city_1 is None: self.ui.Altern_Airport_Text.setText(str('-')) else: self.ui.Altern_Airport_Text.setText(str(altern_city_1[0])) if altern_city_2 is None: self.ui.Altern_Airport_Text_2.setText(str('-')) else: self.ui.Altern_Airport_Text_2.setText(str(altern_city_2[0])) try: if str(info[0][4]) != '': Q_db = SQL_queries.sql_query('Get_Model', ((info[0][4].split('/')[1]), )) data = Q_db.fetchall() self.ui.AirplaneText.setText('Model: %s Fabricant: %s Description: %s' \ % (str(data[0][0]), str(data[0][1]), str(data[0][2]))) except: self.ui.AirplaneText.setText('Pending...') Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][1][-4:]), )) flagCodeHome = Q_db.fetchone() flagCodePath = (ImageFlags + '/%s.png') % flagCodeHome Pixmap = QPixmap(flagCodePath) self.ui.HomeFlag.setPixmap(Pixmap) ratingImage = ImageRatings + '/pilot_level%d.gif' % int(info[0][10]) Pixmap = QPixmap(ratingImage) self.ui.rating_img.setPixmap(Pixmap) player_point = info[0][13], info[0][14] if city_orig_point is None or city_dest_point is None: self.ui.nauticalmiles.setText('Pending...') self.ui.progressBarTrack.setValue(0) if str(info[0][5]) == str(info[0][6]): self.ui.progressBarTrack.setValue(0) self.ui.nauticalmiles.setText('Local Flight') eta = '00:00:00.000000' else: try: total_miles = distance.distance(city_orig_point, city_dest_point).miles dist_traveled = distance.distance(city_orig_point, player_point).miles percent = float((dist_traveled / total_miles) * 100.0) eta = str( datetime.timedelta(hours=((total_miles - dist_traveled) / float(info[0][3])))) except: if city_orig_point or city_dest_point is None: percent = 0.0 eta = '00:00:00.000000' self.ui.nauticalmiles.setText( '%.1f / %.1f miles - %.1f%%' % (float(dist_traveled), float(total_miles), float(percent))) self.ui.progressBarTrack.setValue(int(percent)) status_plane = StatusFlight.status_flight(callsign) self.ui.FlightStatusDetail.setText(str(status_plane)) self.ui.ETA_Arrive.setText(str(eta)[:-7]) try: start_connected = datetime.datetime(int(str(info[0][18])[:4]), int(str(info[0][18])[4:6]), int(str(info[0][18])[6:8]), int(str(info[0][18])[8:10]), int(str(info[0][18])[10:12]), int(str(info[0][18])[12:14])) diff = datetime.datetime.utcnow() - start_connected self.ui.time_online_text.setText(str(diff)[:-7]) except: self.ui.time_online_text.setText('Pending...')
from distance import distance, mirror from mst import mst from time import time n = 125 m = [] for i in range(n): for j in range(n): m.append((i,j)) t = time() m = distance(m) print (time() - t) t = time() g = mst(m) l = 0 for e in g: l += m[e[0]][e[1]] print g print l print (time() - t)
import ev3dev.ev3 as ev3 from chatterbot import ChatBot import rpyc import chatbot import distance import telecommand import camera import danse conn = rpyc.classic.connect( 'ev3dev.local') # host name or IP address of the EV3 ev3 = conn.modules['ev3dev.ev3'] #chatbot.chatbot() #telecommand.telecommand() distance.distance() #camera.camera() #danse.danse()
def postContent(self, content): self.__contents__.append(content) def getContents(self): return self.__contents__ def addUser(self, user): if not user in self.__members__: self.__members__.append(user) class GeoCircle(Circle): center = None diameter = 500 # meters def __init__(self, name, location, radius): Circle.__init__(self, name) self.center = location self.radius = radius def insideMe(self, location): return distance(self.center, location) < self.radius if __name__ == "__main__": circle = GeoCircle(u"test circle", Location(0, 0), 2000) print circle.insideMe(Location(0.01, 0.01)) print distance(Location(0, 0), Location(0.0001, 0.0001)) print unicode(circle)
def test_five(): assert distance(-1, -1, -3, -5) == pytest.approx(4.47214, 0.00001)
def test_distance(self): self.assertEqual(0, distance.distance(1, 1)) self.assertEqual(1, distance.distance(1, 3)) self.assertEqual(1, distance.distance(3, 1)) self.assertEqual(1, distance.distance(1, 5)) self.assertEqual(1, distance.distance(5, 1)) self.assertEqual(2, distance.distance(3, 13)) self.assertEqual(2, distance.distance(13, 3)) self.assertEqual(4, distance.distance(12, 19)) self.assertEqual(4, distance.distance(19, 12)) self.assertEqual(5, distance.distance(19, 30)) self.assertEqual(5, distance.distance(30, 19))
def test_four(): assert distance(0.1, 0.1, 0.2, 0.2) == pytest.approx(0.141421, 0.00001)
def test_two(): assert distance(0,0,1,0) == 1
def similarity_matrix(vectors): return [[distance(vectors[i], vectors[j]) for i in range(len(vectors))] for j in range(len(vectors))]
def get_distance(self, other: _LocationVertex) -> float: """Return the distance between this vertex and other vertex.""" lat1, long1 = self.location # latitude and longitude of self vertex lat2, long2 = other.location # latitude and longitude of other vertex return distance(long1, long2, lat1, lat2)
def status(self, callsign): self.callsign = callsign Q_db = SQL_queries.sql_query('Get_Pilot_data', (str(callsign),)) info = Q_db.fetchall() ImageFlags = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../flags') ImageAirlines = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../airlines') ImageRatings = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../ratings') if info[0][19] == 'FOLME': pass else: try: Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][5]),)) flagCodeOrig = Q_db.fetchone() flagCodePath_orig = (ImageFlags + '/%s.png') % flagCodeOrig Pixmap = QPixmap(flagCodePath_orig) self.ui.DepartureImage.setPixmap(Pixmap) Q_db = SQL_queries.sql_query('Get_Airport_Location', (str(info[0][5]),)) city_orig = Q_db.fetchone() self.ui.DepartureText.setText(str(city_orig[0].encode('latin-1'))) city_orig_point = city_orig[1], city_orig[2] except: self.ui.DepartureText.setText('Pending...') city_orig_point = None try: Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][6]),)) flagCodeDest = Q_db.fetchone() flagCodePath_dest = (ImageFlags + '/%s.png') % flagCodeDest Pixmap = QPixmap(flagCodePath_dest) self.ui.DestinationImage.setPixmap(Pixmap) Q_db = SQL_queries.sql_query('Get_Airport_Location', (str(info[0][6]),)) city_dest = Q_db.fetchone() self.ui.DestinationText.setText(str(city_dest[0].encode('latin-1'))) city_dest_point = city_dest[1], city_dest[2] except: self.ui.DestinationText.setText('Pending...') city_dest_point = None self.ui.vidText.setText(str(info[0][0])) try: code_airline = callsign[:3] airlineCodePath = (ImageAirlines + '/%s.gif') % code_airline if os.path.exists(airlineCodePath) is True: Pixmap = QPixmap(airlineCodePath) airline = QLabel(self) self.ui.airline_image.setPixmap(Pixmap) else: Q_db = SQL_queries.sql_query('Get_Airline', str(callsign[:3])) airline_code = Q_db.fetchone() self.ui.airline_image.setText(str(airline_code[0])) except: pass self.ui.callsign_text.setText(callsign) self.ui.PilotNameText.setText(str(info[0][1][:-4].encode('latin-1'))) self.ui.RouteText.setText(str(info[0][9])) self.ui.GroundSpeedNumber.setText(str(info[0][3])) self.ui.AltitudeNumber.setText(str(info[0][2])) self.ui.PobText.setText(str(info[0][8])) self.ui.TransponderText.setText(str(info[0][11])) self.ui.GSFiledText.setText(str(info[0][17])) self.ui.FLText.setText(str(info[0][7])) Q_db = SQL_queries.sql_query('Get_Airport_from_ICAO', (str(info[0][15]),)) altern_city_1 = Q_db.fetchone() Q_db = SQL_queries.sql_query('Get_Airport_from_ICAO', (str(info[0][16]),)) altern_city_2 = Q_db.fetchone() if altern_city_1 is None: self.ui.Altern_Airport_Text.setText(str('-')) else: self.ui.Altern_Airport_Text.setText(str(altern_city_1[0])) if altern_city_2 is None: self.ui.Altern_Airport_Text_2.setText(str('-')) else: self.ui.Altern_Airport_Text_2.setText(str(altern_city_2[0])) try: if str(info[0][4]) != '': Q_db = SQL_queries.sql_query('Get_Model', ((info[0][4].split('/')[1]),)) data = Q_db.fetchall() self.ui.AirplaneText.setText('Model: %s Fabricant: %s Description: %s' \ % (str(data[0][0]), str(data[0][1]), str(data[0][2]))) except: self.ui.AirplaneText.setText('Pending...') Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(info[0][1][-4:]),)) flagCodeHome = Q_db.fetchone() flagCodePath = (ImageFlags + '/%s.png') % flagCodeHome Pixmap = QPixmap(flagCodePath) self.ui.HomeFlag.setPixmap(Pixmap) ratingImage = ImageRatings + '/pilot_level%d.gif' % int(info[0][10]) Pixmap = QPixmap(ratingImage) self.ui.rating_img.setPixmap(Pixmap) player_point = info[0][13], info[0][14] if city_orig_point is None or city_dest_point is None: self.ui.nauticalmiles.setText('Pending...') self.ui.progressBarTrack.setValue(0) if str(info[0][5]) == str(info[0][6]): self.ui.progressBarTrack.setValue(0) self.ui.nauticalmiles.setText('Local Flight') eta = '00:00:00.000000' else: try: total_miles = distance.distance(city_orig_point, city_dest_point).miles dist_traveled = distance.distance(city_orig_point, player_point).miles percent = float((dist_traveled / total_miles) * 100.0) eta = str(datetime.timedelta(hours=((total_miles - dist_traveled) / float(info[0][3])))) except: if city_orig_point or city_dest_point is None: percent = 0.0 eta = '00:00:00.000000' self.ui.nauticalmiles.setText('%.1f / %.1f miles - %.1f%%' % (float(dist_traveled), float(total_miles), float(percent))) self.ui.progressBarTrack.setValue(int(percent)) status_plane = StatusFlight.status_flight(callsign) self.ui.FlightStatusDetail.setText(str(status_plane)) self.ui.ETA_Arrive.setText(str(eta)[:-7]) try: start_connected = datetime.datetime(int(str(info[0][18])[:4]), int(str(info[0][18])[4:6]) , int(str(info[0][18])[6:8]), int(str(info[0][18])[8:10]) , int(str(info[0][18])[10:12]), int(str(info[0][18])[12:14])) diff = datetime.datetime.utcnow() - start_connected self.ui.time_online_text.setText(str(diff)[:-7]) except: self.ui.time_online_text.setText('Pending...')
def test_three(): assert distance(3,-2,-1,7) == pytest.approx(9.84886, 0.00001)
def __init__(self): # Manually set up our ROI for grabbing the hand. # Feel free to change these. I just chose the top right corner for filming. roi_top = 20 roi_bottom = 140 roi_right = 260 roi_left = 380 # ROI 2 roi_top2 = 340 roi_bottom2 = 460 cam = cv2.VideoCapture(0) cam.set(3, 640) cam.set(4, 480) # Intialize a frame count num_frames = 0 # background calc in real time # Start with a halfway point between 0 and 1 of accumulated weight accumulated_weight = 0.7 accumulated_weight2 = 0.7 accumulated_weight3 = 0.7 background_calc = calc_accum() while True: # get the current frame ret, frame = cam.read() # flip the frame so that it is not the mirror view frame = cv2.flip(frame, 1) # clone the frame frame_copy = frame.copy() # object detection. height = frame_copy.shape[0] object_roi_top = height / 2 object_roi_bottom = 640 object_detect = frame[object_roi_top:object_roi_bottom, :] object_gray = cv2.cvtColor(object_detect, cv2.COLOR_BGR2GRAY) object_gray = cv2.GaussianBlur(object_gray, (5, 5), 0) # ROI 1 # Grab the ROI from the frame(1) roi = frame[roi_top:roi_bottom, roi_right:roi_left] gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) # Apply grayscale and blur to ROI gray = cv2.GaussianBlur(gray, (5, 5), 0) # ROI 2 roi2 = frame[roi_top2:roi_bottom2, roi_right:roi_left] gray2 = cv2.cvtColor(roi2, cv2.COLOR_BGR2GRAY) gray2 = cv2.GaussianBlur(gray2, (5, 5), 0) # For the first 60 frames we will calculate the average of the background. if num_frames < 60: background_calc.calc_accum_avg(gray, accumulated_weight) background_calc.calc_accum_avg2(gray2, accumulated_weight2) background_calc.calc_accum_avg3(object_gray, accumulated_weight3) if num_frames <= 59: cv2.putText(frame_copy, "WAIT! GETTING BACKGROUND AVG.", (1, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) cv2.imshow("Vision", frame_copy) else: # shape detect upper upper_shape = segment(gray) if upper_shape is not None: upper_thresh, upper_contour, upper_segment, upper_cnts = upper_shape upper_shape_detect = detect(upper_contour) # Apply hough transform on the image (upper_cX, upper_cY, upper_c) = centroid(upper_cnts) cv2.drawContours(frame_copy, [upper_segment + (roi_right, roi_top)], -1, (255, 0, 0), 1) cv2.circle(frame_copy, (upper_cX + roi_right, roi_top + upper_cY), 7, (255, 0, 0), -1) cv2.putText(frame_copy, "upper_shape : " + str(upper_shape_detect), (1, 440), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) cv2.imshow("upper_threshold", upper_thresh) # shape detect bottom bottom_shape = segment(gray2) if bottom_shape is not None: bottom_thresh, bottom_contour, bottom_segment, bottom_cnts = bottom_shape bottom_shape_detect = detect(bottom_contour) (bottom_cX, bottom_cY, bottom_c) = centroid(bottom_cnts) cv2.drawContours(frame_copy, [bottom_segment + (roi_right, roi_top2)], -1, (255, 0, 0), 1) cv2.putText(frame_copy, "bottom_shape : " + str(bottom_shape_detect), (1, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) cv2.circle(frame_copy, (bottom_cX + roi_right, roi_top2 + bottom_cY), 7, (255, 0, 0), -1) cv2.imshow("bottom_threshold", bottom_thresh) # distance upper_c = (upper_cX + roi_right, roi_top + upper_cY) bottom_c = (bottom_cX + roi_right, roi_top2 + bottom_cY) roi_distance = distance(upper_c, bottom_c) cv2.putText(frame_copy, "ROI DISTANCE={} ".format(roi_distance), (1, 400), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) if upper_shape_detect == "square" or "rectangle" and bottom_shape_detect == "square" or "rectangle": angles = rotation(bottom_c, upper_c) cv2.putText(frame_copy, "difference ={}".format(angles), (1, 420), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) object_detect = segment(object_gray) if object_detect is not None: object_thresh, object_contour, object_segment, object_cnts = object_detect multi_obejct_detect = multi_detect() multi_obejct_detect.detect( frame_copy[object_roi_top:object_roi_bottom, :], object_contour) # Draw ROI Rectangle on frame copy cv2.rectangle(frame_copy, (roi_left, roi_top), (roi_right, roi_bottom), (0, 0, 255), 5) cv2.rectangle(frame_copy, (roi_left, roi_top2), (roi_right, roi_bottom2), (0, 0, 255), 5) # increment the number of frames for tracking num_frames += 1 #print(distance(upper_c,bottom_c)) # Display the frame with segmented hand cv2.imshow("Vision", frame_copy) # Close windows with Esc k = cv2.waitKey(1) & 0xFF if k == 27: break cam.release() cv2.destroyAllWindows()
def test_distance(): """Test whether the distance function works correctly.""" assert close(distance(1.0, 0.0, 1.0, 0.0), 0.0), "Identical points fail." assert close(distance(0.0, 0.0, 1.0, 0.0), 1.0), "Unit distance fails."
def _calculate_distance(row, key1, key2): return distance(row[key1], row[key2])
def calc_HJC(TrP: np.ndarray): ''' This function calculates the hip joint centre (HJC) Input: TrP clean matrix containing markers'trajectories in the proximal system of reference. dim(TrP)=Nc*3p where Nc is number of good samples and p is the number of distal markers Output: Cm vector with the coordinates of hip joint center (Cx,Cy,Cz). Comments: metodo1b extracts HJC position as the centre of the optimal spherical suface that minimizes the root mean square error between the radius(unknown) and the distance of the centroid of marker's coordinates from sphere center(unknown). Using definition of vector differentiation is it possible to put the problem in the form: A*Cm=B that is a linear equation system References: Gamage, Lasenby J. (2002). New least squares solutions for estimating the average centre of rotation and the axis of rotation. Journal of Biomechanics 35, 87-93 2002 Halvorsen correzione bias ''' r, c = np.shape(TrP) D = np.zeros((3,3)) V2 = [] b1 = np.array([0, 0, 0]) for j in range (0, c, 3): d1 = np.zeros((3,3)) V2a = 0 V3a = np.array([0, 0, 0]) for i in range(r): tmp = (TrP[i,j:(j+3)])[:,np.newaxis] d1 = d1 + np.matmul(tmp,tmp.transpose()) a = np.power(TrP[i,j],2) + np.power(TrP[i,j+1],2) + np.power(TrP[i,j+2],2) V2a = V2a + a V3a = V3a + a*TrP[i,j:(j+3)] D = D + d1/r V2.append(V2a/r) b1 = b1 + V3a/r # Convert V2 to array V2 = np.array(V2) V1 = np.mean(TrP,axis=0) p = np.size(V1) e1 = 0 E = np.zeros((3,3)) f1 = np.array([0, 0, 0]) F = np.array([0, 0, 0]) for k in range(0,p,3): tmp = (V1[k:(k+3)])[:,np.newaxis] e1 = np.matmul(tmp,tmp.transpose()) E = E + e1 f1 = V2[int(k/3)] * V1[k:(k+3)] F = F + f1 # Equation 5 of Gamage and Lasenby A = 2 * (D - E) B = (np.transpose(b1 - F))[:,np.newaxis] U, S, V = np.linalg.svd(A) # Convert S to a diagonal matrix S = np.diag(S) V = np.transpose(V) Cm_in = np.matmul(np.matmul(V,np.linalg.inv(S)), np.matmul(np.transpose(U), B)) Cm_old = Cm_in + (np.transpose(np.array([1, 1, 1])))[:,np.newaxis] while distance(np.transpose(Cm_old), np.transpose(Cm_in)) > 0.0000001: Cm_old = Cm_in sigma2 = [] for j in range(0,c,3): marker = TrP[:,j:(j+3)] Ukp = marker - np.transpose(Cm_in * np.ones((1,r))) # Computation of u^2 u2 = 0 app = [] for i in range(r): u2 = u2 + np.matmul(Ukp[i,:], np.transpose(Ukp[i,:])) app.append(np.matmul(Ukp[i,:], np.transpose(Ukp[i,:]))) u2 = u2/r # Computation of sigma sigmaP = 0 for i in range(r): sigmaP = sigmaP + np.power((app[i] - u2), 2) sigmaP = sigmaP/(4 * u2 * r) sigma2.append(sigmaP) sigma2 = np.mean(sigma2) # Computation of deltaB deltaB = 0 for j in range(0,c,3): deltaB = deltaB + (np.transpose(V1[j:(j+3)]))[:,np.newaxis] - Cm_in deltaB = 2 * sigma2 * deltaB Bcorr = B - deltaB # Corrected term B # Iterative estimation of the centre of rotation Cm_in = np.matmul(np.matmul(V,np.linalg.inv(S)), np.matmul(np.transpose(U), Bcorr)) Cm = Cm_in return Cm
def insideMe(self, location): return distance(self.center, location) < self.radius
import RPi.GPIO as gpio from distance import init, setup, distance import time GPIO_TRIGGER1 = 17 GPIO_TRIGGER2 = 23 GPIO_ECHO1 = 27 GPIO_ECHO2 = 24 print("Initializing gpio pins") init() print("Seting up pins") setup(GPIO_TRIGGER1, GPIO_ECHO1) setup(GPIO_TRIGGER2, GPIO_ECHO2) print("Settling sensor") time.sleep(2) print("Starting program") while True: try: dist1 = distance(GPIO_TRIGGER1, GPIO_ECHO1) dist2 = distance(GPIO_TRIGGER2, GPIO_ECHO2) print("{:.1f}x{:.1f}".format(dist1, dist2)) time.sleep(1) except KeyboardInterrupt: print("Closing GPIO!") gpio.cleanup();
import os from PIL import Image, ImageFilter import distance QUERY_DIR = 'sketches' DATA_DIR = 'edge' RESULT_DIR = 'dist' for query_name in os.listdir(QUERY_DIR): query_path = os.path.join(QUERY_DIR, query_name) query_image = Image.open(query_path) #query_image = query_image.resize((320, 240), Image.ANTIALIAS) query_image = query_image.resize((160, 120), Image.ANTIALIAS) query_image = query_image.filter(ImageFilter.FIND_EDGES).convert('L') print(query_name[:-4]) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) file = open(os.path.join(RESULT_DIR, query_name[:-4]), 'w') count = 0 for data_dir in os.listdir(DATA_DIR): data_path = os.path.join(DATA_DIR, data_dir) for image_name in os.listdir(data_path): image_path = os.path.join(data_path, image_name) dataset_image = Image.open(image_path) dataset_image = dataset_image.resize((160, 120), Image.ANTIALIAS) dist = distance.distance(query_image, dataset_image) dist *= distance.distance(dataset_image, query_image) file.write(image_name[:-4] + ' ' + str(dist) + '\n') count += 1 print(str(count) + '/1240 ' + image_name[:-4] + ' ' + str(dist)) file.close()
def lcs1(a, b): return (len(a) + len(b) - int(distance(a, b, delta2))) // 2
#------------------------------------------------------------# # implementation #------------------------------------------------------------# def compute_centroid(dataset): ''' Helper method to recompute the centroids given new dataset entries. ''' id = dataset[0].label.label data = (entry.values for entry in dataset) values = map(add, *data) return Entry(id, values) def kmeans(database, count, **kwargs): ''' Implementation of kmeans :param database: The training database :param count: The number of clusters to find ''' initialize = kwargs.get('initialize', random_initialize) terminate = kwargs.get('terminate', count_terminate(10)) centroids = initialize(database, count) while not terminate(): for entry in database: weights = [(distance(entry.values, c.values), c) for c in centroids] entry.label = sorted(weights)[0][1] groups = groupby(database, lambda (a,b): centroids = [compute_centroid(group) for group in groups] return centroids
import random import distance import orig_distance for sgh in xrange(1000): rows = random.randint(20, 200) cols = random.randint(20, 200) row1 = random.randint(0, rows - 1) row2 = random.randint(0, rows - 1) col1 = random.randint(0, cols - 1) col2 = random.randint(0, cols - 1) loc1 = (row1, col1) loc2 = (row2, col2) val1 = distance.distance(loc1[0], loc1[1], loc2[0], loc2[1], rows, cols) val2 = orig_distance.distance(loc1, loc2, rows, cols) assert val1 == val2 print "All fine"