Upload folder using huggingface_hub
Browse files- server-local/shortest-paths-terrain-patches/dataset/__init__.py +0 -0
- server-local/shortest-paths-terrain-patches/dataset/__pycache__/__init__.cpython-38.pyc +0 -0
- server-local/shortest-paths-terrain-patches/dataset/__pycache__/patch_dataset.cpython-38.pyc +0 -0
- server-local/shortest-paths-terrain-patches/dataset/across-terrain-simulation.py +132 -0
- server-local/shortest-paths-terrain-patches/dataset/artificial_dem_array.py +171 -0
- server-local/shortest-paths-terrain-patches/dataset/change-height-gen-dataset.py +303 -0
- server-local/shortest-paths-terrain-patches/dataset/change-heights-dem.py +59 -0
- server-local/shortest-paths-terrain-patches/dataset/dataset.py +313 -0
- server-local/shortest-paths-terrain-patches/dataset/generate-test-dataset.py +294 -0
- server-local/shortest-paths-terrain-patches/dataset/patch_dataset.py +261 -0
- server-local/shortest-paths-terrain-patches/dataset/point_sampler.py +59 -0
- server-local/shortest-paths-terrain-patches/dataset/py-to-wavefront.py +76 -0
server-local/shortest-paths-terrain-patches/dataset/__init__.py
ADDED
|
File without changes
|
server-local/shortest-paths-terrain-patches/dataset/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (143 Bytes). View file
|
|
|
server-local/shortest-paths-terrain-patches/dataset/__pycache__/patch_dataset.cpython-38.pyc
ADDED
|
Binary file (6.57 kB). View file
|
|
|
server-local/shortest-paths-terrain-patches/dataset/across-terrain-simulation.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
from torch_geometric.utils import to_networkx
|
| 6 |
+
import networkx as nx
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from tqdm import tqdm, trange
|
| 9 |
+
import multiprocessing as mp
|
| 10 |
+
import time
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
|
| 15 |
+
NSRCS = 100
|
| 16 |
+
|
| 17 |
+
DATASET_INFO = {'norway': [10, False], 'phil': [3, True], 'holland': [1.524, True]}
|
| 18 |
+
|
| 19 |
+
class SingleGraphShortestPathDataset(Dataset):
|
| 20 |
+
def __init__(self, sources, targets, lengths):
|
| 21 |
+
self.sources = sources
|
| 22 |
+
self.targets = targets
|
| 23 |
+
self.lengths = lengths
|
| 24 |
+
|
| 25 |
+
def __len__(self):
|
| 26 |
+
return len(self.sources)
|
| 27 |
+
|
| 28 |
+
def __getitem__(self, idx):
|
| 29 |
+
return self.sources[idx], self.targets[idx], self.lengths[idx]
|
| 30 |
+
|
| 31 |
+
def single_source_sample(G, num_per_src, num_srcs):
|
| 32 |
+
number_of_nodes = G.number_of_nodes()
|
| 33 |
+
src_nodes = np.random.choice(number_of_nodes, size=NSRCS)
|
| 34 |
+
srcs = []
|
| 35 |
+
tars = []
|
| 36 |
+
lengths = []
|
| 37 |
+
for src in src_nodes:
|
| 38 |
+
shortest_paths = nx.single_source_dijkstra_path_length(G, s, weight='weight')
|
| 39 |
+
for i in trange(num_per_src):
|
| 40 |
+
t = np.random.choice(number_of_nodes)
|
| 41 |
+
srcs.append(s)
|
| 42 |
+
tars.append(t)
|
| 43 |
+
lengths.append(shortest_paths[t])
|
| 44 |
+
dataset = SingleGraphShortestPathDataset(sources = srcs, targets = tars, lengths = lengths)
|
| 45 |
+
return dataset
|
| 46 |
+
|
| 47 |
+
def random_sample(G, num_sample):
|
| 48 |
+
number_of_nodes = G.number_of_nodes()
|
| 49 |
+
srcs = []
|
| 50 |
+
tars = []
|
| 51 |
+
lengths = []
|
| 52 |
+
for _ in trange(num_sample):
|
| 53 |
+
src, tar = np.random.choice(number_of_nodes, [2, ], replace=False)
|
| 54 |
+
length = nx.shortest_path_length(G, src, tar, weight='weight')
|
| 55 |
+
srcs.append(src)
|
| 56 |
+
tars.append(tar)
|
| 57 |
+
lengths.append(length)
|
| 58 |
+
dataset = SingleGraphShortestPathDataset(sources = srcs, targets = tars, lengths = lengths)
|
| 59 |
+
return dataset
|
| 60 |
+
|
| 61 |
+
def construct_cross_terrains_dataset(nx_graphs, pyg_graphs, num_per_graph, sampling_technique='single_source_sample'):
|
| 62 |
+
dataset = {'graphs': pyg_graphs, 'datasets': []}
|
| 63 |
+
num_graphs = len(nx_graphs)
|
| 64 |
+
|
| 65 |
+
for i in range(num_graphs):
|
| 66 |
+
print("Processing graph:", i)
|
| 67 |
+
nx_graph = nx_graphs[i]
|
| 68 |
+
if sampling_technique == 'single_source_sample':
|
| 69 |
+
dataset['datasets'].append(single_source_sample(nx_graph, num_per_graph//NSRCS, NSRCS))
|
| 70 |
+
elif sampling_technique == 'random_sample':
|
| 71 |
+
dataset['datasets'].append(random_sample(nx_graph, num_per_graph))
|
| 72 |
+
else:
|
| 73 |
+
raise NotImplementedError('Other sampling techniques not implemented')
|
| 74 |
+
return dataset
|
| 75 |
+
|
| 76 |
+
def npz_to_dataset(data):
|
| 77 |
+
|
| 78 |
+
edge_index = torch.tensor(data['edge_index'], dtype=torch.long)
|
| 79 |
+
|
| 80 |
+
srcs = torch.tensor(data['srcs'])
|
| 81 |
+
tars = torch.tensor(data['tars'])
|
| 82 |
+
lengths = torch.tensor(data['lengths'])
|
| 83 |
+
node_features = torch.tensor(data['node_features'], dtype=torch.double)
|
| 84 |
+
edge_weights = torch.tensor(data['distances'])
|
| 85 |
+
|
| 86 |
+
return srcs, tars, lengths, node_features, edge_index, edge_weights
|
| 87 |
+
|
| 88 |
+
def retrieve_artificial_dataset(file_pth):
|
| 89 |
+
# pth = f'/data/sam/terrain/data/artificial/change-heights/amp-{a}-res-{RES}-train-50k.npz'
|
| 90 |
+
# test_info = generate_train_data(pth, cnn_sz=100)
|
| 91 |
+
#amps = [1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0]
|
| 92 |
+
amps = [2.0, 6.0, 10.0, 14.0, 18.0]
|
| 93 |
+
pyg_graphs = []
|
| 94 |
+
nx_graphs = []
|
| 95 |
+
for a in amps:
|
| 96 |
+
fname = os.path.join(file_pth, f'amp-{a}-res-2-train-50k.npz')
|
| 97 |
+
np_data = np.load(fname, allow_pickle=True)
|
| 98 |
+
_, _, _, node_features, edge_index, edge_weights = npz_to_dataset(np_data)
|
| 99 |
+
pyg_graph = Data(x =node_features, edge_index = edge_index, edge_attr = edge_weights)
|
| 100 |
+
nx_graph = to_networkx(pyg_graph)
|
| 101 |
+
for i in range(len(edge_index[0])):
|
| 102 |
+
v1 = edge_index[0][i].item()
|
| 103 |
+
v2 = edge_index[1][i].item()
|
| 104 |
+
nx_graph[v1][v2]['weight'] = pyg_graph.edge_attr[i].item()
|
| 105 |
+
nx_graphs.append(nx_graph)
|
| 106 |
+
pyg_graphs.append(pyg_graph)
|
| 107 |
+
return nx_graphs, pyg_graphs
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
parser = argparse.ArgumentParser()
|
| 111 |
+
parser.add_argument('--dataset-name', type=str)
|
| 112 |
+
parser.add_argument('--raw-data', type=str)
|
| 113 |
+
parser.add_argument('--filename', type=str) # saves should be named `gr-{graph-resolution}-ps-{patch-size}-ol-{overlap}`
|
| 114 |
+
parser.add_argument('--graph-resolution', type=int)
|
| 115 |
+
parser.add_argument('--per-graph', type=int)
|
| 116 |
+
parser.add_argument('--patch-size', type=int)
|
| 117 |
+
parser.add_argument('--overlap', type=int)
|
| 118 |
+
parser.add_argument('--sampling-technique', type=str)
|
| 119 |
+
|
| 120 |
+
args = parser.parse_args()
|
| 121 |
+
if args.dataset_name != 'artificial':
|
| 122 |
+
raise NotImplementedError('Other datasets not implemented yet')
|
| 123 |
+
file_pth = '/data/sam/terrain/data/artificial/change-heights'
|
| 124 |
+
nx_graphs, pyg_graphs = retrieve_artificial_dataset(file_pth)
|
| 125 |
+
dataset = construct_cross_terrains_dataset(nx_graphs,
|
| 126 |
+
pyg_graphs,
|
| 127 |
+
args.per_graph,
|
| 128 |
+
sampling_technique=args.sampling_technique)
|
| 129 |
+
torch.save(dataset, args.filename)
|
| 130 |
+
|
| 131 |
+
if __name__ == '__main__':
|
| 132 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/artificial_dem_array.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import networkx as nx
|
| 3 |
+
from tqdm import tqdm, trange
|
| 4 |
+
import argparse
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def gaussian_2d(xv, yv, amplitude=1, center_x=0, center_y=0, sigma_x=1, sigma_y=1):
|
| 9 |
+
z1 = (xv - center_x)**2/(2*(sigma_x**2))
|
| 10 |
+
z2 = (yv - center_y)**2/(2*(sigma_y**2))
|
| 11 |
+
z = amplitude * np.exp(-(z1 + z2))
|
| 12 |
+
return z
|
| 13 |
+
|
| 14 |
+
def create_elevation_array(n, k=10):
|
| 15 |
+
'''
|
| 16 |
+
Function which creates an n x n elevation array with k critical points
|
| 17 |
+
|
| 18 |
+
Returns: numpy array of elevations
|
| 19 |
+
'''
|
| 20 |
+
n0 = 10*n
|
| 21 |
+
# create x and y range
|
| 22 |
+
x = np.linspace(-10, 10, n0)
|
| 23 |
+
y = np.linspace(-10, 10, n0)
|
| 24 |
+
xv, yv = np.meshgrid(x, y)
|
| 25 |
+
|
| 26 |
+
z_out = np.zeros((n0, n0))
|
| 27 |
+
centers = [(50, 50), (200, 50), (50, 150), (250, 150), (130, 230)]
|
| 28 |
+
for i in range(k):
|
| 29 |
+
center = centers[i]
|
| 30 |
+
x_c = xv[center[0], center[1]]
|
| 31 |
+
y_c = yv[center[0], center[1]]
|
| 32 |
+
centers.append(center)
|
| 33 |
+
#a = np.random.uniform(low=1.0, high=5.0)
|
| 34 |
+
a = 3.0
|
| 35 |
+
# s_x = np.random.uniform(low=1.0, high=4.0)
|
| 36 |
+
# s_y = np.random.uniform(low=1.0, high=4.0)
|
| 37 |
+
s_x = 2.0
|
| 38 |
+
s_y = 2.0
|
| 39 |
+
z = gaussian_2d(xv, yv, amplitude=a, center_x = x_c, center_y = y_c, sigma_x=s_x, sigma_y=s_y)
|
| 40 |
+
z_out += z
|
| 41 |
+
return z_out
|
| 42 |
+
|
| 43 |
+
def get_array_neighbors_(x, y, left=0, right=500, radius=1):
|
| 44 |
+
temp = [(x - radius, y), (x + radius, y), (x, y - radius), (x, y + radius)]
|
| 45 |
+
neighbors = temp.copy()
|
| 46 |
+
|
| 47 |
+
for val in temp:
|
| 48 |
+
if val[0] < left or val[0] >= right:
|
| 49 |
+
neighbors.remove(val)
|
| 50 |
+
elif val[1] < left or val[1] >= right:
|
| 51 |
+
neighbors.remove(val)
|
| 52 |
+
|
| 53 |
+
return neighbors
|
| 54 |
+
|
| 55 |
+
def construct_nx_graph(xv, yv, elevation, save_img=None):
|
| 56 |
+
sz = elevation.shape[0]
|
| 57 |
+
counts = np.reshape(np.arange(0, sz*sz), (sz, sz))
|
| 58 |
+
G = nx.Graph()
|
| 59 |
+
|
| 60 |
+
node_features = []
|
| 61 |
+
fig = plt.figure(figsize=(15, 15))
|
| 62 |
+
ax = fig.add_subplot(projection='3d')
|
| 63 |
+
|
| 64 |
+
for i in trange(0, len(elevation)):
|
| 65 |
+
for j in range(0, len(elevation)):
|
| 66 |
+
idx1 = counts[i, j]
|
| 67 |
+
G.add_node(idx1)
|
| 68 |
+
node_features.append(np.array([xv[i, j], yv[i, j], elevation[i, j]]))
|
| 69 |
+
neighbors = get_array_neighbors_(i, j, right=elevation.shape[0])
|
| 70 |
+
for n in neighbors:
|
| 71 |
+
p1 = np.array([xv[i, j], yv[i, j], elevation[i, j]])
|
| 72 |
+
p2 = np.array([xv[n[0], n[1]], yv[n[0], n[1]], elevation[n[0], n[1]]])
|
| 73 |
+
w = np.linalg.norm(p1 - p2)
|
| 74 |
+
if save_img != None:
|
| 75 |
+
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 76 |
+
idx2 = counts[n[0], n[1]]
|
| 77 |
+
G.add_edge(idx1, idx2, weight=w)
|
| 78 |
+
print("Size of graph:", len(node_features))
|
| 79 |
+
if save_img != None:
|
| 80 |
+
print("saved in:", save_img)
|
| 81 |
+
plt.savefig(save_img)
|
| 82 |
+
return G, node_features
|
| 83 |
+
|
| 84 |
+
def get_elevated_points(node_features, threshhold=0.4):
|
| 85 |
+
elevated_pts = []
|
| 86 |
+
for i in range(len(node_features)):
|
| 87 |
+
z = node_features[i][2]
|
| 88 |
+
if z > 0.4:
|
| 89 |
+
elevated_pts.append(i)
|
| 90 |
+
return elevated_pts
|
| 91 |
+
|
| 92 |
+
# at least guarantee_rough_path percent of the dataset should be go through "elevated points"
|
| 93 |
+
def construct_pyg_dataset(G, node_features, filename, guarantee_rough_path = 0.2, size=100):
|
| 94 |
+
Nodes = np.sort(list(G.nodes()))
|
| 95 |
+
|
| 96 |
+
distances = []
|
| 97 |
+
|
| 98 |
+
edges = [[], []]
|
| 99 |
+
|
| 100 |
+
print("Formatting edge index.......")
|
| 101 |
+
for e in tqdm(G.edges(data=True)):
|
| 102 |
+
edges[0].append(e[0])
|
| 103 |
+
edges[1].append(e[1])
|
| 104 |
+
edges[0].append(e[1])
|
| 105 |
+
edges[1].append(e[0])
|
| 106 |
+
|
| 107 |
+
distances.append(e[2]['weight'])
|
| 108 |
+
distances.append(e[2]['weight'])
|
| 109 |
+
|
| 110 |
+
# Get elevated points
|
| 111 |
+
elevated_pts = get_elevated_points(node_features, threshhold=0.6)
|
| 112 |
+
|
| 113 |
+
srcs = []
|
| 114 |
+
tars = []
|
| 115 |
+
lengths = []
|
| 116 |
+
print("Generating shortest paths......")
|
| 117 |
+
for i in range(len(Nodes)):
|
| 118 |
+
for j in range(i + 1, len(Nodes)):
|
| 119 |
+
src = i
|
| 120 |
+
tar = j
|
| 121 |
+
srcs.append(i)
|
| 122 |
+
tars.append(j)
|
| 123 |
+
length = nx.shortest_path_length(G, src, tar, weight='weight')
|
| 124 |
+
lengths.append(length)
|
| 125 |
+
|
| 126 |
+
# for i in trange(size):
|
| 127 |
+
# if i < size*guarantee_rough_path and len(elevated_pts) > 0:
|
| 128 |
+
# src = np.random.choice(elevated_pts)
|
| 129 |
+
# tar = np.random.choice(len(node_features), replace=False)
|
| 130 |
+
# else:
|
| 131 |
+
# src, tar = np.random.choice(len(node_features), [2,], replace=False)
|
| 132 |
+
# srcs.append(src)
|
| 133 |
+
# tars.append(tar)
|
| 134 |
+
# length = nx.shortest_path_length(G, src, tar, weight='weight')
|
| 135 |
+
# lengths.append(length)
|
| 136 |
+
print("Saved dataset in:", filename)
|
| 137 |
+
np.savez(filename,
|
| 138 |
+
edge_index = edges,
|
| 139 |
+
distances=distances,
|
| 140 |
+
nodes=Nodes,
|
| 141 |
+
srcs = srcs,
|
| 142 |
+
tars = tars,
|
| 143 |
+
lengths = lengths,
|
| 144 |
+
node_features=node_features)
|
| 145 |
+
|
| 146 |
+
def main():
|
| 147 |
+
parser = argparse.ArgumentParser()
|
| 148 |
+
parser.add_argument("--size", type=int)
|
| 149 |
+
parser.add_argument("--train-dataset-size", type=int)
|
| 150 |
+
parser.add_argument("--test-dataset-size", type=int)
|
| 151 |
+
args = parser.parse_args()
|
| 152 |
+
|
| 153 |
+
for k in range(1):
|
| 154 |
+
|
| 155 |
+
upsample_save = f'/data/sam/terrain/data/artificial/for-lucas.npy'
|
| 156 |
+
xv, yv, dem, upsampled_dem = create_elevation_array(n=args.size, k=5)
|
| 157 |
+
np.save(upsample_save, upsampled_dem)
|
| 158 |
+
img = f'../images/small-k-{k}.png'
|
| 159 |
+
print("saved in", img)
|
| 160 |
+
# G, node_features = construct_nx_graph(xv, yv, dem, save_img=img)
|
| 161 |
+
# #for train_dataset_size in range(10000, 60000, 10000):
|
| 162 |
+
# train_filename = f'/data/sam/terrain/data/artificial/small-k-{k}-train-full.npz'
|
| 163 |
+
# construct_pyg_dataset(G, node_features, filename=train_filename, size=10)
|
| 164 |
+
# test_filename = f'/data/sam/terrain/data/artificial/small-k-{k}-test-{args.test_dataset_size}.npz'
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# construct_pyg_dataset(G, node_features, filename=test_filename, size=args.test_dataset_size)
|
| 168 |
+
return 0
|
| 169 |
+
|
| 170 |
+
if __name__=="__main__":
|
| 171 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/change-height-gen-dataset.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
import networkx as nx
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm, trange
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
import time
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
DATASET_INFO = {'norway': [10, False], 'phil': [3, True], 'holland': [1.524, True], 'la': [28.34, False], 'artificial': [10/50, False]}
|
| 15 |
+
|
| 16 |
+
# Load DEM data from file,
|
| 17 |
+
# outputs elevations in meters
|
| 18 |
+
def load_dem_data_(filename, imperial=False):
|
| 19 |
+
f = open(filename)
|
| 20 |
+
|
| 21 |
+
lines = f.readlines()
|
| 22 |
+
arr = []
|
| 23 |
+
print("Elevation given in imperial units:", imperial)
|
| 24 |
+
c = 1
|
| 25 |
+
if imperial:
|
| 26 |
+
c = 3.28084
|
| 27 |
+
for i in range(1, len(lines)):
|
| 28 |
+
vals = lines[i].split()
|
| 29 |
+
a = []
|
| 30 |
+
for j in range(len(vals)):
|
| 31 |
+
a.append(float(vals[j])/c)
|
| 32 |
+
arr.append(a)
|
| 33 |
+
arr = np.array(arr)
|
| 34 |
+
print("loaded DEM array with shape:", arr.shape)
|
| 35 |
+
return arr
|
| 36 |
+
|
| 37 |
+
def mesh_to_graph(edge_filename, vertex_filename):
|
| 38 |
+
f = open(edge_filename)
|
| 39 |
+
all_vertices = []
|
| 40 |
+
lines = f.readlines()
|
| 41 |
+
edges = []
|
| 42 |
+
for i in range(len(lines)):
|
| 43 |
+
|
| 44 |
+
vals = lines[i].split()
|
| 45 |
+
edges.append((int(vals[0]), int(vals[1])))
|
| 46 |
+
all_vertices.append(int(vals[0]))
|
| 47 |
+
all_vertices.append(int(vals[1]))
|
| 48 |
+
|
| 49 |
+
unique_vertices = np.sort(np.unique(all_vertices))
|
| 50 |
+
|
| 51 |
+
nx_graph = nx.Graph()
|
| 52 |
+
|
| 53 |
+
temp = {}
|
| 54 |
+
for i in range(len(unique_vertices)):
|
| 55 |
+
temp[unique_vertices[i]] = i
|
| 56 |
+
|
| 57 |
+
f = open(vertex_filename)
|
| 58 |
+
|
| 59 |
+
lines = f.readlines()
|
| 60 |
+
vertices = np.zeros((len(unique_vertices), 3))
|
| 61 |
+
for i in range( len(lines)):
|
| 62 |
+
vals = lines[i].split()
|
| 63 |
+
vertices[i] = [ float(vals[0])/1000, float(vals[1])/1000, float(vals[2])/1000]
|
| 64 |
+
|
| 65 |
+
for i in range(len(edges)):
|
| 66 |
+
v1 = temp[edges[i][0]]
|
| 67 |
+
v2 = temp[edges[i][1]]
|
| 68 |
+
weight = np.linalg.norm(vertices[v1] - vertices[v2], ord=2)
|
| 69 |
+
nx_graph.add_edge(v1, v2, weight=weight)
|
| 70 |
+
|
| 71 |
+
return nx_graph, vertices
|
| 72 |
+
|
| 73 |
+
# Get DEM array xloc and yloc
|
| 74 |
+
# outputs all relevant values in km
|
| 75 |
+
def get_dem_xv_yv_(arr, resolution, visualize=True):
|
| 76 |
+
sz = arr.shape[0]
|
| 77 |
+
total_width = resolution * sz
|
| 78 |
+
x = np.linspace(0, total_width, sz)
|
| 79 |
+
y = np.linspace(0, total_width, sz)
|
| 80 |
+
xv, yv = np.meshgrid(x, y)
|
| 81 |
+
if visualize == True:
|
| 82 |
+
plt.contourf(xv/1000, yv/1000, arr/1000)
|
| 83 |
+
print("minimal elevation:", np.min(arr), "maximum elevation:", np.max(arr))
|
| 84 |
+
plt.axis("scaled")
|
| 85 |
+
plt.colorbar()
|
| 86 |
+
plt.show()
|
| 87 |
+
return xv, yv, arr
|
| 88 |
+
#return xv/1000, yv/1000, arr/1000
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# Construct grid
|
| 92 |
+
def get_array_neighbors_(x, y, left=0, right=500, radius=1):
|
| 93 |
+
temp = [(x - radius, y), (x + radius, y), (x, y - radius), (x, y + radius)]
|
| 94 |
+
neighbors = temp.copy()
|
| 95 |
+
|
| 96 |
+
for val in temp:
|
| 97 |
+
if val[0] < left or val[0] >= right:
|
| 98 |
+
neighbors.remove(val)
|
| 99 |
+
elif val[1] < left or val[1] >= right:
|
| 100 |
+
neighbors.remove(val)
|
| 101 |
+
|
| 102 |
+
return neighbors
|
| 103 |
+
|
| 104 |
+
# External use ok
|
| 105 |
+
def construct_nx_graph(xv, yv, elevation, triangles=False, p=2, scale=False):
|
| 106 |
+
|
| 107 |
+
n = elevation.shape[0]
|
| 108 |
+
m = elevation.shape[1]
|
| 109 |
+
print("shape", n, m)
|
| 110 |
+
counts = np.reshape(np.arange(0, n*m), (n, m))
|
| 111 |
+
G = nx.Graph()
|
| 112 |
+
|
| 113 |
+
print(triangles)
|
| 114 |
+
|
| 115 |
+
node_features = []
|
| 116 |
+
#fig = plt.figure()
|
| 117 |
+
#ax = fig.add_subplot(projection='3d')
|
| 118 |
+
for i in trange(0, n):
|
| 119 |
+
for j in range(0, m):
|
| 120 |
+
idx1 = counts[i, j]
|
| 121 |
+
G.add_node(idx1)
|
| 122 |
+
node_features.append(np.array([xv[i, j], yv[i, j], elevation[i, j]]))
|
| 123 |
+
neighbors = get_array_neighbors_(i, j, right=elevation.shape[0], radius=1)
|
| 124 |
+
for neighbor in neighbors:
|
| 125 |
+
p1 = np.array([xv[i, j], yv[i, j], elevation[i, j]])
|
| 126 |
+
p2 = np.array([xv[neighbor[0], neighbor[1]], yv[neighbor[0], neighbor[1]], elevation[neighbor[0], neighbor[1]]])
|
| 127 |
+
if scale:
|
| 128 |
+
angle_of_elevation = np.abs(np.arctan(p1[2] - p2[2])/np.linalg.norm(p2[:2] - p1[:2], ord=2))
|
| 129 |
+
# slope = (abs(p1[2] - p2[2]))/(abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]))
|
| 130 |
+
# w = 1+ np.log(1 + slope)
|
| 131 |
+
w = angle_of_elevation * np.linalg.norm(p1 - p2, ord=p)
|
| 132 |
+
else:
|
| 133 |
+
w = np.linalg.norm(p1 - p2, ord=p)
|
| 134 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 135 |
+
idx2 = counts[neighbor[0], neighbor[1]]
|
| 136 |
+
G.add_edge(idx1, idx2, weight=w)
|
| 137 |
+
print("Size of graph:", len(node_features))
|
| 138 |
+
if triangles:
|
| 139 |
+
for i in trange(0, n - 1):
|
| 140 |
+
for j in range(0, m - 1):
|
| 141 |
+
# index cell by top left coordinate
|
| 142 |
+
triangle_edge = [(counts[i, j], counts[i + 1, j + 1]), (counts[i + 1, j], counts[i, j + 1])]
|
| 143 |
+
edge = triangle_edge[np.random.choice(2)]
|
| 144 |
+
for edge in triangle_edge:
|
| 145 |
+
p1 = node_features[edge[0]]
|
| 146 |
+
p2 = node_features[edge[1]]
|
| 147 |
+
if scale:
|
| 148 |
+
angle_of_elevation = np.abs(np.arctan(p1[2] - p2[2])/np.linalg.norm(p2[:2] - p1[:2], ord=2))
|
| 149 |
+
w = angle_of_elevation * np.linalg.norm(p1 - p2, ord=p)
|
| 150 |
+
else:
|
| 151 |
+
w = np.linalg.norm(p1 - p2, ord = p)
|
| 152 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 153 |
+
G.add_edge(edge[0], edge[1], weight=w)
|
| 154 |
+
#fig.savefig('../images/norway-250.png')
|
| 155 |
+
print(G.edges(0))
|
| 156 |
+
return G, node_features
|
| 157 |
+
|
| 158 |
+
def to_pyg_graph(G):
|
| 159 |
+
distances = []
|
| 160 |
+
|
| 161 |
+
edges = [[], []]
|
| 162 |
+
|
| 163 |
+
print("Formatting edge index.......")
|
| 164 |
+
for e in tqdm(G.edges(data=True)):
|
| 165 |
+
edges[0].append(e[0])
|
| 166 |
+
edges[1].append(e[1])
|
| 167 |
+
edges[0].append(e[1])
|
| 168 |
+
edges[1].append(e[0])
|
| 169 |
+
|
| 170 |
+
distances.append(e[2]['weight'])
|
| 171 |
+
distances.append(e[2]['weight'])
|
| 172 |
+
return edges, distances
|
| 173 |
+
|
| 174 |
+
def generate_probabilities(N, m):
|
| 175 |
+
all_pairs = list(itertools.combinations(range(N), 2))
|
| 176 |
+
probabilities = []
|
| 177 |
+
for src, tar in tqdm(all_pairs):
|
| 178 |
+
hops = abs(src//m - tar//m) + abs(src % m - tar % m )
|
| 179 |
+
probabilities.append(1/(hops**2) if hops > 0 else 1)
|
| 180 |
+
return all_pairs, probabilities
|
| 181 |
+
|
| 182 |
+
def construct_pyg_dataset(G, node_features, filename, size=100, sampling_technique='distance-based', m=10, p=0.10):
|
| 183 |
+
Nodes = np.sort(list(G.nodes()))
|
| 184 |
+
|
| 185 |
+
edges, distances = to_pyg_graph(G)
|
| 186 |
+
|
| 187 |
+
srcs = []
|
| 188 |
+
tars = []
|
| 189 |
+
lengths = []
|
| 190 |
+
print("Generating shortest paths......")
|
| 191 |
+
#jobs = []
|
| 192 |
+
#pool = mp.Pool(processes=20)
|
| 193 |
+
node_idxs = np.reshape(np.arange(m * m), (m, m))
|
| 194 |
+
lst= np.arange(len(node_features))
|
| 195 |
+
print(sampling_technique)
|
| 196 |
+
for i in trange(size):
|
| 197 |
+
if sampling_technique == 'distance-based':
|
| 198 |
+
src = np.random.choice(len(node_features))
|
| 199 |
+
hops = abs(src//m - lst//m) + abs(src % m - lst % m)+ 1
|
| 200 |
+
probs = 1/hops
|
| 201 |
+
probs = probs/np.linalg.norm(probs, ord=1)
|
| 202 |
+
tar = np.random.choice(len(node_features), p = probs)
|
| 203 |
+
elif sampling_technique == 'constrained-125x125':
|
| 204 |
+
src = np.random.choice(len(node_features))
|
| 205 |
+
src_row = src//m
|
| 206 |
+
src_col = src %m
|
| 207 |
+
if np.random.uniform(low=0.0, high=1.0) <= p:
|
| 208 |
+
tar = np.random.choice(len(node_features))
|
| 209 |
+
else:
|
| 210 |
+
b1 = 0 if src_row -125 < 0 else src_row - 125
|
| 211 |
+
b2 = 0 if src_col - 125 < 0 else src_col - 125
|
| 212 |
+
#print(b1, src_row + 25, b2, src_col + 25, node_idxs[b1 : src_row + 25, b2: src_col+25].flatten())
|
| 213 |
+
tar = np.random.choice(node_idxs[b1 : src_row + 125, b2: src_col+125].flatten())
|
| 214 |
+
elif sampling_technique == 'constrained-25x25':
|
| 215 |
+
src = np.random.choice(len(node_features))
|
| 216 |
+
src_row = src//m
|
| 217 |
+
src_col = src %m
|
| 218 |
+
p = np.random.uniform(low=0.0, high=1.0)
|
| 219 |
+
if p > 1.0:
|
| 220 |
+
tar = np.random.choice(len(node_features))
|
| 221 |
+
else:
|
| 222 |
+
b1 = 0 if src_row -25 < 0 else src_row - 25
|
| 223 |
+
b2 = 0 if src_col - 25 < 0 else src_col - 25
|
| 224 |
+
tar = np.random.choice(node_idxs[b1 : src_row + 25, b2: src_col+25].flatten())
|
| 225 |
+
elif sampling_technique == 'ss-random':
|
| 226 |
+
num_tars = size // 100
|
| 227 |
+
src_nodes = np.random.choice(len(node_features), size=100)
|
| 228 |
+
tars = []
|
| 229 |
+
srcs = []
|
| 230 |
+
lengths = []
|
| 231 |
+
for s in tqdm(src_nodes):
|
| 232 |
+
shortest_paths = nx.single_source_dijkstra_path_length(G, s, weight='weight')
|
| 233 |
+
for i in range(num_tars):
|
| 234 |
+
t = np.random.choice(len(node_features))
|
| 235 |
+
srcs.append(s)
|
| 236 |
+
tars.append(t)
|
| 237 |
+
lengths.append(shortest_paths[t])
|
| 238 |
+
break
|
| 239 |
+
else:
|
| 240 |
+
src, tar = np.random.choice(len(node_features), [2, ], replace=False)
|
| 241 |
+
if sampling_technique != 'ss-random':
|
| 242 |
+
length = nx.shortest_path_length(G, src, tar, weight='weight')
|
| 243 |
+
srcs.append(src)
|
| 244 |
+
tars.append(tar)
|
| 245 |
+
lengths.append(length)
|
| 246 |
+
# rotation = np.array([[np.cos(np.pi/9), -np.sin(np.pi/9)], [np.sin(np.pi/9), np.cos(np.pi/9)]])
|
| 247 |
+
# node_features = np.array(node_features)
|
| 248 |
+
# rotated_pts_x_y = (rotation @ node_features[:, :2].T).T
|
| 249 |
+
# node_features[:, :2] = rotated_pts_x_y
|
| 250 |
+
print("Saved dataset in:", filename)
|
| 251 |
+
np.savez(filename,
|
| 252 |
+
edge_index = edges,
|
| 253 |
+
distances=distances,
|
| 254 |
+
nodes=Nodes,
|
| 255 |
+
srcs = srcs,
|
| 256 |
+
tars = tars,
|
| 257 |
+
lengths = lengths,
|
| 258 |
+
node_features=node_features)
|
| 259 |
+
|
| 260 |
+
def main():
|
| 261 |
+
parser = argparse.ArgumentParser()
|
| 262 |
+
parser.add_argument('--name', type=str)
|
| 263 |
+
parser.add_argument('--raw-data', type=str)
|
| 264 |
+
parser.add_argument('--filename', type=str)
|
| 265 |
+
parser.add_argument('--graph-resolution', type=int)
|
| 266 |
+
parser.add_argument('--dataset-size', type=int)
|
| 267 |
+
parser.add_argument('--sampling-technique', type=str, default='random')
|
| 268 |
+
parser.add_argument('--triangles', action='store_true')
|
| 269 |
+
parser.add_argument('--edge-weight', action='store_true')
|
| 270 |
+
|
| 271 |
+
args = parser.parse_args()
|
| 272 |
+
dem_res = DATASET_INFO[args.name][0]
|
| 273 |
+
imperial = DATASET_INFO[args.name][1]
|
| 274 |
+
AMPS = [1.0, 2.0, 4.0, 6.0, 8.0, 9.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0]
|
| 275 |
+
for amp in AMPS:
|
| 276 |
+
raw_data = f'/data/sam/terrain/data/artificial/change-heights/amp-{amp}.npy'
|
| 277 |
+
dem_array = np.load(raw_data)
|
| 278 |
+
xv, yv, elevations = get_dem_xv_yv_(dem_array, dem_res)
|
| 279 |
+
|
| 280 |
+
res = args.graph_resolution
|
| 281 |
+
|
| 282 |
+
filename = args.filename
|
| 283 |
+
|
| 284 |
+
xv_n = xv[::res, ::res]
|
| 285 |
+
yv_n = yv[::res, ::res]
|
| 286 |
+
elevations_n = elevations[::res, ::res]
|
| 287 |
+
m = elevations_n.shape[1]
|
| 288 |
+
print('terrain shape:', elevations.shape)
|
| 289 |
+
|
| 290 |
+
G, node_features = construct_nx_graph(xv_n, yv_n, elevations_n, triangles=args.triangles, scale=args.edge_weight)
|
| 291 |
+
filename = f'{args.filename}/amp-{amp}-res-{res}-train-{args.dataset_size//1000}k.npz'
|
| 292 |
+
sz = args.dataset_size
|
| 293 |
+
sampling_technique = args.sampling_technique
|
| 294 |
+
construct_pyg_dataset(G,
|
| 295 |
+
node_features,
|
| 296 |
+
filename,
|
| 297 |
+
size=sz,
|
| 298 |
+
sampling_technique=sampling_technique,
|
| 299 |
+
m = 10)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == '__main__':
|
| 303 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/change-heights-dem.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import networkx as nx
|
| 3 |
+
from tqdm import tqdm, trange
|
| 4 |
+
import argparse
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
## Fix centers
|
| 9 |
+
## Change amplitude of Gaussians
|
| 10 |
+
## Save several datasets
|
| 11 |
+
## Run training on the <downsampled version> of the datasets
|
| 12 |
+
|
| 13 |
+
def gaussian_2d(xv, yv, amplitude=1, center_x=0, center_y=0, sigma_x=1, sigma_y=1):
|
| 14 |
+
z1 = (xv - center_x)**2/(2*(sigma_x**2))
|
| 15 |
+
z2 = (yv - center_y)**2/(2*(sigma_y**2))
|
| 16 |
+
z = amplitude * np.exp(-(z1 + z2))
|
| 17 |
+
return z
|
| 18 |
+
|
| 19 |
+
def create_artificial_dem(xv, yv, centers, amp=2.0):
|
| 20 |
+
z_out = np.zeros((xv.shape[0], xv.shape[1]))
|
| 21 |
+
for i in range(len(centers)):
|
| 22 |
+
x_c = centers[i][0]
|
| 23 |
+
y_c = centers[i][1]
|
| 24 |
+
|
| 25 |
+
z = gaussian_2d(xv, yv, amplitude=amp, center_x = x_c, center_y = y_c, sigma_x = 1.0, sigma_y = 1.0)
|
| 26 |
+
z_out += z
|
| 27 |
+
return z_out
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
parser.add_argument("--amplitudes", type=float, nargs='+')
|
| 32 |
+
parser.add_argument("--size", type=int)
|
| 33 |
+
args = parser.parse_args()
|
| 34 |
+
n = args.size
|
| 35 |
+
# create x and y range
|
| 36 |
+
x = np.linspace(0, 10, n)
|
| 37 |
+
y = np.linspace(0, 10, n)
|
| 38 |
+
xv, yv = np.meshgrid(x, y)
|
| 39 |
+
|
| 40 |
+
fig =plt.figure(figsize=(40, 5))
|
| 41 |
+
ax_ct = 1
|
| 42 |
+
centers = np.random.choice(x, size=(15, 2))
|
| 43 |
+
for amp in args.amplitudes:
|
| 44 |
+
name=f'/data/sam/terrain/data/artificial/change-heights/amp-{amp}.npy'
|
| 45 |
+
|
| 46 |
+
img = create_artificial_dem(xv, yv, centers, amp)
|
| 47 |
+
|
| 48 |
+
np.save(name, img)
|
| 49 |
+
|
| 50 |
+
ax = fig.add_subplot(1, len(args.amplitudes), ax_ct, projection='3d')
|
| 51 |
+
|
| 52 |
+
ax.plot_surface(xv, yv, img)
|
| 53 |
+
ax.set_zlim(0, 20)
|
| 54 |
+
ax_ct += 1
|
| 55 |
+
fig.savefig('changing-heights.png')
|
| 56 |
+
return 0
|
| 57 |
+
|
| 58 |
+
if __name__=="__main__":
|
| 59 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/dataset.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
import networkx as nx
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm, trange
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
import time
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
+
from point_sampler import *
|
| 14 |
+
|
| 15 |
+
DATASET_INFO = {'norway': [10, False],
|
| 16 |
+
'phil': [3, True],
|
| 17 |
+
'holland': [1.524, True],
|
| 18 |
+
'la': [28.34, False],
|
| 19 |
+
'artificial': [10/50, False]}
|
| 20 |
+
|
| 21 |
+
# Load DEM data from file,
|
| 22 |
+
# outputs elevations in meters
|
| 23 |
+
def load_dem_data_(filename, imperial=False):
|
| 24 |
+
f = open(filename)
|
| 25 |
+
|
| 26 |
+
lines = f.readlines()
|
| 27 |
+
arr = []
|
| 28 |
+
print("Elevation given in imperial units:", imperial)
|
| 29 |
+
c = 1
|
| 30 |
+
if imperial:
|
| 31 |
+
c = 3.28084
|
| 32 |
+
for i in range(1, len(lines)):
|
| 33 |
+
vals = lines[i].split()
|
| 34 |
+
a = []
|
| 35 |
+
for j in range(len(vals)):
|
| 36 |
+
a.append(float(vals[j])/c)
|
| 37 |
+
arr.append(a)
|
| 38 |
+
arr = np.array(arr)
|
| 39 |
+
print("loaded DEM array with shape:", arr.shape)
|
| 40 |
+
return arr
|
| 41 |
+
|
| 42 |
+
def mesh_to_graph(edge_filename, vertex_filename):
|
| 43 |
+
f = open(edge_filename)
|
| 44 |
+
all_vertices = []
|
| 45 |
+
lines = f.readlines()
|
| 46 |
+
edges = []
|
| 47 |
+
for i in range(len(lines)):
|
| 48 |
+
|
| 49 |
+
vals = lines[i].split()
|
| 50 |
+
edges.append((int(vals[0]), int(vals[1])))
|
| 51 |
+
all_vertices.append(int(vals[0]))
|
| 52 |
+
all_vertices.append(int(vals[1]))
|
| 53 |
+
|
| 54 |
+
unique_vertices = np.sort(np.unique(all_vertices))
|
| 55 |
+
|
| 56 |
+
nx_graph = nx.Graph()
|
| 57 |
+
|
| 58 |
+
temp = {}
|
| 59 |
+
for i in range(len(unique_vertices)):
|
| 60 |
+
temp[unique_vertices[i]] = i
|
| 61 |
+
|
| 62 |
+
f = open(vertex_filename)
|
| 63 |
+
|
| 64 |
+
lines = f.readlines()
|
| 65 |
+
vertices = np.zeros((len(unique_vertices), 3))
|
| 66 |
+
for i in range( len(lines)):
|
| 67 |
+
vals = lines[i].split()
|
| 68 |
+
vertices[i] = [ float(vals[0])/1000, float(vals[1])/1000, float(vals[2])/1000]
|
| 69 |
+
|
| 70 |
+
for i in range(len(edges)):
|
| 71 |
+
v1 = temp[edges[i][0]]
|
| 72 |
+
v2 = temp[edges[i][1]]
|
| 73 |
+
weight = np.linalg.norm(vertices[v1] - vertices[v2], ord=2)
|
| 74 |
+
nx_graph.add_edge(v1, v2, weight=weight)
|
| 75 |
+
|
| 76 |
+
return nx_graph, vertices
|
| 77 |
+
|
| 78 |
+
# Get DEM array xloc and yloc
|
| 79 |
+
# outputs all relevant values in km
|
| 80 |
+
def get_dem_xv_yv_(arr, resolution, visualize=True):
|
| 81 |
+
sz = arr.shape[0]
|
| 82 |
+
total_width = resolution * sz
|
| 83 |
+
x = np.linspace(0, total_width, sz)
|
| 84 |
+
y = np.linspace(0, total_width, sz)
|
| 85 |
+
xv, yv = np.meshgrid(x, y)
|
| 86 |
+
if visualize == True:
|
| 87 |
+
plt.contourf(xv/1000, yv/1000, arr/1000)
|
| 88 |
+
print("minimal elevation:", np.min(arr), "maximum elevation:", np.max(arr))
|
| 89 |
+
plt.axis("scaled")
|
| 90 |
+
plt.colorbar()
|
| 91 |
+
plt.show()
|
| 92 |
+
#return xv, yv, arr
|
| 93 |
+
return xv/1000, yv/1000, arr/1000
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# Construct grid with both cross edges
|
| 97 |
+
def get_array_neighbors_(x, y, left=0, right=500, radius=1):
|
| 98 |
+
temp = [(x - radius, y),
|
| 99 |
+
(x + radius, y),
|
| 100 |
+
(x, y - radius),
|
| 101 |
+
(x, y + radius),
|
| 102 |
+
(x - radius, y - radius),
|
| 103 |
+
(x - radius, y + radius),
|
| 104 |
+
(x + radius, y - radius),
|
| 105 |
+
(x+radius, y + radius)]
|
| 106 |
+
neighbors = temp.copy()
|
| 107 |
+
|
| 108 |
+
for val in temp:
|
| 109 |
+
if val[0] < left or val[0] >= right:
|
| 110 |
+
neighbors.remove(val)
|
| 111 |
+
elif val[1] < left or val[1] >= right:
|
| 112 |
+
neighbors.remove(val)
|
| 113 |
+
|
| 114 |
+
return neighbors
|
| 115 |
+
|
| 116 |
+
# External use ok
|
| 117 |
+
def construct_nx_graph(xv, yv, elevation, triangles=False, p=2, scale=False):
|
| 118 |
+
|
| 119 |
+
n = elevation.shape[0]
|
| 120 |
+
m = elevation.shape[1]
|
| 121 |
+
print("shape", n, m)
|
| 122 |
+
counts = np.reshape(np.arange(0, n*m), (n, m))
|
| 123 |
+
G = nx.Graph()
|
| 124 |
+
|
| 125 |
+
print(triangles)
|
| 126 |
+
|
| 127 |
+
node_features = []
|
| 128 |
+
#fig = plt.figure()
|
| 129 |
+
#ax = fig.add_subplot(projection='3d')
|
| 130 |
+
for i in trange(0, n):
|
| 131 |
+
for j in range(0, m):
|
| 132 |
+
idx1 = counts[i, j]
|
| 133 |
+
G.add_node(idx1)
|
| 134 |
+
node_features.append(np.array([xv[i, j], yv[i, j], elevation[i, j]]))
|
| 135 |
+
neighbors = get_array_neighbors_(i, j, right=elevation.shape[0], radius=1)
|
| 136 |
+
for neighbor in neighbors:
|
| 137 |
+
p1 = np.array([xv[i, j], yv[i, j], elevation[i, j]])
|
| 138 |
+
p2 = np.array([xv[neighbor[0], neighbor[1]], yv[neighbor[0], neighbor[1]], elevation[neighbor[0], neighbor[1]]])
|
| 139 |
+
if scale:
|
| 140 |
+
val = abs(np.random.normal(1.0, 1.0))
|
| 141 |
+
slope = (abs(p1[2] - p2[2]))/(abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]))
|
| 142 |
+
angle_of_elevation = np.abs(np.arctan(p1[2] - p2[2])/np.linalg.norm(p2[:2] - p1[:2], ord=2))
|
| 143 |
+
val = angle_of_elevation
|
| 144 |
+
w = (1 + val) * np.linalg.norm(p1 - p2, ord=p)
|
| 145 |
+
else:
|
| 146 |
+
w = np.linalg.norm(p1 - p2, ord=p)
|
| 147 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 148 |
+
idx2 = counts[neighbor[0], neighbor[1]]
|
| 149 |
+
G.add_edge(idx1, idx2, weight=w)
|
| 150 |
+
print("Number of nodes:", len(node_features))
|
| 151 |
+
print("Number of edges:", G.number_of_edges())
|
| 152 |
+
print(G.edges(0))
|
| 153 |
+
return G, node_features
|
| 154 |
+
|
| 155 |
+
def to_pyg_graph(G):
|
| 156 |
+
distances = []
|
| 157 |
+
|
| 158 |
+
edges = [[], []]
|
| 159 |
+
|
| 160 |
+
print("Formatting edge index.......")
|
| 161 |
+
for e in tqdm(G.edges(data=True)):
|
| 162 |
+
edges[0].append(e[0])
|
| 163 |
+
edges[1].append(e[1])
|
| 164 |
+
edges[0].append(e[1])
|
| 165 |
+
edges[1].append(e[0])
|
| 166 |
+
|
| 167 |
+
distances.append(e[2]['weight'])
|
| 168 |
+
distances.append(e[2]['weight'])
|
| 169 |
+
return edges, distances
|
| 170 |
+
|
| 171 |
+
def generate_probabilities(N, m):
|
| 172 |
+
all_pairs = list(itertools.combinations(range(N), 2))
|
| 173 |
+
probabilities = []
|
| 174 |
+
for src, tar in tqdm(all_pairs):
|
| 175 |
+
hops = abs(src//m - tar//m) + abs(src % m - tar % m )
|
| 176 |
+
probabilities.append(1/(hops**2) if hops > 0 else 1)
|
| 177 |
+
return all_pairs, probabilities
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def construct_dataset(G,
|
| 181 |
+
node_features,
|
| 182 |
+
filename,
|
| 183 |
+
sampling_method,
|
| 184 |
+
num_srcs,
|
| 185 |
+
samples_per_source,
|
| 186 |
+
rows=100,
|
| 187 |
+
cols=100,
|
| 188 |
+
threshhold=0.2):
|
| 189 |
+
edges, distances = to_pyg_graph(G)
|
| 190 |
+
|
| 191 |
+
if sampling_method == 'single-source-random':
|
| 192 |
+
src_nodes = np.random.choice(len(node_features), size=num_srcs)
|
| 193 |
+
sampling_fn = random_sampling
|
| 194 |
+
elif sampling_method == 'critical-point-source':
|
| 195 |
+
node_features = np.array(node_features)
|
| 196 |
+
c1 = node_features[:, 0].reshape(rows, cols)
|
| 197 |
+
c2 = node_features[:, 1].reshape(rows, cols)
|
| 198 |
+
c3 = node_features[:, 2].reshape(rows, cols)
|
| 199 |
+
terrain = torch.tensor(np.stack([c1, c2, c3]), dtype=torch.float)
|
| 200 |
+
terrain = np.transpose(terrain, (1, 2, 0))
|
| 201 |
+
print(terrain.size())
|
| 202 |
+
src_nodes = find_critical_points(terrain, threshhold)
|
| 203 |
+
sampling_fn = random_sampling
|
| 204 |
+
elif sampling_method == 'distance-based':
|
| 205 |
+
src_nodes = np.random.choice(len(node_features), size=num_srcs)
|
| 206 |
+
sampling_fn = distance_based
|
| 207 |
+
else:
|
| 208 |
+
raise NotImplementedError("please choose between 'single-source-random', 'critical-point-source', 'distance-based'")
|
| 209 |
+
srcs = []
|
| 210 |
+
tars = []
|
| 211 |
+
lengths = []
|
| 212 |
+
print("Number of source nodes:", len(src_nodes))
|
| 213 |
+
print("Generating shortest path distances.....")
|
| 214 |
+
for src in tqdm(src_nodes):
|
| 215 |
+
source, target, length = sampling_fn(G, samples_per_source, src=src)
|
| 216 |
+
srcs += source
|
| 217 |
+
tars += target
|
| 218 |
+
lengths += length
|
| 219 |
+
print("Number of lengths in dataset:", len(lengths))
|
| 220 |
+
print("Saved dataset in:", filename)
|
| 221 |
+
np.savez(filename,
|
| 222 |
+
edge_index = edges,
|
| 223 |
+
distances=distances,
|
| 224 |
+
srcs = srcs,
|
| 225 |
+
tars = tars,
|
| 226 |
+
lengths = lengths,
|
| 227 |
+
node_features=node_features)
|
| 228 |
+
|
| 229 |
+
def main():
|
| 230 |
+
parser = argparse.ArgumentParser()
|
| 231 |
+
parser.add_argument('--name', type=str)
|
| 232 |
+
parser.add_argument('--raw-data', type=str)
|
| 233 |
+
parser.add_argument('--filename', type=str)
|
| 234 |
+
parser.add_argument('--graph-resolution', type=int)
|
| 235 |
+
parser.add_argument('--dataset-size', type=int)
|
| 236 |
+
parser.add_argument('--num-sources', type=int)
|
| 237 |
+
parser.add_argument('--sampling-technique', type=str, default='random')
|
| 238 |
+
parser.add_argument('--triangles', action='store_true')
|
| 239 |
+
parser.add_argument('--edge-weight', action='store_true')
|
| 240 |
+
parser.add_argument('--change-heights', action='store_true')
|
| 241 |
+
parser.add_argument('--critical-point-threshhold', type=float, default=0.2)
|
| 242 |
+
|
| 243 |
+
args = parser.parse_args()
|
| 244 |
+
dem_res = DATASET_INFO[args.name][0]
|
| 245 |
+
imperial = DATASET_INFO[args.name][1]
|
| 246 |
+
if 'meshes' in args.raw_data:
|
| 247 |
+
edge_filename = os.path.join(args.raw_data, 'percent_edges')
|
| 248 |
+
vertex_filename = os.path.join(args.raw_data, 'percent_vertices')
|
| 249 |
+
G, node_features = mesh_to_graph(edge_filename, vertex_filename)
|
| 250 |
+
m = 10
|
| 251 |
+
else:
|
| 252 |
+
if args.name == 'la' or args.name == 'artificial':
|
| 253 |
+
dem_array = np.load(args.raw_data)
|
| 254 |
+
else:
|
| 255 |
+
dem_array = load_dem_data_(args.raw_data, imperial)
|
| 256 |
+
xv, yv, elevations = get_dem_xv_yv_(dem_array, dem_res)
|
| 257 |
+
row,col = np.random.choice(elevations.shape[0], size=[2,])
|
| 258 |
+
res = args.graph_resolution
|
| 259 |
+
|
| 260 |
+
filename = args.filename
|
| 261 |
+
|
| 262 |
+
xv_n = xv[::res, ::res]
|
| 263 |
+
yv_n = yv[::res, ::res]
|
| 264 |
+
elevations_n = elevations[::res, ::res]
|
| 265 |
+
print(np.min(elevations_n))
|
| 266 |
+
print('terrain shape:', elevations_n.shape)
|
| 267 |
+
print('resolution:', res)
|
| 268 |
+
if args.change_heights:
|
| 269 |
+
for k in range(1, 60):
|
| 270 |
+
filename = f'/data/sam/terrain/data/{args.name}/uncertainty/50/50k-{k}.npz'
|
| 271 |
+
uncertainty = np.random.uniform(-0.050, 0.050, size=elevations_n.shape)
|
| 272 |
+
elevations_n = uncertainty + elevations_n
|
| 273 |
+
|
| 274 |
+
G, node_features = construct_nx_graph(xv_n,
|
| 275 |
+
yv_n,
|
| 276 |
+
elevations_n,
|
| 277 |
+
triangles=args.triangles,
|
| 278 |
+
scale=args.edge_weight)
|
| 279 |
+
sz = args.dataset_size
|
| 280 |
+
sampling_technique = args.sampling_technique
|
| 281 |
+
|
| 282 |
+
construct_dataset(G = G,
|
| 283 |
+
node_features = node_features,
|
| 284 |
+
filename = filename,
|
| 285 |
+
num_srcs = args.num_sources,
|
| 286 |
+
samples_per_source = args.dataset_size//args.num_sources,
|
| 287 |
+
sampling_method=sampling_technique,
|
| 288 |
+
rows = elevations_n.shape[0],
|
| 289 |
+
cols = elevations_n.shape[1],
|
| 290 |
+
threshhold = args.critical_point_threshhold)
|
| 291 |
+
else:
|
| 292 |
+
G, node_features = construct_nx_graph(xv_n,
|
| 293 |
+
yv_n,
|
| 294 |
+
elevations_n,
|
| 295 |
+
triangles=args.triangles,
|
| 296 |
+
scale=args.edge_weight)
|
| 297 |
+
filename = args.filename
|
| 298 |
+
sz = args.dataset_size
|
| 299 |
+
sampling_technique = args.sampling_technique
|
| 300 |
+
|
| 301 |
+
construct_dataset(G = G,
|
| 302 |
+
node_features = node_features,
|
| 303 |
+
filename = filename,
|
| 304 |
+
num_srcs = args.num_sources,
|
| 305 |
+
samples_per_source = args.dataset_size//args.num_sources,
|
| 306 |
+
sampling_method=sampling_technique,
|
| 307 |
+
rows = elevations_n.shape[0],
|
| 308 |
+
cols = elevations_n.shape[1],
|
| 309 |
+
threshhold = args.critical_point_threshhold)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
if __name__ == '__main__':
|
| 313 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/generate-test-dataset.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
import networkx as nx
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm, trange
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
import time
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
|
| 13 |
+
DATASET_INFO = {'norway': [10, False], 'phil': [3, True], 'holland': [1.524, True], 'la': [28.34, False]}
|
| 14 |
+
|
| 15 |
+
# Load DEM data from file,
|
| 16 |
+
# outputs elevations in meters
|
| 17 |
+
def load_dem_data_(filename, imperial=False):
|
| 18 |
+
f = open(filename)
|
| 19 |
+
|
| 20 |
+
lines = f.readlines()
|
| 21 |
+
arr = []
|
| 22 |
+
print("Elevation given in imperial units:", imperial)
|
| 23 |
+
c = 1
|
| 24 |
+
if imperial:
|
| 25 |
+
c = 3.28084
|
| 26 |
+
for i in range(1, len(lines)):
|
| 27 |
+
vals = lines[i].split()
|
| 28 |
+
a = []
|
| 29 |
+
for j in range(len(vals)):
|
| 30 |
+
a.append(float(vals[j])/c)
|
| 31 |
+
arr.append(a)
|
| 32 |
+
arr = np.array(arr)
|
| 33 |
+
print("loaded DEM array with shape:", arr.shape)
|
| 34 |
+
return arr
|
| 35 |
+
|
| 36 |
+
# Get DEM array xloc and yloc
|
| 37 |
+
# outputs all relevant values in km
|
| 38 |
+
def get_dem_xv_yv_(arr, resolution, visualize=True):
|
| 39 |
+
sz = arr.shape[0]
|
| 40 |
+
total_width = resolution * sz
|
| 41 |
+
x = np.linspace(0, total_width, sz)
|
| 42 |
+
y = np.linspace(0, total_width, sz)
|
| 43 |
+
xv, yv = np.meshgrid(x, y)
|
| 44 |
+
if visualize == True:
|
| 45 |
+
plt.contourf(xv/1000, yv/1000, arr/1000)
|
| 46 |
+
print("minimal elevation:", np.min(arr/1000), "maximum elevation:", np.max(arr/1000))
|
| 47 |
+
plt.axis("scaled")
|
| 48 |
+
plt.colorbar()
|
| 49 |
+
plt.show()
|
| 50 |
+
#return xv, yv, arr
|
| 51 |
+
return xv/1000, yv/1000, arr/1000
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# Construct grid
|
| 55 |
+
def get_array_neighbors_(x, y, left=0, right=500, radius=1):
|
| 56 |
+
temp = [(x - radius, y), (x + radius, y), (x, y - radius), (x, y + radius)]
|
| 57 |
+
neighbors = temp.copy()
|
| 58 |
+
|
| 59 |
+
for val in temp:
|
| 60 |
+
if val[0] < left or val[0] >= right:
|
| 61 |
+
neighbors.remove(val)
|
| 62 |
+
elif val[1] < left or val[1] >= right:
|
| 63 |
+
neighbors.remove(val)
|
| 64 |
+
|
| 65 |
+
return neighbors
|
| 66 |
+
|
| 67 |
+
# External use ok
|
| 68 |
+
def construct_nx_graph(xv, yv, elevation, triangles=False, p=2):
|
| 69 |
+
|
| 70 |
+
n = elevation.shape[0]
|
| 71 |
+
m = elevation.shape[1]
|
| 72 |
+
print("shape", n, m)
|
| 73 |
+
counts = np.reshape(np.arange(0, n*m), (n, m))
|
| 74 |
+
G = nx.Graph()
|
| 75 |
+
|
| 76 |
+
node_features = []
|
| 77 |
+
#fig = plt.figure()
|
| 78 |
+
#ax = fig.add_subplot(projection='3d')
|
| 79 |
+
for i in trange(0, n):
|
| 80 |
+
for j in range(0, m):
|
| 81 |
+
idx1 = counts[i, j]
|
| 82 |
+
G.add_node(idx1)
|
| 83 |
+
node_features.append(np.array([xv[i, j], yv[i, j], elevation[i, j]]))
|
| 84 |
+
neighbors = get_array_neighbors_(i, j, right=elevation.shape[0], radius=1)
|
| 85 |
+
for neighbor in neighbors:
|
| 86 |
+
p1 = np.array([xv[i, j], yv[i, j], elevation[i, j]])
|
| 87 |
+
p2 = np.array([xv[neighbor[0], neighbor[1]], yv[neighbor[0], neighbor[1]], elevation[neighbor[0], neighbor[1]]])
|
| 88 |
+
w = np.linalg.norm(p1 - p2, ord=p)
|
| 89 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 90 |
+
idx2 = counts[neighbor[0], neighbor[1]]
|
| 91 |
+
G.add_edge(idx1, idx2, weight=w)
|
| 92 |
+
print("Size of graph:", len(node_features))
|
| 93 |
+
if triangles:
|
| 94 |
+
for i in trange(0, n - 1):
|
| 95 |
+
for j in range(0, m - 1):
|
| 96 |
+
# index cell by top left coordinate
|
| 97 |
+
triangle_edge = [(counts[i, j], counts[i + 1, j + 1]), (counts[i + 1, j], counts[i, j + 1])]
|
| 98 |
+
for edge in triangle_edge:
|
| 99 |
+
p1 = node_features[edge[0]]
|
| 100 |
+
p2 = node_features[edge[1]]
|
| 101 |
+
w = np.linalg.norm(p1 - p2, ord = p)
|
| 102 |
+
G.add_edge(edge[0], edge[1], weight=w)
|
| 103 |
+
#fig.savefig('../images/norway-250.png')
|
| 104 |
+
return G, node_features
|
| 105 |
+
|
| 106 |
+
def to_pyg_graph(G):
|
| 107 |
+
distances = []
|
| 108 |
+
|
| 109 |
+
edges = [[], []]
|
| 110 |
+
|
| 111 |
+
print("Formatting edge index.......")
|
| 112 |
+
for e in tqdm(G.edges(data=True)):
|
| 113 |
+
edges[0].append(e[0])
|
| 114 |
+
edges[1].append(e[1])
|
| 115 |
+
edges[0].append(e[1])
|
| 116 |
+
edges[1].append(e[0])
|
| 117 |
+
|
| 118 |
+
distances.append(e[2]['weight'])
|
| 119 |
+
distances.append(e[2]['weight'])
|
| 120 |
+
return edges, distances
|
| 121 |
+
|
| 122 |
+
def generate_probabilities(N, m):
|
| 123 |
+
all_pairs = list(itertools.combinations(range(N), 2))
|
| 124 |
+
probabilities = []
|
| 125 |
+
for src, tar in tqdm(all_pairs):
|
| 126 |
+
hops = abs(src//m - tar//m) + abs(src % m - tar % m )
|
| 127 |
+
probabilities.append(1/(hops**2) if hops > 0 else 1)
|
| 128 |
+
return all_pairs, probabilities
|
| 129 |
+
|
| 130 |
+
def get_neighbors(center, n=1):
|
| 131 |
+
ret = []
|
| 132 |
+
for dx in range(-n, n + 1):
|
| 133 |
+
ydiff = n - abs(dx)
|
| 134 |
+
for dy in range(-ydiff, ydiff + 1):
|
| 135 |
+
ret.append((center[0] + dx, center[1] + dy))
|
| 136 |
+
return ret
|
| 137 |
+
|
| 138 |
+
# n = rows
|
| 139 |
+
# m = columns
|
| 140 |
+
def generate_src_tar_pairs(node_features, n, m, size=100, sampling_technique='random'):
|
| 141 |
+
num_nodes = len(node_features)
|
| 142 |
+
node_idxs = np.reshape(np.arange(n * m), (n, m))
|
| 143 |
+
tars = []
|
| 144 |
+
if sampling_technique == 'random':
|
| 145 |
+
srcs = np.random.choice(np.arange(num_nodes), size = size)
|
| 146 |
+
tars = np.random.choice(np.arange(num_nodes), size = size)
|
| 147 |
+
elif sampling_technique == 'expanding-radius':
|
| 148 |
+
radii = [60, 100, 120, 140, 160, 200]
|
| 149 |
+
num_per_radius = 20
|
| 150 |
+
num_srcs = size // (len(radii) * num_per_radius)
|
| 151 |
+
srcs = np.random.choice(np.arange(num_nodes), size = num_srcs)
|
| 152 |
+
for s in srcs:
|
| 153 |
+
x_loc = s//n
|
| 154 |
+
y_loc = s % m
|
| 155 |
+
for r in radii:
|
| 156 |
+
# collect all nodes at radii 5
|
| 157 |
+
nodes_at_radii = get_neighbors((x_loc, y_loc), n=r)
|
| 158 |
+
for i in range(num_per_radius):
|
| 159 |
+
node = nodes_at_radii[np.random.choice(len(nodes_at_radii), replace = False)]
|
| 160 |
+
if node[0] >= n or node[0] < 0:
|
| 161 |
+
continue
|
| 162 |
+
if node[1] >= m or node[1] < 0:
|
| 163 |
+
continue
|
| 164 |
+
tar = node_idxs[node[0], node[1]]
|
| 165 |
+
tars.append(tar)
|
| 166 |
+
# sample sources from top 100 height points.
|
| 167 |
+
elif sampling_technique == 'height-sensitive-random':
|
| 168 |
+
node_features = np.array(node_features)
|
| 169 |
+
sorted_height_array = np.argsort(node_features[:, 2])
|
| 170 |
+
num_srcs = 10
|
| 171 |
+
num_per_src = int(size//20)
|
| 172 |
+
srcs = []
|
| 173 |
+
src_nodes = np.random.choice(sorted_height_array[-1000000:], size = num_srcs)
|
| 174 |
+
for s in tqdm(src_nodes):
|
| 175 |
+
tar_nodes = np.random.choice(len(node_features), size=num_per_src)
|
| 176 |
+
for t in tar_nodes:
|
| 177 |
+
tars.append(t)
|
| 178 |
+
srcs.append(s)
|
| 179 |
+
# check that all src, target nodes are in the graph
|
| 180 |
+
for i in range(len(srcs)):
|
| 181 |
+
assert srcs[i] >= 0 and srcs[i] < len(node_features)
|
| 182 |
+
assert tars[i] >=0 and tars[i] < len(node_features)
|
| 183 |
+
return srcs, tars
|
| 184 |
+
|
| 185 |
+
def single_src_dataset(G, node_features, filename, size=100):
|
| 186 |
+
num_nodes = len(node_features)
|
| 187 |
+
lengths = []
|
| 188 |
+
srcs = []
|
| 189 |
+
tars = []
|
| 190 |
+
node_features = np.array(node_features)
|
| 191 |
+
sorted_height_array = np.argsort(node_features[:, 2])
|
| 192 |
+
num_srcs = 10
|
| 193 |
+
src_nodes = np.random.choice(sorted_height_array[-1000000:], size = num_srcs)
|
| 194 |
+
for i in trange(len(src_nodes)):
|
| 195 |
+
#src = np.random.choice(num_nodes)
|
| 196 |
+
src = src_nodes[i]
|
| 197 |
+
all_pairs_shortest_paths = nx.single_source_dijkstra_path_length(G, src, weight='weight')
|
| 198 |
+
for tar in all_pairs_shortest_paths:
|
| 199 |
+
tars.append(tar)
|
| 200 |
+
srcs.append(src)
|
| 201 |
+
lengths.append(all_pairs_shortest_paths[tar])
|
| 202 |
+
|
| 203 |
+
return srcs, tars, lengths
|
| 204 |
+
|
| 205 |
+
def construct_pyg_dataset(G, node_features, filename, size=100, distance_based=False, m=10):
|
| 206 |
+
Nodes = np.sort(list(G.nodes()))
|
| 207 |
+
|
| 208 |
+
edges, distances = to_pyg_graph(G)
|
| 209 |
+
|
| 210 |
+
srcs = []
|
| 211 |
+
tars = []
|
| 212 |
+
lengths = []
|
| 213 |
+
print("Generating shortest paths......")
|
| 214 |
+
#jobs = []
|
| 215 |
+
#pool = mp.Pool(processes=20)
|
| 216 |
+
srcs, tars, lengths = single_src_dataset(G, node_features, filename, size=size)
|
| 217 |
+
# samples = np.random.choice(len(srcs), size=100000, replace=False)
|
| 218 |
+
srcs = np.array(srcs)
|
| 219 |
+
tars = np.array(tars)
|
| 220 |
+
lengths = np.array(lengths)
|
| 221 |
+
# srcs, tars = generate_src_tar_pairs(node_features, m, m, size = size, sampling_technique = 'random')
|
| 222 |
+
# for i in trange(len(srcs)):
|
| 223 |
+
# s = srcs[i]
|
| 224 |
+
# t = tars[i]
|
| 225 |
+
# length = nx.shortest_path_length(G, s, t, weight='weight')
|
| 226 |
+
# lengths.append(length)
|
| 227 |
+
|
| 228 |
+
print("Saved dataset in:", filename)
|
| 229 |
+
np.savez(filename,
|
| 230 |
+
edge_index = edges,
|
| 231 |
+
distances=distances,
|
| 232 |
+
nodes=Nodes,
|
| 233 |
+
srcs = srcs,
|
| 234 |
+
tars = tars,
|
| 235 |
+
lengths = lengths,
|
| 236 |
+
node_features=node_features)
|
| 237 |
+
|
| 238 |
+
def main():
|
| 239 |
+
parser = argparse.ArgumentParser()
|
| 240 |
+
parser.add_argument('--name', type=str)
|
| 241 |
+
parser.add_argument('--raw-data', type=str)
|
| 242 |
+
parser.add_argument('--filename', type=str)
|
| 243 |
+
parser.add_argument('--graph-resolution', type=int)
|
| 244 |
+
parser.add_argument('--dataset-size', type=int)
|
| 245 |
+
parser.add_argument('--distance-based-sampling', action='store_true')
|
| 246 |
+
parser.add_argument('--triangles', action='store_true')
|
| 247 |
+
|
| 248 |
+
args = parser.parse_args()
|
| 249 |
+
dem_res = DATASET_INFO[args.name][0]
|
| 250 |
+
imperial = DATASET_INFO[args.name][1]
|
| 251 |
+
if args.name == 'la':
|
| 252 |
+
dem_array = np.load(args.raw_data)
|
| 253 |
+
else:
|
| 254 |
+
dem_array = load_dem_data_(args.raw_data, imperial)
|
| 255 |
+
xv, yv, elevations = get_dem_xv_yv_(dem_array, dem_res)
|
| 256 |
+
# row,col = np.random.choice(elevations.shape[0], size=[2,])
|
| 257 |
+
# print(row, col)
|
| 258 |
+
# Norway
|
| 259 |
+
# row = 122
|
| 260 |
+
# col = 1647
|
| 261 |
+
## Philadelphia
|
| 262 |
+
# row = 181
|
| 263 |
+
# col = 613
|
| 264 |
+
## holland
|
| 265 |
+
# row = 439
|
| 266 |
+
# col = 471
|
| 267 |
+
## L A
|
| 268 |
+
# 624 510
|
| 269 |
+
# row = 624
|
| 270 |
+
# col = 512
|
| 271 |
+
# xv_n = xv[row:row+ 100, col:col+100]
|
| 272 |
+
# yv_n = yv[row:row+100, col:col+100]
|
| 273 |
+
# elevations_n = elevations[row:row+100, col:col+100]
|
| 274 |
+
|
| 275 |
+
res = args.graph_resolution
|
| 276 |
+
sz = args.dataset_size
|
| 277 |
+
filename = args.filename
|
| 278 |
+
xv_n = xv[::res, ::res]
|
| 279 |
+
yv_n = yv[::res, ::res]
|
| 280 |
+
elevations_n = elevations[::res, ::res]
|
| 281 |
+
print('terrain shape:', elevations.shape)
|
| 282 |
+
|
| 283 |
+
G, node_features = construct_nx_graph(xv_n, yv_n, elevations_n, triangles=args.triangles)
|
| 284 |
+
|
| 285 |
+
construct_pyg_dataset(G,
|
| 286 |
+
node_features,
|
| 287 |
+
filename,
|
| 288 |
+
size=sz,
|
| 289 |
+
distance_based=args.distance_based_sampling,
|
| 290 |
+
m = elevations_n.shape[1])
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == '__main__':
|
| 294 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/patch_dataset.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
import networkx as nx
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm, trange
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
import time
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
|
| 13 |
+
DATASET_INFO = {'norway': [10, False], 'phil': [3, True], 'holland': [1.524, True], 'la': [28.34, False]}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TerrainPatchesData(Data):
|
| 17 |
+
def __inc__(self, key, value, *args, **kwargs):
|
| 18 |
+
if key == 'src':
|
| 19 |
+
return self.x.size(0)
|
| 20 |
+
if key == 'tar':
|
| 21 |
+
return self.x.size(0)
|
| 22 |
+
return super().__inc__(key, value, *args, **kwargs)
|
| 23 |
+
|
| 24 |
+
# Load DEM data from file
|
| 25 |
+
def load_dem_data_(filename, imperial=False):
|
| 26 |
+
f = open(filename)
|
| 27 |
+
|
| 28 |
+
lines = f.readlines()
|
| 29 |
+
arr = []
|
| 30 |
+
print("Elevation given in imperial units:", imperial)
|
| 31 |
+
c = 1
|
| 32 |
+
if imperial:
|
| 33 |
+
c = 3.28084
|
| 34 |
+
for i in range(1, len(lines)):
|
| 35 |
+
vals = lines[i].split()
|
| 36 |
+
a = []
|
| 37 |
+
for j in range(len(vals)):
|
| 38 |
+
a.append(float(vals[j])/c)
|
| 39 |
+
arr.append(a)
|
| 40 |
+
arr = np.array(arr)
|
| 41 |
+
print("loaded DEM array with shape:", arr.shape)
|
| 42 |
+
return arr
|
| 43 |
+
|
| 44 |
+
# Get DEM array xloc and yloc
|
| 45 |
+
def get_dem_xv_yv_(arr, resolution, visualize=True):
|
| 46 |
+
x_sz = arr.shape[0]
|
| 47 |
+
total_width_x = resolution * x_sz
|
| 48 |
+
y_sz = arr.shape[1]
|
| 49 |
+
total_width_y = resolution * y_sz
|
| 50 |
+
x = np.linspace(0, total_width_x, x_sz)
|
| 51 |
+
y = np.linspace(0, total_width_y, y_sz)
|
| 52 |
+
xv, yv = np.meshgrid(x, y, indexing='ij')
|
| 53 |
+
if visualize == True:
|
| 54 |
+
plt.contourf(xv/1000, yv/1000, arr/1000, origin='upper')
|
| 55 |
+
print("minimum elevation:", np.min(arr/1000), "maximum elevation:", np.max(arr/1000))
|
| 56 |
+
plt.axis("scaled")
|
| 57 |
+
plt.colorbar()
|
| 58 |
+
plt.savefig('la-county-contour')
|
| 59 |
+
return xv/1000, yv/1000, arr/1000
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Construct grid
|
| 63 |
+
def get_array_neighbors_(x, y, left=0, right=500, top=0, bottom=500, radius=1):
|
| 64 |
+
temp = [(x - radius, y), (x + radius, y), (x, y - radius), (x, y + radius)]
|
| 65 |
+
neighbors = temp.copy()
|
| 66 |
+
|
| 67 |
+
for val in temp:
|
| 68 |
+
if val[0] < left or val[0] >= right:
|
| 69 |
+
neighbors.remove(val)
|
| 70 |
+
elif val[1] < top or val[1] >= bottom:
|
| 71 |
+
neighbors.remove(val)
|
| 72 |
+
|
| 73 |
+
return neighbors
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# External use ok
|
| 77 |
+
def construct_nx_graph(xv, yv, elevation, triangles=False, p=2, scale=False):
|
| 78 |
+
|
| 79 |
+
n = elevation.shape[0]
|
| 80 |
+
m = elevation.shape[1]
|
| 81 |
+
counts = np.reshape(np.arange(0, n*m), (n, m))
|
| 82 |
+
G = nx.Graph()
|
| 83 |
+
|
| 84 |
+
node_features = []
|
| 85 |
+
#fig = plt.figure()
|
| 86 |
+
#ax = fig.add_subplot(projection='3d')
|
| 87 |
+
for i in range(0, n):
|
| 88 |
+
for j in range(0, m):
|
| 89 |
+
idx1 = counts[i, j]
|
| 90 |
+
G.add_node(idx1)
|
| 91 |
+
node_features.append(np.array([xv[i, j], yv[i, j], elevation[i, j]]))
|
| 92 |
+
neighbors = get_array_neighbors_(i, j, right=elevation.shape[0], bottom=elevation.shape[1], radius=1)
|
| 93 |
+
for neighbor in neighbors:
|
| 94 |
+
p1 = np.array([xv[i, j], yv[i, j], elevation[i, j]])
|
| 95 |
+
|
| 96 |
+
p2 = np.array([xv[neighbor[0], neighbor[1]], yv[neighbor[0], neighbor[1]], elevation[neighbor[0], neighbor[1]]])
|
| 97 |
+
if scale:
|
| 98 |
+
slope = (abs(p1[2] - p2[2]))/(abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]))
|
| 99 |
+
# w = np.log(1 + slope)
|
| 100 |
+
deg_angle = np.arctan(slope) * (180/np.pi)
|
| 101 |
+
w = np.power(deg_angle, 1.2)
|
| 102 |
+
else:
|
| 103 |
+
w = np.linalg.norm(p1 - p2, ord=p)
|
| 104 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 105 |
+
idx2 = counts[neighbor[0], neighbor[1]]
|
| 106 |
+
G.add_edge(idx1, idx2, weight=w)
|
| 107 |
+
if triangles:
|
| 108 |
+
for i in range(0, n - 1):
|
| 109 |
+
for j in range(0, m - 1):
|
| 110 |
+
# index cell by top left coordinate
|
| 111 |
+
triangle_edge = [(counts[i, j], counts[i + 1, j + 1]), (counts[i + 1, j], counts[i, j + 1])]
|
| 112 |
+
edge = triangle_edge[np.random.choice(2)]
|
| 113 |
+
for edge in triangle_edge:
|
| 114 |
+
p1 = node_features[edge[0]]
|
| 115 |
+
p2 = node_features[edge[1]]
|
| 116 |
+
if scale:
|
| 117 |
+
slope = (abs(p1[2] - p2[2]))/(abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]))
|
| 118 |
+
# w = np.log(1 + slope)
|
| 119 |
+
deg_angle = np.arctan(slope) * (180/np.pi)
|
| 120 |
+
w = np.power(deg_angle, 1.2)
|
| 121 |
+
else:
|
| 122 |
+
w = np.linalg.norm(p1 - p2, ord=p)
|
| 123 |
+
#ax.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], color='black')
|
| 124 |
+
G.add_edge(edge[0], edge[1], weight=w)
|
| 125 |
+
#fig.savefig('../images/norway-250.png')
|
| 126 |
+
return G, node_features
|
| 127 |
+
|
| 128 |
+
def get_patches_(xv, yv, dem_array, patch_size, overlap):
|
| 129 |
+
patches = []
|
| 130 |
+
patch_graphs = []
|
| 131 |
+
patch_features = []
|
| 132 |
+
for i in trange(0, dem_array.shape[0] , patch_size - overlap):
|
| 133 |
+
for j in range(0, dem_array.shape[1], patch_size- overlap):
|
| 134 |
+
xv_patch = xv[i:i + patch_size, j:j+patch_size]
|
| 135 |
+
yv_patch = yv[i:i+patch_size, j : j+patch_size]
|
| 136 |
+
patch = dem_array[i : i + patch_size, j : j + patch_size].copy()
|
| 137 |
+
graph, node_features = construct_nx_graph(xv_patch, yv_patch, patch)
|
| 138 |
+
# print(patch.shape)
|
| 139 |
+
# print(list(nx.selfloop_edges(graph)))
|
| 140 |
+
patches.append(patch)
|
| 141 |
+
patch_graphs.append(graph)
|
| 142 |
+
patch_features.append(node_features)
|
| 143 |
+
|
| 144 |
+
return patches, patch_graphs, patch_features
|
| 145 |
+
|
| 146 |
+
def get_edge_index(G):
|
| 147 |
+
weights = []
|
| 148 |
+
|
| 149 |
+
edges = [[], []]
|
| 150 |
+
|
| 151 |
+
for e in G.edges(data=True):
|
| 152 |
+
edges[0].append(e[0])
|
| 153 |
+
edges[1].append(e[1])
|
| 154 |
+
edges[0].append(e[1])
|
| 155 |
+
edges[1].append(e[0])
|
| 156 |
+
|
| 157 |
+
weights.append(e[2]['weight'])
|
| 158 |
+
weights.append(e[2]['weight'])
|
| 159 |
+
return edges, weights
|
| 160 |
+
|
| 161 |
+
def construct_patch_dataset(xv, yv, dem_array, patch_size, sz, triangles=False, scale=False):
|
| 162 |
+
all_data = []
|
| 163 |
+
print("size of dataset:", sz, "patch sizes:", patch_size)
|
| 164 |
+
n = dem_array.shape[0]
|
| 165 |
+
m = dem_array.shape[1]
|
| 166 |
+
nc = 40
|
| 167 |
+
cx = np.random.choice(n-patch_size, size=nc, replace=False)
|
| 168 |
+
cy = np.random.choice(m - patch_size, size=nc, replace=False)
|
| 169 |
+
for i in range(nc):
|
| 170 |
+
xr = cx[i]
|
| 171 |
+
yr = cy[i]
|
| 172 |
+
xv_patch = xv[xr: xr + patch_size, yr: yr+patch_size]
|
| 173 |
+
yv_patch = yv[xr: xr + patch_size, yr: yr+patch_size]
|
| 174 |
+
patch = dem_array[xr: xr + patch_size, yr: yr+patch_size]
|
| 175 |
+
graph, node_features = construct_nx_graph(xv_patch,
|
| 176 |
+
yv_patch,
|
| 177 |
+
patch,
|
| 178 |
+
triangles=triangles,
|
| 179 |
+
scale=scale)
|
| 180 |
+
|
| 181 |
+
edge_index, weights = get_edge_index(graph)
|
| 182 |
+
for m in trange(patch_size * patch_size):
|
| 183 |
+
for n in range(m + 1, patch_size * patch_size):
|
| 184 |
+
shortest_path = nx.shortest_path_length(graph, m, n, weight='weight')
|
| 185 |
+
data=TerrainPatchesData(x=node_features,
|
| 186 |
+
edge_index = edge_index,
|
| 187 |
+
edge_attr=weights,
|
| 188 |
+
src=m,
|
| 189 |
+
tar=n,
|
| 190 |
+
length=shortest_path)
|
| 191 |
+
all_data.append(data)
|
| 192 |
+
|
| 193 |
+
# for i in trange(sz):
|
| 194 |
+
# c = np.random.randint(low = 0, high=5)
|
| 195 |
+
# #c = 0
|
| 196 |
+
# xr = cx[c]
|
| 197 |
+
# yr = cy[c]
|
| 198 |
+
# xv_patch = xv[xr: xr + patch_size, yr: yr+patch_size]
|
| 199 |
+
# yv_patch = yv[xr: xr + patch_size, yr: yr+patch_size]
|
| 200 |
+
# patch = dem_array[xr: xr + patch_size, yr: yr+patch_size]
|
| 201 |
+
# graph, node_features = construct_nx_graph(xv_patch,
|
| 202 |
+
# yv_patch,
|
| 203 |
+
# patch,
|
| 204 |
+
# triangles=triangles,
|
| 205 |
+
# scale=scale)
|
| 206 |
+
|
| 207 |
+
# edge_index, weights = get_edge_index(graph)
|
| 208 |
+
|
| 209 |
+
# src, tar = np.random.choice(len(node_features), [2, ], replace=False)
|
| 210 |
+
# if src == tar:
|
| 211 |
+
# continue
|
| 212 |
+
# shortest_path = nx.shortest_path_length(graph, src, tar, weight='weight')
|
| 213 |
+
# data=TerrainPatchesData(x=node_features,
|
| 214 |
+
# edge_index = edge_index,
|
| 215 |
+
# edge_attr=weights,
|
| 216 |
+
# src=src,
|
| 217 |
+
# tar=tar,
|
| 218 |
+
# length=shortest_path)
|
| 219 |
+
# all_data.append(data)
|
| 220 |
+
return all_data, np.hstack((cx, cy))
|
| 221 |
+
|
| 222 |
+
def main():
|
| 223 |
+
parser = argparse.ArgumentParser()
|
| 224 |
+
parser.add_argument('--name', type=str)
|
| 225 |
+
parser.add_argument('--raw-data', type=str)
|
| 226 |
+
parser.add_argument('--filename', type=str) # saves should be named `gr-{graph-resolution}-ps-{patch-size}-ol-{overlap}`
|
| 227 |
+
parser.add_argument('--graph-resolution', type=int)
|
| 228 |
+
parser.add_argument('--patch-size', type=int)
|
| 229 |
+
parser.add_argument('--dataset-size', type=int)
|
| 230 |
+
parser.add_argument('--triangles', action='store_true')
|
| 231 |
+
parser.add_argument('--scale', action='store_true')
|
| 232 |
+
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
|
| 235 |
+
dem_res = DATASET_INFO[args.name][0]
|
| 236 |
+
imperial = DATASET_INFO[args.name][1]
|
| 237 |
+
|
| 238 |
+
if args.name == 'la':
|
| 239 |
+
dem_array = np.load(args.raw_data)
|
| 240 |
+
else:
|
| 241 |
+
dem_array = load_dem_data_(args.raw_data, imperial)
|
| 242 |
+
|
| 243 |
+
xv, yv, elevations = get_dem_xv_yv_(dem_array, dem_res)
|
| 244 |
+
print('total elevation shape:', elevations.shape)
|
| 245 |
+
xv = xv[::args.graph_resolution, :2000:args.graph_resolution]
|
| 246 |
+
yv = yv[::args.graph_resolution, :2000:args.graph_resolution]
|
| 247 |
+
elevations = elevations[::args.graph_resolution, :2000:args.graph_resolution]
|
| 248 |
+
print("DEM array shape", elevations.shape)
|
| 249 |
+
|
| 250 |
+
all_data, centers = construct_patch_dataset(xv,
|
| 251 |
+
yv,
|
| 252 |
+
elevations,
|
| 253 |
+
args.patch_size,
|
| 254 |
+
args.dataset_size,
|
| 255 |
+
triangles=args.triangles,
|
| 256 |
+
scale=args.scale)
|
| 257 |
+
torch.save(all_data, args.filename+'.pt')
|
| 258 |
+
torch.save(centers, args.filename + '-centers.pt')
|
| 259 |
+
|
| 260 |
+
if __name__ == '__main__':
|
| 261 |
+
main()
|
server-local/shortest-paths-terrain-patches/dataset/point_sampler.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From Haoyun Wang: I took this chunk of code from Haoyun Wang's final project
|
| 2 |
+
# from the Topological Data Analysis course from UCSD.
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from ripser import ripser, lower_star_img
|
| 8 |
+
from persim import plot_diagrams
|
| 9 |
+
|
| 10 |
+
def random_sampling(graph: nx.Graph, samples_per_source, src=None):
|
| 11 |
+
if src is None:
|
| 12 |
+
src = np.random.randint(0, graph.number_of_nodes())
|
| 13 |
+
distance = nx.single_source_dijkstra_path_length(graph, src)
|
| 14 |
+
# random
|
| 15 |
+
target = np.random.choice(graph.number_of_nodes(), (samples_per_source, ), replace=False)
|
| 16 |
+
distance = [distance[t] for t in target]
|
| 17 |
+
return [src] * samples_per_source, target.tolist(), distance
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def distance_based(graph: nx.Graph, samples_per_source, src=None):
|
| 21 |
+
if src is None:
|
| 22 |
+
src = np.random.randint(0, graph.number_of_nodes())
|
| 23 |
+
distance = nx.single_source_dijkstra_path_length(graph, src)
|
| 24 |
+
# random
|
| 25 |
+
vertices = np.arange(graph.number_of_nodes())
|
| 26 |
+
row_num = int(np.around(graph.number_of_nodes() ** 0.5))
|
| 27 |
+
hops = abs(src // row_num - vertices // row_num) + abs(src % row_num - vertices % row_num) + 1
|
| 28 |
+
probs = 1 / hops
|
| 29 |
+
probs = probs / probs.sum()
|
| 30 |
+
target = np.random.choice(vertices, (samples_per_source, ), p=probs, replace=False)
|
| 31 |
+
distance = [distance[t] for t in target]
|
| 32 |
+
return [src] * samples_per_source, target.tolist(), distance
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def find_critical_points(terrain, threshold):
|
| 36 |
+
# the original terrain has same-height points we must break the tie
|
| 37 |
+
N = terrain.shape[0]
|
| 38 |
+
terrain[:, :, 2] += torch.rand((N, N)) * 1e-5
|
| 39 |
+
lower_dgm = lower_star_img(terrain[:, :, 2])
|
| 40 |
+
upper_dgm = - lower_star_img(- terrain[:, :, 2])
|
| 41 |
+
long_pers_lower_dgm = lower_dgm[lower_dgm[:, 1]- lower_dgm[:, 0] > threshold]
|
| 42 |
+
long_pers_upper_dgm = upper_dgm[upper_dgm[:, 0]- upper_dgm[:, 1] > threshold]
|
| 43 |
+
long_pers_dgm = np.concatenate([long_pers_lower_dgm, long_pers_upper_dgm])
|
| 44 |
+
print(f"{long_pers_dgm.shape[0]} significant critical point pairs")
|
| 45 |
+
|
| 46 |
+
flatten_terrain = terrain.flatten(0, 1)
|
| 47 |
+
critical_idx_0 = [np.argmin(abs(flatten_terrain[:, 2] - long_pers_lower_dgm[i, 0])) for i in range(long_pers_lower_dgm.shape[0])]
|
| 48 |
+
critical_idx_2 = [np.argmin(abs(flatten_terrain[:, 2] - long_pers_upper_dgm[i, 0])) for i in range(long_pers_upper_dgm.shape[0])]
|
| 49 |
+
critical_idx_1 = [np.argmin(abs(flatten_terrain[:, 2] - long_pers_lower_dgm[i, 1])) for i in range(long_pers_lower_dgm.shape[0])] + \
|
| 50 |
+
[np.argmin(abs(flatten_terrain[:, 2] - long_pers_upper_dgm[i, 1])) for i in range(long_pers_upper_dgm.shape[0])]
|
| 51 |
+
critical_idx_1 = list(set(critical_idx_1))
|
| 52 |
+
|
| 53 |
+
critical_idx = torch.stack(critical_idx_0 + critical_idx_1 + critical_idx_2)
|
| 54 |
+
# shuffle it
|
| 55 |
+
critical_idx = critical_idx[torch.randperm(critical_idx.shape[0])]
|
| 56 |
+
critical_idx = [src.item() for src in critical_idx]
|
| 57 |
+
return critical_idx
|
| 58 |
+
|
| 59 |
+
|
server-local/shortest-paths-terrain-patches/dataset/py-to-wavefront.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch, queue
|
| 3 |
+
from torch_geometric.data import Data
|
| 4 |
+
import networkx as nx
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from tqdm import tqdm, trange
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
import time
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
|
| 13 |
+
from torch_geometric.utils import to_networkx
|
| 14 |
+
|
| 15 |
+
def npz_to_dataset(data):
|
| 16 |
+
|
| 17 |
+
edge_index = torch.tensor(data['edge_index'], dtype=torch.long)
|
| 18 |
+
|
| 19 |
+
srcs = data['srcs']
|
| 20 |
+
tars = data['tars']
|
| 21 |
+
lengths = data['lengths']
|
| 22 |
+
node_features = torch.tensor(data['node_features'], dtype=torch.double)
|
| 23 |
+
|
| 24 |
+
return srcs, tars, lengths, node_features, edge_index
|
| 25 |
+
|
| 26 |
+
def triangle_graph_to_wavefront_obj(vertices, edge_index, n, m, filename, triangle=False):
|
| 27 |
+
f = open(filename, "w")
|
| 28 |
+
|
| 29 |
+
ids = np.reshape(np.arange(1, n * m + 1), (n, m))
|
| 30 |
+
|
| 31 |
+
for v in vertices:
|
| 32 |
+
string = f'v {v[0]} {v[1]} {v[2]}\n'
|
| 33 |
+
f.write(string)
|
| 34 |
+
graph_data = Data(x =vertices, edge_index = edge_index)
|
| 35 |
+
G = to_networkx(graph_data)
|
| 36 |
+
|
| 37 |
+
for i in range(n - 1):
|
| 38 |
+
for j in range(m - 1):
|
| 39 |
+
# cell_idx = ids[i, j]
|
| 40 |
+
if triangle:
|
| 41 |
+
if G.has_edge(ids[i, j + 1], ids[i + 1, j]):
|
| 42 |
+
# diagonal = (ids[i, j + 1], ids[i + 1, j])
|
| 43 |
+
f1 = f'f {ids[i, j]} {ids[i + 1, j]} {ids[i, j + 1]} \n'
|
| 44 |
+
f2 = f'f {ids[i, j + 1]} {ids[i + 1, j]} {ids[i + 1, j + 1]}\n'
|
| 45 |
+
f.write(f1)
|
| 46 |
+
f.write(f2)
|
| 47 |
+
else:
|
| 48 |
+
# diagonal = (ids[i, j], ids[i + 1, j + 1])
|
| 49 |
+
f1 = f'f {ids[i, j]} {ids[i + 1, j + 1]} {ids[i, j + 1]}\n'
|
| 50 |
+
f2 = f'f {ids[i, j]} {ids[i + 1, j]} {ids[i + 1, j + 1]} \n'
|
| 51 |
+
f.write(f1)
|
| 52 |
+
f.write(f2)
|
| 53 |
+
else:
|
| 54 |
+
face = f'f {ids[i, j]} {ids[i + 1, j]} {ids[i + 1, j + 1]} {ids[i, j + 1]} \n'
|
| 55 |
+
f.write(face)
|
| 56 |
+
|
| 57 |
+
f.close()
|
| 58 |
+
print("Saved wavefront obj to:", filename)
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
parser = argparse.ArgumentParser()
|
| 62 |
+
parser.add_argument('--raw-data', type=str)
|
| 63 |
+
parser.add_argument('--filename', type=str)
|
| 64 |
+
parser.add_argument('--n', type=int)
|
| 65 |
+
parser.add_argument('--m', type=int)
|
| 66 |
+
parser.add_argument('--triangle', action='store_true')
|
| 67 |
+
|
| 68 |
+
args = parser.parse_args()
|
| 69 |
+
|
| 70 |
+
data = np.load(args.raw_data, allow_pickle=True)
|
| 71 |
+
_, _, _, vertices, edge_index = npz_to_dataset(data)
|
| 72 |
+
print(len(vertices))
|
| 73 |
+
triangle_graph_to_wavefront_obj(vertices, edge_index, args.n, args.m, args.filename, triangle=args.triangle)
|
| 74 |
+
|
| 75 |
+
if __name__ =='__main__':
|
| 76 |
+
main()
|