def gen_adj_mat(longs, lats, prob_edge=.2,
additional_length=lambda: np.random.exponential(20,1)):
'''Get an adjacency matrix for the cities whose longitudes and latitudes
are passed. Each entry will either be a number somewhat greater than the
crow-flies distance between the two cities (with probability prob_edge),
or math.inf. The matrix will consist of floats, and be symmetric. The
diagonal will be all zeroes. The "somewhat greater" is controlled by the
additional_length parameter, a function returning a random amount.'''
# Generate full nxn Bernoulli's, even though we'll only use the upper
# triangle.
edges = np.random.binomial(1, prob_edge, size=(len(longs),len(longs)))
am = np.zeros((len(longs),len(longs)))
for i in range(len(longs)):
for j in range(len(longs)):
if i==j:
am[i,i] = 0
elif i < j:
if edges[i,j] == 1:
am[i,j] = (math.hypot(longs[i]-longs[j],lats[i]-lats[j])
+ additional_length())
am[j,i] = am[i,j]
else:
am[i,j] = am[j,i] = math.inf
return np.around(am,1)
评论列表
文章目录