-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathver4.py
344 lines (238 loc) · 6.74 KB
/
ver4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import math
import matplotlib.pyplot as plt
import time
def square_distance(a, b):
s = 0
for x, y in zip(a, b):
d = x - y
s += d * d
return s
class Node:
def __init__(self,pt,ax,l,lt,rt):
self.point=pt
self.axis=ax
self.label=l
self.left=lt
self.right=rt
def cnt():
cnt.count+=1
cnt.count=0
class KDTree(object):
def __init__(self,objects=[]):
def build_tree(objects, axis=0):
if not objects:
return None
objects.sort(key=lambda o: o[0][axis])
median_idx = len(objects) // 2
median_point, median_label = objects[median_idx]
next_axis = (axis + 1) % 2
return Node(median_point, axis, median_label,
build_tree(objects[:median_idx], next_axis),
build_tree(objects[median_idx + 1:], next_axis))
self.root = build_tree(list(objects))
def nearest_neighbor(self, destination,t,x=None,r=None):
best = [None, None, float('inf')]
# state of search: best point found, its label,
# lowest squared distance
def recursive_search(here):
if here is None:
return
cnt()
point, axis, label, left, right = here.point,here.axis,here.label,here.left,here.right
here_sd = square_distance(point, destination)
# if axis==0:
# plt.axvline(point[0])
# else:
# plt.axhline(point[1])
if t==1 and here_sd < best[2] and here_sd <= r*r and label not in x :
best[0] = point
best[1] = label
best[2] = here_sd
if t==2 and here_sd < best[2] and label not in x :
best[0] = point
best[1] = label
best[2] = here_sd
diff = destination[axis] - point[axis]
close, away = (left, right) if diff <= 0 else (right, left)
recursive_search(close)
if diff ** 2 < best[2]:
recursive_search(away)
recursive_search(self.root)
return best[0], best[1], math.sqrt(best[2])
def find_places(tree,name,d,pts):
prevlabel=[]
x=[]
y=[]
x_all=[]
y_all=[]
for i in pts[0] :
x_all.append(i[0][0])
y_all.append(i[0][1])
#print(x_all,"--",y_all)
print("Do you want to fine the closest ",name,"\n\t1) In a given radius\n\t2) Enter the no. closest points")
t=int(input())
start_time=time.time()
if t==2:
l=int(input("Enter no. of closest points required : "))
print(" ---- CLOSEST ",l," ",name," ----")
k=0
for i in range (l):
closest, label, mindistance = tree.nearest_neighbor(d,t,prevlabel,r=None)
if mindistance==float('inf'):
print("only ",k," nearest points are available")
break
n=mindistance
print("mindistance :",mindistance)
print("label:",label)
print("closest point",closest)
print("counter of recursive_search:",cnt.count)
print()
x.append(closest[0])
y.append(closest[1])
prevlabel.append(label)
k+=1
print("-----------",time.time()-start_time,"-------------")
patch=plt.Circle((d[0],d[1]),radius=n,color="#98ffff",alpha=0.2)
ax=plt.gca()
ax.add_patch(patch)
plt.scatter(d[0], d[1], label="My Location", color= "black",marker= "^", s=140)
plt.scatter(x_all, y_all, label= name, color= pts[2],marker= "*", s=30)
plt.scatter(x,y,s=80,facecolors='none',edgecolors='b')
# plt.xlabel('x - axis')
# plt.ylabel('y - axis')
# plt.title("CLOSEST ", name)
plt.axis('scaled')
plt.legend()
plt.show()
if t==1:
#l=int(input("Enter no. of closest points required : "))
print(" ---- CLOSEST ",name," ----")
r=float(input("\nEnter search radius :"))
prevlabel=[]
while True:
closest, label, mindistance = tree.nearest_neighbor(d,t,prevlabel,r)
if mindistance==float('inf'):
break
print("mindistance :",mindistance)
print("label:",label)
print("closest point",closest)
print("counter of recursive_search:",cnt.count)
print()
x.append(closest[0])
y.append(closest[1])
prevlabel.append(label)
patch=plt.Circle((d[0],d[1]),radius=r,color="#98ffff",alpha=0.2)
ax=plt.gca()
ax.add_patch(patch)
# plt.axis('scaled')
plt.scatter(d[0], d[1], label="My Location", color= "black",marker= "^", s=140)
# plt.scatter(x, y, label= name, color= "green",marker= "*", s=30)
plt.scatter(x_all, y_all, label= name, color= pts[2],marker= "*", s=30)
plt.scatter(x,y,s=80,facecolors='none',edgecolors='b')
# plt.xlabel('x - axis')
# plt.ylabel('y - axis')
# plt.title("CLOSEST ", name)
plt.axis('scaled')
plt.legend()
plt.show()
def plotgraph(*args):
for arg in args:
x=[]
y=[]
for i in arg[0] :
x.append(i[0][0])
y.append(i[0][1])
plt.scatter(x, y, label= arg[1], color=arg[2], marker= "*", s=80)
# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('CITY')
# showing legend
def hotels():
points=[]
c=0
infile=open('hotels.txt','r')
for i in infile:
points.append([])
points[c].append((list(map(float,i.rstrip().split(",")))))
points[c].append(c)
c+=1
return KDTree(points),points
def schools():
points=[]
c=0
infile=open('schools.txt','r')
for i in infile:
points.append([])
points[c].append((list(map(float,i.rstrip().split(",")))))
points[c].append(c)
c+=1
return KDTree(points),points
def police():
points=[]
c=0
infile=open('police.txt','r')
for i in infile:
points.append([])
points[c].append((list(map(float,i.rstrip().split(",")))))
points[c].append(c)
c+=1
return KDTree(points),points
def hospitals():
points=[]
c=0
infile=open('hospitals.txt','r')
for i in infile:
points.append([])
points[c].append((list(map(float,i.rstrip().split(",")))))
points[c].append(c)
c+=1
return KDTree(points),points
def petrol_bunk():
points=[]
c=0
infile=open('petrol_bunk.txt','r')
for i in infile:
points.append([])
points[c].append((list(map(float,i.rstrip().split(",")))))
points[c].append(c)
c+=1
return KDTree(points),points
def main():
print("Enter your location ( x y ): ")
d=list(map(float,input().split()))
h =[None,"hotels","green"]
p =[None,"police","yellow"]
ho=[None,"hospitals","red"]
pe=[None,"petrol_bunk","cyan"]
s =[None,"schools","blue"]
h_tree ,h[0] =hotels()
p_tree ,p[0] =police()
ho_tree,ho[0] =hospitals()
pe_tree,pe[0] =petrol_bunk()
s_tree ,s[0] =schools()
plotgraph(h,p,ho,pe,s)
# my location
plt.scatter(d[0], d[1], label="MY_location", color="black", marker= "^", s=140)
plt.legend()
# function to show the plot
plt.show()
plt.clf()
print("Which closest place do you wanna find?\n\t1.Police Station \n\t2.Hotels \n\t3.Schools \n\t4.Petrol Bunk \n\t5.Hospitals")
choice=int(input())
if choice==1:
find_places(p_tree,"police_stations",d,p)
elif choice==2:
find_places(h_tree,"hotels",d,h)
elif choice==3:
find_places(s_tree,"school",d,s)
elif choice==4:
find_places(pe_tree,"petrol_bunks",d,pe)
elif choice==5:
find_places(ho_tree,"hospitals",d,ho)
else:
print("wrong choice!")
if __name__ == '__main__':
main()