68 lines
2.0 KiB
Python
68 lines
2.0 KiB
Python
import numpy as np
|
|
|
|
|
|
def construct_gram_matrix(distance_matrix):
|
|
# M_ij = (D_1j^2 + D_i1^2 - D_ij^2) / 2
|
|
row, col = distance_matrix.shape
|
|
gram = np.zeros([row, col])
|
|
for i in range(row):
|
|
for j in range(col):
|
|
gram[i][j] = 0.5 * (
|
|
(distance_matrix[0][j]) ** 2 + (distance_matrix[i][0]) ** 2 - (distance_matrix[i][j]) ** 2)
|
|
return gram
|
|
|
|
|
|
def get_coordinates_by_distance(distance_matrix):
|
|
eps = 1e-5
|
|
|
|
gram_matrix = construct_gram_matrix(distance_matrix)
|
|
# get eigenvalue and eigenvectors
|
|
feature_values, feature_vectors = np.linalg.eig(gram_matrix)
|
|
select_feature_values = []
|
|
|
|
# if eigenvalue == 0, delete it and its eigenvector
|
|
for i in range(len(feature_values) - 1, -1, -1):
|
|
if feature_values[i] > eps:
|
|
select_feature_values.append(feature_values[i])
|
|
else:
|
|
feature_vectors = np.delete(feature_vectors, i, axis=1)
|
|
eye_matrix = np.eye(len(select_feature_values))
|
|
select_feature_values.reverse()
|
|
# sqrt(eigenvalues) * eigenvectors
|
|
for i in range(len(select_feature_values)):
|
|
eye_matrix[i, i] = select_feature_values[i]
|
|
return np.dot(feature_vectors, eye_matrix ** 0.5)
|
|
|
|
|
|
def from_dist_get_coord(dist_matrix):
|
|
dist_array = np.array(dist_matrix)
|
|
coordinates_array = get_coordinates_by_distance(dist_array)
|
|
coordinates = coordinates_array.tolist()
|
|
return coordinates
|
|
|
|
|
|
def cross_judge(l1p1, l1p2, l2p1, l2p2):
|
|
if min(l1p1[0], l1p2[0]) <= max(l2p1[0], l2p2[0]) \
|
|
and min(l2p1[1], l2p2[1]) <= max(l1p1[1], l1p2[1]) \
|
|
and min(l2p1[0], l2p2[0]) <= max(l1p1[0], l1p2[0]) \
|
|
and min(l1p1[1], l1p2[1]) <= max(l2p1[1], l2p2[1]):
|
|
return True
|
|
else:
|
|
return False
|
|
|
|
|
|
if __name__ == "__main__":
|
|
dist_matrix = [
|
|
[0, 1, 1],
|
|
[1, 0, 1],
|
|
[1, 1, 0]
|
|
]
|
|
coordinates = from_dist_get_coord(dist_matrix)
|
|
print(coordinates)
|
|
a = [1, 1]
|
|
b = [2, 2]
|
|
c = [1, 2]
|
|
d = [4, 1]
|
|
a = cross_judge(a, b, c, d)
|
|
print(a)
|