Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. import matplotlib.pyplot as mplot
  2. import math
  3.  
  4. def meanNearestNeighbors(x, y, data_x, data_y, pop_change, k):
  5.     sortedDistances = {}
  6.     for i in range(len(data_x)):
  7.         distance = computeDistance(x,y, data_x[i], data_y[i])
  8.         sortedDistances[distance] = pop_change[i]
  9.    
  10.     sortedKeys = sorted(sortedDistances.keys())
  11.     sum = 0
  12.     for i in range(k):
  13.         sum += sortedDistances[sortedKeys[i]]
  14.    
  15.     return sum/k
  16.        
  17. def computeDistance(x1,y1,x2,y2):
  18.     return math.sqrt(math.pow(x1-x2,2)+math.pow(y1-y2,2))
  19.  
  20. print("Please input a k-value:")
  21. k = int(input())
  22.  
  23. us_outline_file = open("us_outline.csv", "r");
  24. us_x = []
  25. us_y = []
  26.  
  27. data_file = open("data.csv", "r");
  28. data_x = []
  29. data_y = []
  30. pop_change = []
  31. lookup = {}
  32.  
  33. for line in us_outline_file:
  34.     tokens = line.split(",")
  35.     us_x.append(float(tokens[0]))
  36.     us_y.append(float(tokens[1]))
  37.    
  38. for line in data_file:
  39.     line = line.replace("\n",'')
  40.     if len(line) > 0:
  41.         tokens = line.split(",")
  42.         lookup[tokens[0]] = {}
  43.         lookup[tokens[0]][tokens[1]] = tokens[2]
  44.         data_x.append(float(tokens[0]))
  45.         data_y.append(float(tokens[1]))
  46.         pop_change.append(float(tokens[2]))
  47.  
  48. recons_x = []
  49. recons_y= []
  50. recons_value = []
  51. for y in range(121):
  52.     for x in range (195):
  53.         recons_x.append(x)
  54.         recons_y.append(y)
  55.         x = str(x)
  56.         y = str(y)
  57.         if x in lookup:
  58.             if y in lookup[x]:
  59.                 recons_value.append(lookup[x][y])
  60.             else:
  61.                 recons_value.append(meanNearestNeighbors(int(x), int(y), data_x, data_y, pop_change, k))
  62.         else:
  63.                 recons_value.append(meanNearestNeighbors(int(x), int(y), data_x, data_y, pop_change, k))
  64.  
  65. mplot.plot(us_x, us_y,'-ok', marker=None)
  66. mplot.scatter(recons_x, recons_y, c=recons_value, cmap="viridis", marker=".")
  67.  
  68. print(len(recons_x))
  69. print(len(recons_y))
  70. print(len(recons_value))
  71.  
  72. mplot.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement