forked from HBPNeurorobotics/hbpprak_2018_throwing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtual_coach.py
135 lines (94 loc) · 3.84 KB
/
virtual_coach.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
import numpy as np
from evolution_strategy import EvolutionStrategy
import tempfile
import os
import csv
import time
import pickle
class TestCaseError(Exception):
pass
def make_dict_from_weights(weights):
index = 1
wdic = {}
for layer in weights:
wdic["layer"+str(index)]=layer.tolist()
index = index + 1
return wdic
last_status = [None]
def on_status(msg):
last_status[0] = msg
def wait_condition(timeout, description, condition):
start = time.time()
while time.time() < start + timeout:
time.sleep(0.25)
if condition(last_status[0]):
return
raise TestCaseError(description)
def make_get_reward(sim, csv_name):
def get_reward(index, weight, bias, topology):
wdic = make_dict_from_weights(weights)
wbias = make_dict_from_weights(bias)
tf = 'import numpy as np\[email protected]("weights", initial_value = None, scope = nrp.GLOBAL)\[email protected]("topology", initial_value = None, scope = nrp.GLOBAL)\[email protected]("bias", initial_value = None, scope = nrp.GLOBAL)\ndef set_weights (t,weights,topology, bias):\n top = [6,10,8,6]\n in_wieghts = []\n in_bias = []\n weights.value = {}\n topology.value = {}\n bias.value = {}\n'.format(wdic, topology, wbias)
sim.edit_transfer_function('set_weights',tf)
sim.start()
try:
wait_condition(100, 'Running simulation for 10 seconds', lambda x: x['simulationTime'] > 10.0)
except TestCaseError:
pass
sim.pause()
csv_data = np.array(sim.get_csv_data(csv_name))
sim.reset('full')
wait_condition(100, 'Waiting for full reset', lambda x: x['simulationTime'] == 0.0 and x['state'] == 'paused')
cylinder_reward = -csv_data[1:,1].astype(np.float).min()
distance_reward = csv_data[1:,2].astype(np.float).min()
reward = (1 + cylinder_reward)**2 - distance_reward
print('FINISHED TEST WITH REWARD {}'.format(reward))
return reward
return get_reward
if __name__ == '__main__':
# Start simulation and launch experiment
csv_name = "cylinder_position.csv"
try:
from hbp_nrp_virtual_coach.virtual_coach import VirtualCoach
vc = VirtualCoach(environment='local', storage_username='nrpuser')
except ImportError as e:
print(e)
print("You have to start this notebook with the command:\
cle-virtual-coach jupyter notebook")
raise e
sim = vc.launch_experiment('hbpprak_2018_throwing')
sim.register_status_callback(on_status) #solution
# Network params and init
topology = [6,50,20,6]
weights = []
bias = []
rewards = []
for index in range(len(topology)-1):
weights.append(np.random.uniform(-1,1,(topology[index], topology[index+1])))
bias.append(np.random.uniform(-1,1,(1,topology[index+1])))
#with open('tmp_weights.pickle', 'rb') as tmpFile:
# savedObject = pickle.load(tmpFile)
# weights = savedObject['weights']
# bias = savedObject['bias']
with open('weights/weights_reward_24.2747422414.pickle','rb') as f:
s = pickle.load(f)
weights = s['weights']
bias = s['bias']
#Start the evolutionary strategy
print(weights)
#Evo Params
n_threads = 1
pop_size = 25
#pop_size = 10
learning_rate = 0.01
decay = 0.97
sigma = 0.00
iterations = 50
es = EvolutionStrategy(topology, weights, bias, make_get_reward(sim, csv_name), pop_size, sigma, learning_rate, decay, n_threads)
average_rewards = es.run(iterations, 1)
final_weights = es.get_weights()
final_bias = es.bias
optimal_params = {'weights':final_weights,'bias':final_bias}
with open("optimal_params.pickle","wb") as f:
pickle.dump(optimal_params,f)
np.savetxt("rewards.txt",np.array(average_rewards))