FILE DHDP.py SHA256 3a813bb9754918d8dcf1ddab482b02fd0021257a360874121758362648d7d532
1: import copy
2: import numpy as np
3: import torch
4: import torch.nn as nn
5: import torch.nn.functional as F
6: 
7: 
8: device = torch.device("cpu")
9: 
10: #ACTOR NETWORK
11: class Actor(nn.Module):
12: 	def __init__(self, state_dim, action_dim, max_action):
13: 		super(Actor, self).__init__()
14: 
15: 		self.l1 = nn.Linear(state_dim, 1024)
16: 		self.l2 = nn.Linear(1024, action_dim)
17: 		
18: 		self.max_action = max_action
19: 
20: 	
21: 	def forward(self, state):
22: 		a = F.relu(self.l1(state))
23: 		return self.max_action * torch.tanh(self.l2(a))
24: 
25: #CRITIC NETWORK
26: class Critic(nn.Module):
27: 	def __init__(self, state_dim, action_dim):
28: 		super(Critic, self).__init__()
29: 
30: 		self.l1 = nn.Linear(state_dim + action_dim, 1024)
31: 		self.l3 = nn.Linear(1024, 1)
32: 
33: 
34: 	def forward(self, state, action):
35: 		q = F.relu(self.l1(torch.cat([state, action], 1)))
36: 		return self.l3(q)
37: 
38: 
39: class DHDP(object):
40: 	def __init__(self, state_dim, action_dim, max_action, discount=0.95, tau=0.1):
41: 		self.actor = Actor(state_dim, action_dim, max_action).to(device)
42: 		self.actor_target = copy.deepcopy(self.actor)
43: 		self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=0.001)
44: 
45: 		self.critic = Critic(state_dim, action_dim).to(device)
46: 		self.critic_target = copy.deepcopy(self.critic)
47: 		self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=0.001)
48: 
49: 		self.discount = discount
50: 		self.tau = tau
51: 
52: 
53: 	def select_action(self, state):
54: 		state = torch.FloatTensor(state.reshape(1, -1)).to(device)
55: 		return self.actor(state).cpu().data.numpy().flatten()
56: 
57: 
58: 	def train(self, replay_buffer, batch_size=1):
59: 		# Sample replay buffer 
60: 		state, action, next_state, reward, not_done = replay_buffer.sample(batch_size)
61: 
62: 		# Compute the target Q value
63: 		target_Q = self.critic_target(next_state, self.actor_target(next_state))
64: 		target_Q = reward + (not_done * self.discount * target_Q).detach()
65: 
66: 		# Get current Q estimate
67: 		current_Q = self.critic(state, action)
68: 
69: 		# Compute critic loss
70: 		critic_loss = F.mse_loss(current_Q, target_Q)
71: 
72: 		# Optimize the critic
73: 		self.critic_optimizer.zero_grad()
74: 		critic_loss.backward()
75: 		self.critic_optimizer.step()
76: 
77: 		# Compute actor loss
78: 		actor_loss = self.critic(state, self.actor(state)).mean()
79: 		
80: 		# Optimize the actor 
81: 		self.actor_optimizer.zero_grad()
82: 		actor_loss.backward()
83: 		self.actor_optimizer.step()
84: 
85: 		# Update the frozen target models
86: 		for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):
87: 			target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)
88: 
89: 		for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):
90: 			target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)
91: 
92: 
93: 	def save(self, filename):
94: 		torch.save(self.critic.state_dict(), filename + "_critic")
95: 		torch.save(self.critic_optimizer.state_dict(), filename + "_critic_optimizer")
96: 		
97: 		torch.save(self.actor.state_dict(), filename + "_actor")
98: 		torch.save(self.actor_optimizer.state_dict(), filename + "_actor_optimizer")
99: 
100: 
101: 	def load(self, filename):
102: 		self.critic.load_state_dict(torch.load(filename + "_critic"))
103: 		self.critic_optimizer.load_state_dict(torch.load(filename + "_critic_optimizer"))
104: 		self.critic_target = copy.deepcopy(self.critic)
105: 
106: 		self.actor.load_state_dict(torch.load(filename + "_actor"))
107: 		self.actor_optimizer.load_state_dict(torch.load(filename + "_actor_optimizer"))
108: 		self.actor_target = copy.deepcopy(self.actor)
109: 		
FILE AIP_Online_training.py SHA256 2c5c3a6ba21c5c7da13cd7734b76015af4bce90eed2bef37d93c411e2c7e9b04
80: 
81: if __name__ == "__main__":
82:     
83:     
84:     parser = argparse.ArgumentParser()
85:     parser.add_argument("--MAX_EPISODES", default=50, type=int)    # Max EP to run environment
86:     parser.add_argument("--expl_noise", default=0.05)                # Std of Gaussian exploration noise
87:     parser.add_argument("--batch_size", default=2, type=int)        # Batch size for both actor and critic
88:     parser.add_argument("--max_mem_size", default=50, type=int)     # max buffer size
89:     parser.add_argument("--discount", default=0.95)                 # Discount factor
90:     parser.add_argument("--tau", default=0.5)                      # Target network update rate
91:     parser.add_argument("--policy_noise", default=0.00)             # Noise added to target policy during critic update
92:     parser.add_argument("--noise_clip", default=0.1)                # Range to clip target policy noise
93:     parser.add_argument("--save_model", default = False)             # Save model and optimizer parameters
94:     parser.add_argument("--load_model", default="dhdp_mocap")          # Model load file name, "" doesn't load, "default" uses file_name
95:     args = parser.parse_args()
96:     
97: 
98:     # #Load Offline Data
99:     # # data = genfromtxt(r"C:\Users\jz5zh\eclipse-workspace\soft_suit\gait_data_2control.csv", dtype=float,delimiter=',')
100:     # data = genfromtxt(r"gait_data_1.csv", dtype=float,delimiter=',')
170:         # for j in range(1):
171:             try:
172:                 #Compute RL action
173:                 action = (
174:                         policy.select_action(np.array(state))  #policy from state
175:                         + np.random.normal(0, max_action * args.expl_noise, size=action_dim)  #add some noise
176:                             ).clip(-max_action, max_action)
177:                 
178:                 """ Send action data to pressure controller """
179:                 #Convert the action from normalized values to seconds (junmin)
180:                 #Junmin add here the denormalization (a + 1)*(max - min)/2 + min
181:                 gaie_duration = data[8]
182:                 t1 = (((action[0] + 1)*(0.2-0)/2) + 0)*gaie_duration
183:                 u1 = (((action[1] + 1)*(0.25)/2) + 0)*gaie_duration
184:                 t2 = (((action[2] + 1)*(0.74-0.5)/2) + 0.5)*gaie_duration
185:                 u2 = (((action[3] + 1)*(0.28-0)/2) + 0)*gaie_duration 
186:                 
187:                 #Send the RL timings (action) to the pressure controller (emiliano)
188:                 timing_export_array = np.array([t1, u1, t2, u2])
189:                 socket_export.send_pyobj(timing_export_array) #send data to pressure_commands.py
190:                 print("action timings (sec) =", timing_export_array)
191:                 
192:                 
193:                 """ RL """
194:                 ###double check this read data will wait 5 steps average?
195:                 ###apply action to plant
196:                 if Realtime_Run:
197:                     #Receive Gait Data Array
198:                     data = socket0.recv_pyobj()
199:                 else:
200:                     #Read Gait Data Array from data structure
201:                     data = data_csv[i][4:8]
202:                     data_mocap = data_mocap_csv[i][4:8]
203:                 
204:                 # next_state = (data[0],data[2]) #first gait state data
205:                 emg_state = data[5]+data[6]+data[7]
206:                 next_state = (data[0],data[1]/2,data[2],data[3],data[4])
207:                 
208:                 ####in online training we should compare real human data with target. NOT ACTION anymore.
209:                 #JUNMIN 0.232 0.523 1.118 0.289 1.095
210:                 #juseph 0.231 0.684 1.326 0.311 0.698
211:                 t1_error = data[0] - 0.124 ####t1 12.4%
212:                 d1_error = data[1]/2 - 0.375/2 ####d1 
213:                 t2_error = data[2] - 0.71
214:                 d2_error = data[3] - 0.168
215:                 kinematic_error = data[4]- 0.698
216:                 emg_VL = data[5]
217:                 emg_RF = data[6]
218:                 emg_BF = data[7]
219:                 ####state action alignment
220:                 action1_error =  (2*(data[0])/(0.2) - 1) - action[0]
221:                 action2_error =  (2*(data[1]/2)/(0.25) - 1) - action[1]
222:                 action3_error =  (2*(data[2]-0.5)/(0.24) - 1) - action[2]
223:                 action4_error =  (2*(data[3])/(0.28) - 1) - action[3]
224:                 
225:                 coeff_t1 = 20
226:                 coeff_d1 = 20
227:                 coeff_t2 = 10
228:                 coeff_d2 = 20
229:                 coeff_a1 = 2
230:                 coeff_a2 = 2
231:                 coeff_a3 = 1
232:                 coeff_a4 = 2
233:                 coeff_kine = 0.05
234:                 coeff_emg = 0.2
235:                 
236:                 error_state = coeff_t1*(t1_error)**2 + coeff_d1*(d1_error)**2 + coeff_t2*(t2_error)**2 + coeff_d2*(d2_error)**2
237:                 error_action = coeff_a1*(action1_error)**2 + coeff_a2*(action2_error)**2 + coeff_a3*(action3_error)**2 + coeff_a4*(action4_error)**2
238:                 
239:                 cost = 0.5*(error_state + error_action
240:                            + coeff_kine*(kinematic_error)**2 
241:                            + coeff_emg*(emg_state)**2) #cost for timing and duration
242:                 
243:                 done = 0
244:                 counter_samples += 1  #add to counter
245:                 replay_buffer.add(state, action, next_state, cost, done)
246:             
247:                 if counter_samples >= 2:  #collect at least 10 samples of data before training
248:                     
249:                     policy.train(replay_buffer, args.batch_size) #training
250:                 
251:                 training_data.append((counter_samples,cost,t1_error,d1_error,t2_error,d2_error,kinematic_error,state,action,next_state,emg_VL,emg_RF,emg_BF))  
252:                 state = next_state
253:                 
254:                 #Print results for current sample training
255:                 print('Sample=', counter_samples, 
256:                        '\t Cost=', cost)
257:                 
258:                 print('\t t1=', t1/gaie_duration,
259:                       '\t d1=', u1/gaie_duration,
260:                       '\t t2=', t2/gaie_duration,
261:                       '\t d2=', u2/gaie_duration)
262:                 
263:                 print('\t t1 error=', t1_error,
264:                         '\t d1 error=', d1_error,
265:                         '\t t2 error=', t2_error,
266:                         '\t d2 error=', d2_error)
267:                 
268:                 print('\t a1 error=', action1_error,
269:                         '\t a2 error=', action2_error,
270:                         '\t a3 error=', action3_error,
271:                         '\t a4 error=', action4_error)
272:                 
273:                 print('emg = ', emg_state)
274:                 
275:                 if counter_samples > 45:
276:                     run_exp = False
277:                     
278:             except KeyboardInterrupt:
279:                 if Realtime_Run: 
280:                     socket0.close()
FILE AIP_offline_training.py SHA256 db40471d621d32f1eaf4ccd825029f7b757384670a653ae64c39dbdfbc24884b
140:         
141:         
142:         data_csv = genfromtxt(r"gait_data_6_22_percent.csv", dtype=float,delimiter=',')
143:         data_mocap_csv = genfromtxt(r"gait_data_6_22_percent_mocap.csv", dtype=float,delimiter=',')
144:         print(data_csv.shape[0],'total data length') #row number
145:         print(data_mocap_csv.shape[0],'total mocap data length') #row number
146:         
147:         
148:         replay_buffer = utils.ReplayBuffer(state_dim, action_dim,args.max_mem_size)
149:         training_data = []
150:         all_epc = []
151: 
152:         
153:         print("---------------------------------------")
154:         print(f" Start RL Training")
155:         print("---------------------------------------")
156:         
157:         #Run training loop for the number of max episodes. One episode is one run of the whole data set.
158:         for j in range(int(args.MAX_EPISODES)):
159:         # for j in range(1):
160:             ep_c = 0
161:             counter_samples = 0
162:             
163: 
164:             data = data_csv[0][0:5]
165:                 
166:             
167:             # state = (data[0],data[2]) #first gait state data
168:             state = (data[0],data[1],data[2],data[3],data[4]) #first gait state data
169:             
170:             # while True:
171:             num_data = data_mocap_csv.shape[0]
172:             for i in range(num_data - 2):  #debug, alternative loop statement. 214 = number of gait cycles in the offline data
173:                 
174:                 #Read Gait Data Array from data structure
175:                 data = data_csv[i+1][0:5]
176:                 data_mocap = data_mocap_csv[i][5:10]
177:                 
178:                 # next_state = (data[0],data[2]) #first gait state data
179:                 next_state = (data[0],data[1],data[2],data[3], data[4])
180:                 
181:                 action = (
182:                         policy.select_action(np.array(state))  #policy from state
183:                         + np.random.normal(0, max_action * args.expl_noise, size=action_dim)  #add some noise
184:                             ).clip(-max_action, max_action)
185:                             
186:                 action_raw = policy.select_action(np.array(state))
187:                 
188: 
189:                 coeff_t1 = 2
190:                 coeff_d1 = 2
191:                 coeff_t2 = 2
192:                 coeff_d2 = 2
193:                 cost = 0.5*(coeff_t1*(action_raw[0] - data_mocap[0])**2 + coeff_d1*(action_raw[1]- data_mocap[1])**2 
194:                             + coeff_t2*(action_raw[2]- data_mocap[2])**2 + coeff_d2*(action_raw[3]- data_mocap[3])**2) #cost for timing and duration
195:                 
196:                 done = 0
197:                 ep_c += cost   
198:                 counter_samples += 1  #add to counter
199:                 
200:                 replay_buffer.add(state, action, next_state, cost, done)
201:                 if j > 190:
202:                     print('T1',((action[0] + 1)*(0.2-0)/2) + 0, 'state T1', state[0] ,'D1',((action[1] + 1)*(0.25-0)/2) + 0, 'state D1', state[1]  )
203:                     print('T2',((action[2] + 1)*(0.74-0.5)/2) + 0.5,'state T2', state[2] , 'D2',((action[3] + 1)*(0.45-0)/2) + 0, 'state D2', state[3]  )
204:                     
205:             
206:                 if counter_samples >= args.batch_size:  #collect at least 10 samples of data before training
207:                     
208:                     policy.train(replay_buffer, args.batch_size) #training
209:                     
210:                 state = next_state
211:                 
212:                     
213:                         
214:             #Print Results for complete episode (1 pass of training data)
215:             all_epc += [ep_c]
216:             training_data.append((j,ep_c/num_data))
217:             print('Ep: %i  | Average step cost: %.1f | ' % (j, ep_c/num_data ))
218:             
FILE utils.py SHA256 a19d5e6ccc92b0ea01dea2638904ecf7a059e1e03dd0f330259703751e117174
1: import numpy as np
2: import torch
3: 
4: 
5: class ReplayBuffer(object):
6: 	def __init__(self, state_dim, action_dim, max_size=int(50000)):
7: 		self.max_size = max_size
8: 		self.ptr = 0
9: 		self.size = 0
10: 
11: 		self.state = np.zeros((max_size, state_dim))
12: 		self.action = np.zeros((max_size, action_dim))
13: 		self.next_state = np.zeros((max_size, state_dim))
14: 		self.reward = np.zeros((max_size, 1))
15: 		self.not_done = np.zeros((max_size, 1))
16: 
17: 		self.device = torch.device("cpu")
18: 
19: 
20: 	def add(self, state, action, next_state, reward, done):
21: 		self.state[self.ptr] = state
22: 		self.action[self.ptr] = action
23: 		self.next_state[self.ptr] = next_state
24: 		self.reward[self.ptr] = reward
25: 		self.not_done[self.ptr] = 1. - done
26: 
27: 		self.ptr = (self.ptr + 1) % self.max_size
28: 		self.size = min(self.size + 1, self.max_size)
29: 
30: 
31: 	def sample(self, batch_size):
32: 		ind = np.random.randint(0, self.size, size=batch_size)
33: 
34: 		return (
35: 			torch.FloatTensor(self.state[ind]).to(self.device),
36: 			torch.FloatTensor(self.action[ind]).to(self.device),
37: 			torch.FloatTensor(self.next_state[ind]).to(self.device),
38: 			torch.FloatTensor(self.reward[ind]).to(self.device),
39: 			torch.FloatTensor(self.not_done[ind]).to(self.device)
40: 		)
FILE README.md SHA256 bc197563daa34b97ccf781e29dae5b2d5e2ccae22b84592af9d4884ba00ce3df
1: # Reinforcement Learning Control of a Physical Robot Device for Assisted Human Walking without a Simulator (ICML2025-AIP)
2: Offline to online dHDP for soft exosuit personalized control
3: 
4: **[Reinforcement Learning Control of a Physical Robot Device for Assisted Human Level Ground Walking without a Simulator](https://icml.cc/virtual/2025/poster/43549)**
5: 
6: ICML | 2025
7: 
8: [Junmin Zhong](https://scholar.google.com/citations?user=uVv_eWQAAAAJ&hl=en&oi=ao)<sup>1</sup>, Emiliano Quinones Yumbla<sup>2</sup>, Seyed Yousef Soltanian<sup>2</sup>,   Ruofan Wu<sup>1</sup>, Wenlong Zhang<sup>2</sup><sup>3</sup>, Jennie Si<sup>1</sup><sup>3</sup>
9: 
10: <sup>1</sup>School of Electrical, Computer and Energy Engineering, Arizona State University, Tempe, Arizona. 
11: 
12: <sup>2</sup>School of Manufacturing Systems and Networks, Arizona State University, Mesa, Arizona.
13: 
14: <sup>3</sup>Corresponding Authors. Correspondence to: Jennie Si <si@asu.edu>, Wenlong Zhang <wenlong.zhang@asu.edu>.
15: 
16: ## Installation
17: 
18: The code has been tested on Python 3.10.6 and PyTorch 2.0.1. 
19: 
20: See other required packages:
21:   1. Numpy
22: 
23: 
24: ## Offline training
25: 
26: 
27: ```Deploy_RL = 0``` for offline training, ```Deploy_RL = 1``` for validation
28: 
29: ```data_csv``` is the path to the sensor state data, ```data_mocap_csv``` is the path to the MoCap ground truth data
30: 
31: ## Online training
32: 
33: Interaction with bottom control files and sensor reading files.
34: 
35: ## Data
36: 
37: Offline Sensor data ```gait_data_6_22_percent.csv```
38: 
39:   data[0:5]:
40:   1. t_A
41:   2. d_A
42:   3. t_C
43:   4. d_C
44:   5. theta
45:      
46: Offline MoCap data ```gait_data_6_22_percent.csv```
47: 
48:   data[5:10]:
49:   1. t_A
50:   2. d_A
51:   3. t_C
52:   4. d_C
53:   5. theta
