-
Notifications
You must be signed in to change notification settings - Fork 21
/
sim_est_error.py
220 lines (191 loc) · 6.97 KB
/
sim_est_error.py
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
"""
Please contact the author(s) of this library if you have any questions.
Authors: Kai-Chieh Hsu ( [email protected] )
1. We want to evaluate how well we learned from the data.
2. We compare the DDQN-predicted value vs. the rollout value by DDQN-induced
policies.
3. Pre-processing:
we need to run `genEstSamples.py` beforehand to get state samples
4. This script uses samples from `{args.modelFolder}/data/samplesEst.npy` as
the initial states of testing rollouts. We then specify the arguments of
the rollout (see help section of arguments for more details). The rollout
results are stored in
`{args.modelFolder}/data/est/{args.outFile}{args.index}.npy`.
EXAMPLES
test:
python3 sim_est_error.py -of tmp
default:
python3 sim_est_error.py
toEnd:
python3 sim_est_error.py -te
consider pursuer failure set:
python3 sim_est_error.py -cpf -mf <model_path>
"""
from warnings import simplefilter
import gym
import numpy as np
import torch
import os
import time
import argparse
from multiprocessing import Pool
from utils.carPEAnalysis import loadAgent, loadEnv
from gym_reachability import gym_reachability # Custom Gym env.
simplefilter(action='ignore', category=FutureWarning)
def multiExp(
args, posAtt, thetaAttIdx, samplesDef, thetas, maxLength, toEnd,
verbose=False
):
np.set_printoptions(precision=3, suppress=True, floatmode='fixed')
# == ENVIRONMENT ==
env = loadEnv(args, verbose)
stateNum = env.state.shape[0]
actionNum = env.action_space.n
numActionList = env.numActionList
device = env.device
# == AGENT ==
agent = loadAgent(args, device, stateNum, actionNum, numActionList, verbose)
# print("I'm process", os.getpid())
numTheta = thetas.shape[0]
numDef = samplesDef.shape[0]
shapeTmp = np.array([numDef, numTheta])
trajLength = np.empty(shape=shapeTmp, dtype=int)
ddqnValue = np.empty(shape=shapeTmp, dtype=float)
rolloutValue = np.empty(shape=shapeTmp, dtype=float)
it = np.nditer(ddqnValue, flags=['multi_index'])
while not it.finished:
idx = it.multi_index
print(idx, end='\r')
state = np.empty(shape=(6,), dtype=float)
state[:2] = posAtt
state[2] = thetas[thetaAttIdx]
state[3:5] = samplesDef[idx[0], :]
state[5] = thetas[idx[1]]
traj, _, _, minV, _ = env.simulate_one_trajectory(
agent.Q_network, T=maxLength, state=state, toEnd=toEnd
)
trajLength[idx] = traj.shape[0]
rolloutValue[idx] = minV
agent.Q_network.eval()
state = torch.from_numpy(state).float().to(agent.device)
state_action_values = agent.Q_network(state)
Q_mtx = state_action_values.detach().cpu().reshape(
agent.numActionList[0], agent.numActionList[1]
)
pursuerValues, _ = Q_mtx.max(dim=1)
minmaxValue, _ = pursuerValues.min(dim=0)
ddqnValue[idx] = minmaxValue
it.iternext()
carPEDict = {}
carPEDict['trajLength'] = trajLength
carPEDict['ddqnValue'] = ddqnValue
carPEDict['rolloutValue'] = rolloutValue
carPEDict['thetaAttIdx'] = thetaAttIdx
return carPEDict
def run(args):
startTime = time.time()
dataFolder = os.path.join(args.modelFolder, 'data')
dataFile = os.path.join(dataFolder, 'samplesEst.npy')
print('Load from {:s} ...'.format(dataFile))
read_dictionary = np.load(dataFile, allow_pickle='TRUE').item()
samples = read_dictionary['samples']
[samplesAtt, samplesDef, thetas] = samples
numTheta = thetas.shape[0]
numDef = samplesDef.shape[0]
posAtt = samplesAtt[args.index, :]
print(posAtt, numTheta, numDef)
# == ROLLOUT RESULTS ==
print("\n== Estimation Error Information ==")
maxLength = args.maxLength
toEnd = args.toEnd
carPESubDictList = []
numThread = args.numWorker
numTest = thetas.shape[0]
numTurn = int(numTest / (numThread+1e-6)) + 1
for ith in range(numTurn):
print('{} / {}'.format(ith + 1, numTurn), end=': ')
with Pool(processes=numThread) as pool:
startIdx = ith * numThread
endIdx = min(numTest, (ith+1) * numThread)
print('{:.0f}-{:.0f}'.format(startIdx, endIdx - 1))
thetaIdxAttList = [j for j in range(startIdx, endIdx)]
numExp = len(thetaIdxAttList)
posAttList = [posAtt] * numExp
argsList = [args] * numExp
samplesDefList = [samplesDef] * numExp
thetasList = [thetas] * numExp
maxLengthList = [maxLength] * numExp
toEndList = [toEnd] * numExp
verboseList = [False] * numExp
carPESubDict_i = pool.starmap(
multiExp,
zip(
argsList, posAttList, thetaIdxAttList, samplesDefList,
thetasList, maxLengthList, toEndList, verboseList
)
)
carPESubDictList = carPESubDictList + carPESubDict_i
# == COMBINE RESULTS ==
shapeTmp = np.array([numTheta, numDef, numTheta])
trajLength = np.empty(shape=shapeTmp, dtype=int)
ddqnValue = np.empty(shape=shapeTmp, dtype=float)
rolloutValue = np.empty(shape=shapeTmp, dtype=float)
for i, carPESubDict_i in enumerate(carPESubDictList):
thetaAttIdx = carPESubDict_i['thetaAttIdx']
trajLength[thetaAttIdx, :, :] = carPESubDict_i['trajLength']
ddqnValue[thetaAttIdx, :, :] = carPESubDict_i['ddqnValue']
rolloutValue[thetaAttIdx, :, :] = carPESubDict_i['rolloutValue']
print(ddqnValue.shape)
endTime = time.time()
execTime = endTime - startTime
print('--> Execution time: {:.1f}'.format(execTime))
carPEDict = {}
carPEDict['maxLength'] = maxLength
carPEDict['toEnd'] = toEnd
carPEDict['samples'] = samples
carPEDict['idx'] = args.index
carPEDict['trajLength'] = trajLength
carPEDict['ddqnValue'] = ddqnValue
carPEDict['rolloutValue'] = rolloutValue
outFolder = os.path.join(args.modelFolder, 'data', 'est')
os.makedirs(outFolder, exist_ok=True)
outFile = os.path.join(outFolder, args.outFile + str(args.index) + '.npy')
np.save('{:s}'.format(outFile), carPEDict)
print('--> Save to {:s} ...'.format(outFile))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Environment Parameters
parser.add_argument(
"-cpf", "--cpf", help="consider pursuer failure", action="store_true"
)
# Simulation Parameters
parser.add_argument(
"-f", "--forceCPU", help="force PyTorch to use CPU", action="store_true"
)
parser.add_argument(
"-te", "--toEnd",
help="continue the rollout until both cars cross the boundary",
action="store_true"
)
parser.add_argument(
"-ml", "--maxLength", help="maximum length of rollout episodes",
default=150, type=int
)
parser.add_argument(
"-nw", "--numWorker", help="#workers", default=6, type=int
)
parser.add_argument(
"-idx", "--index", help="the index of state in samples", default=0,
type=int
)
# File Parameters
parser.add_argument(
"-of", "--outFile", help="output file", default='estError', type=str
)
parser.add_argument("-mf", "--modelFolder", help="model folder", type=str)
args = parser.parse_args()
print("\n== Arguments ==")
print(args)
# == Execution ==
np.set_printoptions(precision=3, suppress=True, floatmode='fixed')
run(args)