File size: 9,143 Bytes
1403119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import argparse
import os
import time
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
from glob import glob
torch.autograd.set_detect_anomaly(True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)

all_folders = glob("...")  # Collects all previous trainings (the folder names start with the training number)
all_folder_nums = np.array([int(x.split("/")[-1].split("_")[0]) for x in all_folders])  # Contains the train ids

parser = argparse.ArgumentParser()
parser.add_argument('--id', help='ID of the train run', required=True)
parser.add_argument('--test', help='number of the test dataset', required=True)

args = parser.parse_args()
folder_id = int(args.id)
test_num = int(args.test)
# If the folder for the defined train id doesn't exist, then exit
if folder_id not in all_folder_nums:
	print("Folder ID not finished yet")
	exit()
folder = all_folders[np.where(all_folder_nums == folder_id)[0][0]]  # pick the correct folder out of the folder ids
# Read in the parameters specified in the parameter file of the current train id
f = open(folder + "/parameters.txt", "r")
lines = f.read()
train_num = int(lines.split("\n")[1].split(" ")[-1])
BETA = 50
time_size = int(lines.split("\n")[6].split(" ")[-1])
rnn_size = int(lines.split("\n")[7].split(" ")[-1])
backrot = int(lines.split("\n")[8].split(" ")[-1])
mode = int(lines.split("\n")[9].split(" ")[-1])
net_name = lines.split("\n")[10].split(" ")[-1]
stacks = int(lines.split("\n")[11].split(" ")[-1])
f.close()
print(folder)
# Collect all weight files and use the last one
weights = glob(folder + "/weights/*")
startweight = weights[-1]
loss_name = "rmse"

if not os.path.exists(folder + "/error/"):
	os.makedirs(folder + "/error/")

# Choose and create the network specified in the arguments
if net_name == "lstm":
	from lstm import *
	model = LSTM_stack(14, rnn_size, device, stacks)
	model.train()
	model = model.to(device)
elif net_name == "cfn":
	from cfn import *
	model = CFN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "gru":
	from gru import *
	model = GRU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "mgu":
	from mgu import *
	model = MGU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "qrnn":
	from qrnn import *
	model = fakeQRNN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "ran":
	from ran import *
	model = RAN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "sru":
	from sru import *
	model = SRU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "trnn":
	from trnn import *
	model = TRNN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
import utilities_comb_notqdm as utilities


# The following deals with paths and folders for the data. It has to be adjusted to your setup.  -------------------- #
# In the end 2 file paths are defined: test_dataset_abs/test_dataset_rel
# Folders with the test data for the different methods
# Each is a dictionary with an entry for every train number
abs_datasets_sfm = {1: ..., 2: ...}
abs_datasets = {1: ..., 2: ...}
rel_datasets = {1: ..., 2: ...}
abs_synt_post_datasets = {1: ..., 2: ...}
rel_synt_post_datasets = {1: ..., 2: ...}
# Depending on the mode, the absolute and relative data is combined from different methods
# !! Use the test num to differentiate between the different tests
if mode == 1:
	train_base_abs = abs_datasets[train_num]
	train_base_rel = rel_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 2:
	train_base_abs = abs_synt_post_datasets[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 3:
	train_base_abs = abs_datasets_sfm[train_num]
	train_base_rel = rel_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 4:
	train_base_abs = abs_datasets[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 5:
	train_base_abs = abs_synt_post_datasets[train_num]
	train_base_rel = rel_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 6:
	train_base_abs = abs_datasets_sfm[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
# ------------------------------------------------------------------------------------------------------------------- #

# Create files to save the results in
tests_error = open(folder + "/error/" + folder.split("/")[-1] + "_result_" + test_dataset_abs.split("/")[-1].split(".")[0] + ".txt", "w")
tests_error_pred = open(folder + "/error/" + folder.split("/")[-1] + "_prediction_" + test_dataset_abs.split("/")[-1].split(".")[0] + ".txt", "w")


def getError(posx, posq, actualx, actualq):
	""" Calculates the position and rotation error """
	q1 = actualq / np.linalg.norm(actualq)
	q2 = posq / np.linalg.norm(posq)
	d = abs(np.sum(np.multiply(q1, q2)))
	theta = 2 * np.arccos(d) * 180 / np.pi
	errx = np.linalg.norm(actualx - posx)
	return errx, theta


def rmse_p(y_true, y_pred):
	return torch.sqrt(torch.sum(torch.square(y_pred-y_true), axis=-1))


def rmse_q(y_true, y_pred):
	return BETA * torch.sqrt(torch.sum(torch.square(y_true-y_pred), axis=-1))


class rmse_wrap(torch.nn.Module):
	""" Wrapper for dealing with the position loss and rotation loss. The rotation loss is multiplied with BETA. """
	def __init__(self):
		super(rmse_wrap, self).__init__()
	def __call__(self, output, target):
		loss1 = rmse_p(output[:, :3], target[:, :3])
		loss2 = rmse_q(output[:, 3:], target[:, 3:])
		return loss1 + loss2


# Loads the test data
pred_abs_test, pred_rel_test, gt_abs_test, gt_rel_test = utilities.get_training_data(test_dataset_abs, test_dataset_rel, backrot)
optimizer = optim.Adam(model.parameters())
criterion = rmse_wrap().to(device)

model.load_state_dict(torch.load(startweight))  # Load the trained weights
model.eval()
# create a generator for the test data (Batchsize = 1)
datagen = utilities.limited_gen_data(pred_abs_test, pred_rel_test, gt_abs_test, gt_rel_test, time_size)
results = []
results2d = []
i = 0
for ims,xs,qs in datagen:  # Iterate over the test data and evaluate it
	inputs = np.zeros((1, time_size, 14)).astype("float32")
	inputs[0, :] = ims
	inputs = inputs.transpose((1, 0, 2))
	inputs = torch.tensor(inputs).to(device)
	out = model(inputs).float()
	pred_x = out[0][:3].detach().cpu().numpy()
	pred_q = out[0][3:].detach().cpu().numpy()
	label_x = xs
	label_q = qs

	_, theta = getError(pred_x, pred_q, label_x, label_q)
	label_x = np.squeeze(label_x)
	label_q = np.squeeze(label_q)
	pred_x = np.squeeze(pred_x)
	pred_q = np.squeeze(pred_q)
	# Calculate the error in 3d and 2d
	error_x = np.linalg.norm(label_x - pred_x)
	error_x_2d = np.linalg.norm(label_x - [pred_x[0], pred_x[1], label_x[2]])
	results.append([error_x, theta])
	results2d.append([error_x_2d])
	# Write the error and the predicted values in the above defined files
	tests_error.write("\t Image %d: Error xyz: %fm, Error wpqr: %f degrees \n" % (int(i), error_x, theta))
	tests_error.flush()
	tests_error_pred.write("Timestamp: " + " 1" + ", Label: x: " + str(label_x[0]) + ", y: " + str(label_x[1]) + ", z: " + str(label_x[2]) + ", w0: " + str(label_q[0]) + ", w1: " + str(label_q[1]) + ", w2: " + str(label_q[2]) + ", w3: " + str(label_q[3]) + " Prediction: x: " + str(pred_x[0]) + ", y: " + str(pred_x[1]) + ", z: " + str(pred_x[2]) + ", w0: " + str(pred_q[0]) + ", w1: " + str(pred_q[1]) + ", w2: " + str(pred_q[2]) + ", w3: " + str(pred_q[3]) + "\n")
	tests_error_pred.flush()
	i = i + 1

# Caluclate the mean/median and percentiles of the errors
mean_result = np.nanmean(results, axis=0)
median_result = np.nanmedian(results, axis=0)
percentile50_result_2d = np.nanpercentile(results2d, axis=0, q=50)
percentile95_result_2d = np.nanpercentile(results2d, axis=0, q=95)
percentile50_result = np.nanpercentile(results, axis=0, q=50)
percentile95_result = np.nanpercentile(results, axis=0, q=95)
# Print and save the overview of the results
print("\n Results: \n \t MAE 2D: %f m \n\t Median 2D: %f m \n\t CEP: %f m \n\t CE95: %f m \n\t MAE 2D: %f deg \n\t Median 2D: %f deg \n\t CE95: %f deg \n" % (mean_result[0], median_result[0], percentile50_result_2d[0], percentile95_result_2d[0], mean_result[1], median_result[1], percentile95_result[1]))
tests_error.write("\n Results: \n \t MAE 2D: %f m \n\t Median 2D: %f m \n\t CEP: %f m \n\t CE95: %f m \n\t MAE 2D: %f deg \n\t Median 2D: %f deg \n\t CE95: %f deg \n" % (mean_result[0], median_result[0], percentile50_result_2d[0], percentile95_result_2d[0], mean_result[1], median_result[1], percentile95_result[1]))