├── reach task ├── data │ └── readme ├── muscularArmClass.py ├── optimizingscript_reachtask.py └── NetworkClass.py ├── posture task ├── data │ └── readme ├── muscularArmClass.py ├── optimizingscript_posturetask.py └── NetworkClass.py ├── README.md └── LICENSE /reach task/data/readme: -------------------------------------------------------------------------------- 1 | this folder saves data from neural network training 2 | -------------------------------------------------------------------------------- /posture task/data/readme: -------------------------------------------------------------------------------- 1 | This folder saves data from neural network training 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CorticalDynamics 2 | Code for training neural network controllers to emulate posture and reach tasks. 3 | 4 | ## Dependecies. 5 | 6 | ### Python Libraries: 7 | 1. PyTorch deep learning library 8 | 2. Numpy 9 | 3. Scipy 10 | 4. Matplotlib 11 | 12 | ## File information 13 | Each folder has three python scripts. 14 | 1. muscularArmClass.py contains dynamics of 2-DOF planar arm containing shoulder and elbow joints and muscle activation dynamics. 15 | 2. NetworkClass.py contains script for neural network and cost computation for the executed movements. 16 | 3. optimizingscript.py runs the posture/reach tasks and optimizes/trains neural networks to learn an optimal control policy. 17 | 18 | 19 | ## To Run. 20 | 1. Go to posture/reach folder 21 | 2. Open and execute script titled "optimizingscript_xxtask.py" where xx = reach for reach task and xx = posture for posture task 22 | 3. Data is saved as .mat files in the folders named "data" 23 | 24 | 25 | ## Reference 26 | 27 | The code is a part of research article titled "Rotational dynamics in motor cortex are consistent with a feedback controller" in eLife (DOI: 10.7554/eLife.67256). 28 | 29 | eLife 2021;10:e67256 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /posture task/muscularArmClass.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Jul 18 12:25:40 2019 4 | 5 | @author: Hari - hariteja1992@gmail.com 6 | This code implements the state equations for a 2-DOF planar arm with 7 | 6 muscle actuators and non-linearities. 8 | 9 | In the tensor representation, the 3 dimensions represent : 10 | time tensor dimension (T) - 1 11 | sample number tensor dimension (C) - 2 12 | features dimension (N) - 3 13 | 14 | 15 | MOST IMPORTANT NOTE - 16 | Do not ever perform tensor assignment in the middle of 'forward' method. 17 | becasue torch.tensor does not remember or retain the graph unlike torch.cat. 18 | THis results in non-computation of gradient memory. 19 | 20 | for example the wrong code is as follows - 21 | h1 = ((-theta2_dot) * ((2*theta1_dot) + theta2_dot) * (self.a2 * torch.sin(theta2))) + (self.b11*theta1_dot) + (self.b12*theta2_dot) 22 | h2 = ((theta1_dot**2) * self.a2 * torch.sin(theta2)) + (self.b21*theta1_dot) + (self.b22*theta2_dot) 23 | H = torch.tensor([[h1], [h2]]) 24 | 25 | above tensor assignment to H eliminates the gradient graph. 26 | 27 | instead you should write the H assignment as 28 | 29 | H = torch.cat((h1.unsqueeze(0), h2.unsqueeze(0)), 0) 30 | This retains the grad_fn during the backprop 31 | """ 32 | import torch 33 | 34 | use_cuda = 'false' 35 | device = torch.device('cuda:0' if use_cuda else 'cpu') 36 | device = 'cpu' 37 | class muscular_arm(): 38 | def __init__(self, dh=0.01): 39 | super(muscular_arm, self).__init__() 40 | 41 | # fixed Monkey arm parameters (1=shoulder; 2=elbow) (refer to Lillicrap et al 2013, Li&Todorov2007) 42 | self.i1 = torch.tensor([0.025]).to(device) # kg*m**2 shoulder inertia 43 | self.i2 = torch.tensor([0.045]).to(device) # kg*m**2 elbow inertia 44 | self.m1 = torch.tensor([0.2108]).to(device) # kg mass of shopulder link 45 | self.m2 = torch.tensor([0.1938]).to(device) # kg mass of elbow link 46 | self.l1 = torch.tensor([0.145]).to(device) # meter 47 | self.l2 = torch.tensor([0.284]).to(device) # meter 48 | self.s1 = torch.tensor([0.0749]).to(device) 49 | self.s2 = torch.tensor([0.0757]).to(device) 50 | # fixed joint-friction 51 | self.b11 = torch.tensor([0.5]).to(device) # Could use low values like 0.05 also 52 | self.b22 = torch.tensor([0.5]).to(device) # Could use low values like 0.05 also 53 | self.b21 = torch.tensor([0.1]).to(device) # Could use low values like 0.02 - 0.05 also 54 | self.b12 = torch.tensor([0.1]).to(device) # Could use low values like 0.02 - 0.05 also 55 | 56 | # inertial matrix tmp vars 57 | self.a1 = (self.i1 + self.i2) + (self.m2 * self.l1**2) 58 | self.a2 = self.m2 * self.l1 * self.s2 59 | self.a3 = self.i2 60 | 61 | # Moment arm param in centimeters, but it can be directly used with this code... 62 | # ...as the scaling can be assumed to happen at the output layer (1 a.u = 100N force) 63 | self.M = torch.tensor([[2.0, -2.0, 0.0, 0.0, 1.50, -2.0], [0.0, 0.0, 2.0, -2.0, 2.0, -1.50]]).to(device) 64 | 65 | # Muscle properties 66 | self.theta0 = 0.0175*torch.tensor([[15.0, 4.88, 0.00, 0.00, 4.5, 2.12], [0.00, 0.00, 80.86, 109.32, 92.96, 91.52]]).to(device) 67 | self.L0 = torch.tensor([[7.32, 3.26, 6.4, 4.26, 5.95, 4.04]]).to(device) # in centimeters but ( self.M / self.L0 ) ratio will be unaffected as self.M is in centimeters too 68 | self.beta = 1.55 69 | self.omega = 0.81 70 | self.rho = 2.12 71 | self.Vmax = -7.39 72 | self.cv0 = -3.21 73 | self.cv1 = 4.17 74 | self.bv = 0.62 75 | self.av0 = -3.12 76 | self.av1 = 4.21 77 | self.av2 = -2.67 78 | 79 | # time-step of dynamics 80 | self.dh = dh 81 | 82 | self.cur_j_state = torch.zeros(9, 4).to(device) 83 | self.FV = torch.zeros(9,6).to(device) 84 | 85 | def forward(self, x, u, cur_perturbation): 86 | """ 87 | rout is the readout from M1 layer. mact is the muscle activation fcn 88 | """ 89 | # for linear muscle activation 90 | mus_inp = u 91 | #self.cur_j_state = x 92 | # for non-linear muscle activation - add F-L/V property contribution 93 | fl_out, fv_out = self.muscleDyn() 94 | flv_computed = fl_out * fv_out 95 | mus_out = fl_out * fv_out * mus_inp 96 | 97 | 98 | 99 | #muscle-force to joint-torque transformation (using M) 100 | self.tor = torch.mm(self.M, mus_out.transpose(0,1)) 101 | # add external torque to the muscle generated torque 102 | self.tor = self.tor.transpose(0,1) + cur_perturbation 103 | # run the arm dynamics 104 | net_command = self.tor 105 | out, x = self.armdyn(x, net_command) 106 | 107 | # compute cartesian-states from joint-states (Run armkinematics) 108 | #y = x 109 | #y = self.armkin(x) 110 | return x, net_command, mus_out 111 | 112 | 113 | def armdyn(self, x, u): 114 | batch_size = u.size(0) 115 | 116 | 117 | # extract joint angle states 118 | theta1 = x[:, 0].clone().unsqueeze(1) 119 | theta2 = x[:, 1].clone().unsqueeze(1) 120 | theta1_dot = x[:, 2].clone().unsqueeze(1) 121 | theta2_dot = x[:, 3].clone().unsqueeze(1) 122 | 123 | 124 | # compute inertia matrix 125 | I11 = self.a1 + (2*self.a2*(torch.cos(theta2))) 126 | I12 = self.a3 + (self.a2*(torch.cos(theta2))) 127 | I21 = self.a3 + (self.a2*(torch.cos(theta2))) 128 | I22 = self.a3 129 | I22 = I22.repeat(batch_size,1) 130 | 131 | 132 | # compute determinant of mass matrix [a * b of two tensors is the element-wise product] 133 | det = (I11 * I22) - (I12 * I21) 134 | 135 | # compute Inverse of inertia matrix 136 | Irow1 = torch.cat((I22, -I12), 1) 137 | Irow2 = torch.cat((-I21, I11), 1) 138 | 139 | # Iinv = (1/det.unsqueeze(1)) * torch.cat((Irow1.unsqueeze(1), Irow2.unsqueeze(1)), 1) # WORKING 140 | 141 | 142 | # compute extra torque H (coriolis, centripetal, friction) 143 | h1 = ((-theta2_dot) * ((2*theta1_dot) + theta2_dot) * (self.a2 * torch.sin(theta2))) + (self.b11*theta1_dot) + (self.b12*theta2_dot) 144 | h2 = ((theta1_dot**2) * self.a2 * torch.sin(theta2)) + (self.b21*theta1_dot) + (self.b22*theta2_dot) 145 | 146 | 147 | H = torch.cat((h1, h2), 1) 148 | 149 | 150 | # compute xdot = inv(M) * (u - H) 151 | torque = u - H 152 | 153 | # determione the terms in xdot matrix; xdot = [[dq1], [dq2], [ddq1], [ddq2]] 154 | dq1 = theta1_dot 155 | dq2 = theta2_dot 156 | dq = torch.cat((dq1, dq2), 1) 157 | 158 | Irow1 = (1/det) * Irow1 159 | Irow2 = (1/det) * Irow2 160 | # terms of Iinv matrix 161 | Iinv_11 = Irow1[:, 0].unsqueeze(1) 162 | Iinv_12 = Irow1[:, 1].unsqueeze(1) 163 | Iinv_21 = Irow2[:, 0].unsqueeze(1) 164 | Iinv_22 = Irow2[:, 1].unsqueeze(1) 165 | 166 | # Update acceleration of shoulder and elbow joints - FWDDYN equations 167 | ddq1 = Iinv_11*torque[:, 0].unsqueeze(1) + Iinv_12*torque[:, 1].unsqueeze(1) 168 | ddq2 = Iinv_21*torque[:, 0].unsqueeze(1) + Iinv_22*torque[:, 1].unsqueeze(1) 169 | ddq = torch.cat((ddq1, ddq2), 1) 170 | 171 | # update xdot 172 | x_dot = torch.cat((dq, ddq), 1) 173 | 174 | # step-update from x to x_next 175 | x_next = x + (self.dh * x_dot) 176 | 177 | x = x_next 178 | out = x[:, 0:2] 179 | # above transposing is done to rearrange the state and output in a column 180 | # as is demanded by the tensor form in which we wrote our optimization code 181 | return out, x 182 | 183 | def armkin(self, x): 184 | theta1 = x[:, 0].clone().unsqueeze(1) 185 | theta2 = x[:, 1].clone().unsqueeze(1) 186 | theta1_dot = x[:, 2].clone().unsqueeze(1) 187 | theta2_dot = x[:, 3].clone().unsqueeze(1) 188 | 189 | g11 = (self.l1 * torch.cos(theta1)) + (self.l2 * torch.cos(theta1+theta2)) 190 | g12 = (self.l1*torch.sin(theta1)) + (self.l2*torch.sin(theta1+theta2)) 191 | g13 = -theta1_dot*((self.l1*torch.sin(theta1))+(self.l2*torch.sin(theta1+theta2))) 192 | g13 = g13-(theta2_dot*(self.l2*torch.sin(theta1+theta2))) 193 | g14 = theta1_dot*((self.l1*torch.cos(theta1))+(self.l2*torch.cos(theta1+theta2))) 194 | g14=g14+(theta2_dot*(self.l2*torch.cos(theta1+theta2))) 195 | y = torch.cat((g11,g12,g13,g14), 1) 196 | return y 197 | 198 | def muscleDyn(self): 199 | 200 | # F-L/V dependency 201 | mus_l = 1 + self.M[0,:] * (self.theta0[0,:] - self.cur_j_state[:, 0].unsqueeze(1))/self.L0 + self.M[1,:] * (self.theta0[1,:] - self.cur_j_state[:, 1].unsqueeze(1))/self.L0 202 | mus_v = self.M[0, :] * self.cur_j_state[:, 2].unsqueeze(1)/self.L0 + self.M[1, :] * self.cur_j_state[:, 3].unsqueeze(1)/self.L0 203 | mus_v = -mus_v + 0.0 # mus_v = d (mus_l) / dt 204 | FL = torch.exp(-torch.abs((mus_l**self.beta - 1)/self.omega)**self.rho) 205 | FV = self.FV.clone() 206 | for i in range(0, 6): 207 | vel_i = mus_v[:, i] 208 | len_i = mus_l[:,i] 209 | FV[vel_i<=0, i] = (self.Vmax - vel_i[vel_i<=0])/(self.Vmax + vel_i[vel_i<=0]*(self.cv0 + self.cv1*len_i[vel_i<=0])) 210 | FV[vel_i >0, i] = (self.bv - vel_i[vel_i>0]*(self.av0+self.av1*len_i[vel_i>0]+self.av2*len_i[vel_i>0]**2))/(self.bv + vel_i[vel_i>0]) 211 | 212 | return FL, FV 213 | -------------------------------------------------------------------------------- /reach task/muscularArmClass.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Jul 18 12:25:40 2019 4 | 5 | @author: Hari - hariteja1992@gmail.com 6 | This code implements the state equations for a 2-DOF planar arm with 7 | 6 muscle actuators and non-linearities. 8 | 9 | In the tensor representation, the 3 dimensions represent : 10 | time tensor dimension - 1 11 | sample number tensor dimension - 2 12 | features dimension - 3 13 | 14 | 15 | MOST IMPORTANT NOTE - 16 | Do not ever perform tensor assignment in the middle of 'forward' method. 17 | becasue torch.tensor does not remember or retain the graph unlike torch.cat. 18 | THis results in non-computation of gradient memory. 19 | 20 | for example the wrong code is as follows - 21 | h1 = ((-theta2_dot) * ((2*theta1_dot) + theta2_dot) * (self.a2 * torch.sin(theta2))) + (self.b11*theta1_dot) + (self.b12*theta2_dot) 22 | h2 = ((theta1_dot**2) * self.a2 * torch.sin(theta2)) + (self.b21*theta1_dot) + (self.b22*theta2_dot) 23 | H = torch.tensor([[h1], [h2]]) 24 | 25 | above tensor assignment to H eliminates the gradient graph. 26 | 27 | instead you should write the H assignment as 28 | 29 | H = torch.cat((h1.unsqueeze(0), h2.unsqueeze(0)), 0) 30 | This retains the grad_fn during the backprop 31 | """ 32 | import torch 33 | 34 | use_cuda = torch.cuda.is_available() 35 | device = torch.device('cuda:0' if use_cuda else 'cpu') 36 | device = 'cpu' 37 | 38 | class muscular_arm(): 39 | def __init__(self, dh=0.01): 40 | super(muscular_arm, self).__init__() 41 | 42 | # fixed Monkey arm parameters (1=shoulder; 2=elbow) (refer to Lillicrap et al 2013, Li&Todorov2007) 43 | self.i1 = torch.tensor([0.025]).to(device) # kg*m**2 shoulder inertia 44 | self.i2 = torch.tensor([0.045]).to(device) # kg*m**2 elbow inertia 45 | self.m1 = torch.tensor([0.2108]).to(device) # kg mass of shopulder link 46 | self.m2 = torch.tensor([0.1938]).to(device) # kg mass of elbow link 47 | self.l1 = torch.tensor([0.145]).to(device) # meter 48 | self.l2 = torch.tensor([0.284]).to(device) # meter 49 | self.s1 = torch.tensor([0.0749]).to(device) 50 | self.s2 = torch.tensor([0.0757]).to(device) 51 | # fixed joint-friction 52 | self.b11 = torch.tensor([0.5]).to(device) # Could use low values like 0.05 also 53 | self.b22 = torch.tensor([0.5]).to(device) # Could use low values like 0.05 also 54 | self.b21 = torch.tensor([0.1]).to(device) # Could use low values like 0.02 - 0.05 also 55 | self.b12 = torch.tensor([0.1]).to(device) # Could use low values like 0.02 - 0.05 also 56 | 57 | # inertial matrix tmp vars 58 | self.a1 = (self.i1 + self.i2) + (self.m2 * self.l1**2) 59 | self.a2 = self.m2 * self.l1 * self.s2 60 | self.a3 = self.i2 61 | 62 | # Moment arm param in centimeters, but it can be directly used with this code... 63 | # ...as the scaling can be assumed to happen at the output layer (1 a.u = 100N force) 64 | self.M = torch.tensor([[2.0, -2.0, 0.0, 0.0, 1.50, -2.0], [0.0, 0.0, 2.0, -2.0, 2.0, -1.50]]).to(device) 65 | 66 | # Muscle properties 67 | self.theta0 = 0.0175*torch.tensor([[15.0, 4.88, 0.00, 0.00, 4.5, 2.12], [0.00, 0.00, 80.86, 109.32, 92.96, 91.52]]).to(device) 68 | self.L0 = torch.tensor([[7.32, 3.26, 6.4, 4.26, 5.95, 4.04]]).to(device) # in centimeters but ( self.M / self.L0 ) ratio will be unaffected as self.M is in centimeters too 69 | self.beta = 1.55 70 | self.omega = 0.81 71 | self.rho = 2.12 72 | self.Vmax = -7.39 73 | self.cv0 = -3.21 74 | self.cv1 = 4.17 75 | self.bv = 0.62 76 | self.av0 = -3.12 77 | self.av1 = 4.21 78 | self.av2 = -2.67 79 | 80 | # time-step of dynamics 81 | self.dh = dh 82 | 83 | self.cur_j_state = torch.zeros(17, 4).to(device) 84 | self.FV = torch.zeros(17,6).to(device) 85 | 86 | def forward(self, x, u): 87 | """ 88 | rout is the readout from M1 layer. mact is the muscle activation fcn 89 | """ 90 | # for linear muscle activation 91 | mus_inp = u 92 | #self.cur_j_state = x 93 | # for non-linear muscle activation - add F-L/V property contribution 94 | fl_out, fv_out = self.muscleDyn() 95 | flv_computed = fl_out * fv_out 96 | mus_out = flv_computed * mus_inp 97 | 98 | 99 | #muscle-force to joint-torque transformation (using M) 100 | self.tor = torch.mm(self.M, mus_out.transpose(0,1)) 101 | 102 | self.tor = self.tor.transpose(0,1) 103 | 104 | net_command = self.tor 105 | out, x = self.armdyn(x, net_command) 106 | 107 | return x, net_command, mus_out 108 | 109 | 110 | def armdyn(self, x, u): 111 | batch_size = u.size(0) 112 | 113 | 114 | # extract joint angle states 115 | theta1 = x[:, 0].clone().unsqueeze(1) 116 | theta2 = x[:, 1].clone().unsqueeze(1) 117 | theta1_dot = x[:, 2].clone().unsqueeze(1) 118 | theta2_dot = x[:, 3].clone().unsqueeze(1) 119 | 120 | 121 | # compute inertia matrix 122 | I11 = self.a1 + (2*self.a2*(torch.cos(theta2))) 123 | I12 = self.a3 + (self.a2*(torch.cos(theta2))) 124 | I21 = self.a3 + (self.a2*(torch.cos(theta2))) 125 | I22 = self.a3 126 | I22 = I22.repeat(batch_size,1) 127 | 128 | 129 | # compute determinant of mass matrix [a * b of two tensors is the element-wise product] 130 | det = (I11 * I22) - (I12 * I21) 131 | 132 | # compute Inverse of inertia matrix 133 | Irow1 = torch.cat((I22, -I12), 1) 134 | Irow2 = torch.cat((-I21, I11), 1) 135 | 136 | # Iinv = (1/det.unsqueeze(1)) * torch.cat((Irow1.unsqueeze(1), Irow2.unsqueeze(1)), 1) # WORKING 137 | 138 | 139 | # compute extra torque H (coriolis, centripetal, friction) 140 | h1 = ((-theta2_dot) * ((2*theta1_dot) + theta2_dot) * (self.a2 * torch.sin(theta2))) + (self.b11*theta1_dot) + (self.b12*theta2_dot) 141 | h2 = ((theta1_dot**2) * self.a2 * torch.sin(theta2)) + (self.b21*theta1_dot) + (self.b22*theta2_dot) 142 | 143 | 144 | H = torch.cat((h1, h2), 1) 145 | 146 | 147 | # compute xdot = inv(M) * (u - H) 148 | #torque = u - H 149 | 150 | 151 | #print(torque) 152 | #torque = torque.unsqueeze(2) # WORKING 153 | #print(torque) 154 | # determione the terms in xdot matrix; xdot = [[dq1], [dq2], [ddq1], [ddq2]] 155 | dq1 = theta1_dot 156 | dq2 = theta2_dot 157 | dq = torch.cat((dq1, dq2), 1) 158 | 159 | 160 | 161 | # VISCOUS FORCE-FEILD 162 | #torque = u - H + ext_force 163 | 164 | torque = u - H 165 | 166 | Irow1 = (1/det) * Irow1 167 | Irow2 = (1/det) * Irow2 168 | # terms of Iinv matrix 169 | Iinv_11 = Irow1[:, 0].unsqueeze(1) 170 | Iinv_12 = Irow1[:, 1].unsqueeze(1) 171 | Iinv_21 = Irow2[:, 0].unsqueeze(1) 172 | Iinv_22 = Irow2[:, 1].unsqueeze(1) 173 | 174 | # Update acceleration of shoulder and elbow joints - FWDDYN equations 175 | ddq1 = Iinv_11*torque[:, 0].unsqueeze(1) + Iinv_12*torque[:, 1].unsqueeze(1) 176 | ddq2 = Iinv_21*torque[:, 0].unsqueeze(1) + Iinv_22*torque[:, 1].unsqueeze(1) 177 | ddq = torch.cat((ddq1, ddq2), 1) 178 | 179 | 180 | #ddq = torch.matmul(Iinv, torque) # matmul is a bit slower than the by 1 sec for batch matrix multiplication # WORKING 181 | #ddq = torch.einsum('ijk,ikl->ijl', [Iinv, torque]) # WORKING 182 | 183 | # update xdot 184 | x_dot = torch.cat((dq, ddq), 1) 185 | 186 | # step-update from x to x_next 187 | x_next = x + (self.dh * x_dot) 188 | 189 | x = x_next 190 | out = x[:, 0:2] 191 | return out, x 192 | 193 | def armkin(self, x): 194 | theta1 = x[:, 0].clone().unsqueeze(1) 195 | theta2 = x[:, 1].clone().unsqueeze(1) 196 | theta1_dot = x[:, 2].clone().unsqueeze(1) 197 | theta2_dot = x[:, 3].clone().unsqueeze(1) 198 | 199 | g11 = (self.l1 * torch.cos(theta1)) + (self.l2 * torch.cos(theta1+theta2)) 200 | g12 = (self.l1*torch.sin(theta1)) + (self.l2*torch.sin(theta1+theta2)) 201 | g13 = -theta1_dot*((self.l1*torch.sin(theta1))+(self.l2*torch.sin(theta1+theta2))) 202 | g13 = g13-(theta2_dot*(self.l2*torch.sin(theta1+theta2))) 203 | g14 = theta1_dot*((self.l1*torch.cos(theta1))+(self.l2*torch.cos(theta1+theta2))) 204 | g14=g14+(theta2_dot*(self.l2*torch.cos(theta1+theta2))) 205 | y = torch.cat((g11,g12,g13,g14), 1) 206 | return y 207 | 208 | def muscleDyn(self): 209 | 210 | # F-L/V dependency 211 | mus_l = 1 + self.M[0,:] * (self.theta0[0,:] - self.cur_j_state[:, 0].unsqueeze(1))/self.L0 + self.M[1,:] * (self.theta0[1,:] - self.cur_j_state[:, 1].unsqueeze(1))/self.L0 212 | mus_v = self.M[0, :] * self.cur_j_state[:, 2].unsqueeze(1)/self.L0 + self.M[1, :] * self.cur_j_state[:, 3].unsqueeze(1)/self.L0 213 | mus_v = -mus_v + 0.0 # mus_v = d (mus_l) / dt 214 | FL = torch.exp(-torch.abs((mus_l**self.beta - 1)/self.omega)**self.rho) 215 | FV = self.FV.clone() 216 | for i in range(0, 6): 217 | vel_i = mus_v[:, i] 218 | len_i = mus_l[:,i] 219 | FV[vel_i<=0, i] = (self.Vmax - vel_i[vel_i<=0])/(self.Vmax + vel_i[vel_i<=0]*(self.cv0 + self.cv1*len_i[vel_i<=0])) 220 | FV[vel_i >0, i] = (self.bv - vel_i[vel_i>0]*(self.av0+self.av1*len_i[vel_i>0]+self.av2*len_i[vel_i>0]**2))/(self.bv + vel_i[vel_i>0]) 221 | 222 | return FL, FV 223 | -------------------------------------------------------------------------------- /posture task/optimizingscript_posturetask.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on February 2021 4 | 5 | @author: hariteja1992@gmail.com 6 | 7 | This code optimizes the neural networks for posture perturbation task. 8 | 9 | Dependecies: 10 | 1. biomechanical arm model from "MuscularArm.py" 11 | 2. Network class from "FeedbackController.py" 12 | 3. Scientific libraries such as numpy, matplotlib etc., 13 | 4. PyTorch deep-learning library from: https://pytorch.org/get-started/locally/ 14 | 15 | code structure: 16 | 1. define the time duration, feedback properties, task goal 17 | 2. initialize the neural network and optimizer 18 | 3. While optimizing: 19 | a. run the control and movement for one time-instance 20 | b. collect the trajectory and network information 21 | c. backpropagate the error to compute the gradients (dJ/dw) 22 | d. change weights using ADAM rule 23 | 24 | variables of interest for plotting are stored in "collector_" variables inside the 25 | "feedback_controller" class 26 | """ 27 | 28 | import torch 29 | import torch.optim as optim 30 | import numpy as np 31 | import matplotlib.pyplot as plt 32 | import scipy.io 33 | from NetworkClass import feedback_controller, costcriterionPosture 34 | 35 | use_cuda = 'false' 36 | device = torch.device('cuda:0' if use_cuda else 'cpu') 37 | device = 'cpu' 38 | 39 | # Time-settings 40 | dh = 0.01 # 10 ms sim-step 41 | T = 3.0 # 3 seconds simulation duration (300 time-steps) 42 | #time_seq = np.linspace(0.0,T/dh-1,T/dh) 43 | # if the time_seq def above yields a float-int error use the following line instead 44 | time_seq = np.linspace(0.0,299,300) 45 | perturbation_time = 100 # around t = 1sec apply perturbation 46 | 47 | # Task scenario settings 48 | num_joints = 2 49 | num_torque_combinations = 9 50 | 51 | 52 | # spatial target in radians (Home location for the hand/end-effector) 53 | xtarg = np.array([0.4368]) # shoulder angle 54 | ytarg = np.array([1.4464]) # elbow angle 55 | 56 | 57 | # Define the tensors to carry task information. 58 | # each tensor is [T, C, N].Where 59 | # T = time sequence length 60 | # C = number of task conditions (in this case number of different perturbations) 61 | # N = signal dimensionality (number of neurons (or) number of sensory-feedback components) 62 | # input_targ_seq as network spatial target, perturb_seq as the external torques n [sho, elb] joint-directions 63 | input_targ_seq = np.zeros([time_seq.size, num_torque_combinations, num_joints]) 64 | perturb_seq = np.zeros([time_seq.size, num_torque_combinations, num_joints]) 65 | test_perturb_seq = np.zeros([time_seq.size, num_torque_combinations, num_joints]) 66 | 67 | # apply perturbations (radial in shoulder-elbow space) 68 | pert_angles = np.array(np.linspace(0, 360, num_torque_combinations)) 69 | test_pert_angles = np.random.uniform(low=0.0, high=360.0, size=(num_torque_combinations,)) 70 | # perturb with 0.2 Nm of l2-norm joint-torque 71 | xpert = 0.2 * np.cos(np.deg2rad(pert_angles)) 72 | ypert = 0.2 * np.sin(np.deg2rad(pert_angles)) 73 | xpert[-1] = 0.0 # include a no perturbation condition at the end 74 | ypert[-1] = 0.0 # include a no perturbation condition at the end 75 | 76 | 77 | ## write the temporal and conditional aspects of the task into 3-D (T by C by N) tensor format 78 | input_targ_seq[:, :, 0] = xtarg[:] # target shoulder joint config 79 | input_targ_seq[:, :, 1] = ytarg[:] # target elbow joint config 80 | perturb_seq[perturbation_time:, :num_torque_combinations, 0] = xpert # shoulder perturbation info 81 | perturb_seq[perturbation_time:, :num_torque_combinations, 1] = ypert # elbow perturbation info 82 | 83 | # wrap the numpy input sequence into tensors for pytorch 84 | input_targ_seq = torch.from_numpy(input_targ_seq) 85 | perturb_seq = torch.from_numpy(perturb_seq) 86 | test_perturb_seq = torch.from_numpy(test_perturb_seq) 87 | input_targ_seq = input_targ_seq.float().to(device) 88 | perturb_seq = perturb_seq.float().to(device) 89 | 90 | # specify home location as a torch tensor 91 | home_jstate = input_targ_seq[0, :, :] 92 | 93 | # Which kind of network? RNN or FNN 94 | rec_connection_status = 'True' # enter 'False' to switch off recurrent connections 95 | 96 | # simulation and file settings for training/optimizing the networks 97 | max_simulations = 1 98 | EPOCHS = 2000 99 | num_optimizations = 1 100 | file_name = 'Posture_' 101 | fb_type = 'posvelmus_fb_' 102 | 103 | # The while loop is for training multiple networks 104 | # The for-loop inside is to train one network for fixed EPOCHS or until a reasonabe cost is obtained. 105 | while num_optimizations <= max_simulations: 106 | # initilize a neural network instance and send it to device = 'cpu' 107 | posture_sim = feedback_controller(dh, home_jstate) 108 | posture_sim.num_inplayer_neurons =500 109 | posture_sim.num_outplayer_neurons = 500 110 | posture_sim.num_muscles = 6 111 | posture_sim.feedback_delay = 5 # 50ms delay (or 5 time-steps) 112 | posture_sim.num_feedbacksignals = 12 # 2 target pos + 6 muscle_fb + 2 actual pos + 2 actual vel 113 | posture_sim.perturbation_time = perturbation_time 114 | posture_sim.num_torque_combinations = num_torque_combinations 115 | posture_sim.float() 116 | posture_sim.to(device) 117 | 118 | # decide if the network has recurrent connections or not 119 | posture_sim.rec_connection_status = rec_connection_status 120 | 121 | # Set the neural newtork paramters to be optimized. 122 | lrate = 3.0e-4 123 | if posture_sim.rec_connection_status == 'True': 124 | optim_params = list(posture_sim.inplayer.parameters()) + list(posture_sim.outplayer.parameters()) + list(posture_sim.musclelayer.parameters()) 125 | optim_params += list(posture_sim.inplayerself.parameters()) + list(posture_sim.outplayerself.parameters()) 126 | print('REC network selected with optimizable recurrent connections') 127 | else: 128 | optim_params = list(posture_sim.inplayer.parameters()) + list(posture_sim.outplayer.parameters()) + list(posture_sim.musclelayer.parameters()) 129 | print('NOREC network selected with no recurrent connections') 130 | # define the optimizer 131 | optimizer = optim.Adam(optim_params, lr=lrate, weight_decay=1e-8) # good for the RNN case lr = 1.0e-4 132 | 133 | # Loss value holders 134 | cost_curve_for_plotting = np.empty(0) 135 | total_loss_for_plotting = np.zeros(EPOCHS) 136 | 137 | # Run the optimization until the end of epochs (or can be modified to run 138 | # until a satisfactory error is reached) 139 | for epoch in range(1, EPOCHS): 140 | # reset the arm movement simulation to initial states of network and the arm 141 | posture_sim.resetsim() 142 | 143 | # reset the optimizer gradients 144 | optimizer.zero_grad() 145 | 146 | # Run the arm control simulation for the duration set as time_seq and 147 | # collect the joint, muscle and network information 148 | joint_kinematics = posture_sim.forward(input_targ_seq, perturb_seq) 149 | x_pos = joint_kinematics[:, :, 0] # shoulder displacement 150 | y_pos = joint_kinematics[:, :, 1] # elbow displacement 151 | x_vel = joint_kinematics[: ,:, 2] # shoulder velocity 152 | y_vel = joint_kinematics[:, :, 3] # elbow velocity 153 | 154 | # Compute the loss function defined by "costcriterionPosture" 155 | loss_x = costcriterionPosture(posture_sim, input_targ_seq[:, :, 0], x_pos, x_vel) 156 | loss_y = costcriterionPosture(posture_sim, input_targ_seq[:, :, 1], y_pos, y_vel) 157 | loss = loss_x + loss_y 158 | 159 | # Backpropagate the loss to compute loss gradients w.r.t network paramters 160 | loss.backward() # does backprop and calculates gradients 161 | cost_curve_for_plotting = np.append(cost_curve_for_plotting, loss.item()) 162 | 163 | # Update the newtork weights 164 | optimizer.step() 165 | 166 | 167 | total_loss_for_plotting[epoch] = loss.item() 168 | 169 | 170 | if epoch%10 == 0: 171 | print("Cur instance Loss: {:.6f}".format(loss.item()), end=' ') 172 | print(' after Epoch number: {}/{}...'.format(epoch, EPOCHS), end=' ') 173 | print('num_optimizations: {}/{}'.format(num_optimizations, max_simulations, )) 174 | 175 | if epoch % 100 == 0: 176 | plt.figure() 177 | plt.plot(posture_sim.collector_jointstate[:,:,0].data.cpu().numpy(), posture_sim.collector_jointstate[:,:,1].data.cpu().numpy()) 178 | plt.plot(input_targ_seq[-1,:,0].data.cpu().numpy(), input_targ_seq[-1,:,1].data.cpu().numpy(), 'o') 179 | plt.show() 180 | 181 | plt.figure() 182 | plt.plot(posture_sim.collector_muscleactivity[:,1,:].data.cpu().numpy()) 183 | plt.show() 184 | 185 | plt.figure() 186 | plt.plot(posture_sim.collector_outplayeractivity[:, 0, :].data.cpu().numpy()) 187 | plt.show() 188 | 189 | plt.figure() 190 | plt.plot(np.log(total_loss_for_plotting[1:epoch])) 191 | plt.show() 192 | 193 | if epoch%100 == 0: 194 | outplayer_data = posture_sim.collector_outplayeractivity.data.cpu().numpy() 195 | file_no = 'trial' + '0' + str(num_optimizations) 196 | scipy.io.savemat('data/M1_' + file_name + fb_type + file_no + '.mat', {'m1data':outplayer_data}) 197 | 198 | networkinp_data = posture_sim.collector_networkinputs.data.cpu().numpy() 199 | scipy.io.savemat('data/Inp_' + file_name + fb_type + file_no + '.mat', {'inpdata':networkinp_data}) 200 | 201 | inplayer_data = posture_sim.collector_inplayeractivity.data.cpu().numpy() 202 | scipy.io.savemat('data/S1_' + file_name + fb_type + file_no + '.mat', {'S1data':inplayer_data}) 203 | 204 | muscle_data = posture_sim.collector_muscleactivity.data.cpu().numpy() 205 | scipy.io.savemat('data/Mus_' + file_name + fb_type + file_no + '.mat', {'musdata':muscle_data}) 206 | 207 | cartesiankin_data = posture_sim.collector_cartesianstate.data.cpu().numpy() 208 | scipy.io.savemat('data/Cartkin_' + file_name + fb_type + file_no + '.mat', {'cartkindata':cartesiankin_data}) 209 | 210 | jointkin_data = posture_sim.collector_jointstate.data.cpu().numpy() 211 | scipy.io.savemat('data/Jointkin_' + file_name + fb_type + file_no + '.mat', {'jointkindata':jointkin_data}) 212 | 213 | torque_data = posture_sim.collector_jointtorques.data.cpu().numpy() 214 | scipy.io.savemat('data/Torque_' + file_name + fb_type + file_no + '.mat', {'torquedata':torque_data}) 215 | 216 | scipy.io.savemat('data/Cost_' + file_name + fb_type + file_no + '.mat', {'costcurve':cost_curve_for_plotting}) 217 | 218 | if num_optimizations == 1 and epoch > 100: 219 | torch.save(posture_sim.state_dict(), 'Optimizednetwork_' + file_name + fb_type + file_no + '.pth') 220 | 221 | num_optimizations += 1 222 | -------------------------------------------------------------------------------- /reach task/optimizingscript_reachtask.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on February 2021 4 | 5 | @author: hariteja1992@gmail.com 6 | 7 | This code optimizes the neural networks for center-out upper-limb reaching task. 8 | 9 | Dependecies: 10 | 1. biomechanical arm model from "MuscularArm.py" 11 | 2. Network class from "FeedbackController.py" 12 | 3. Scientific libraries such as numpy, matplotlib etc., 13 | 4. PyTorch deep-learning library from: https://pytorch.org/get-started/locally/ 14 | 15 | code structure: 16 | 1. define the time duration, feedback properties, task goal 17 | 2. initialize the neural network and optimizer 18 | 3. While optimizing: 19 | a. run the control and movement for one time-instance 20 | b. collect the trajectory and network information 21 | c. backpropagate the error to compute the gradients (dJ/dw) 22 | d. change weights using ADAM rule 23 | 24 | variables of interest for plotting are stored in "collector_" variables inside the 25 | "feedback_controller" class 26 | 27 | Modifications from the manuscript simulation settings for reach task: 28 | To enable relatively faster optimization, time durations have been reduced 29 | from the original article. In the article the hold_cue/GO_signal (that indicates the arm 30 | should stay at home even when target appears on screen) turns off at 800ms (80 time-steps), 31 | and total simulation runs for 300 time-steps. In this simulation, hold-cue does not 32 | exist. The simulated arm should start moving towards the target as soon as it is 33 | presented. Hence only a step-target signal is simulated here. 34 | 35 | Contact the author for simulation with additional hold-phase. 36 | """ 37 | 38 | 39 | import torch 40 | import torch.nn as nn 41 | import torch.optim as optim 42 | from torch.autograd import gradcheck 43 | import numpy as np 44 | import matplotlib.pyplot as plt 45 | from torch.distributions import normal 46 | import scipy.io 47 | from NetworkClass import feedback_controller, costCriterionReaching 48 | 49 | use_cuda = 'false' 50 | device = torch.device('cuda:0' if use_cuda else 'cpu') 51 | device = 'cpu' 52 | 53 | # time-settings 54 | # To enable fast optimization, time durations have been reduced from the original 55 | # article. In the article the hold_cue turns off at 800ms (80 time-steps), and 56 | # total simulation runs for 300 time-steps. In this simulation, the hold-cue 57 | # turns-off at 300ms (30 time-steps) and total simulation duration is 1300ms. 58 | dh = 0.01 # 10 ms sim-step 59 | T = 1.3 # 1300ms simulation duration (130 time-steps) 60 | #time_seq = np.linspace(0.0,T/dh-1,T/dh) # issue with float to int conversion 61 | time_seq = np.linspace(0.0,129,130) 62 | hold_cue_time = 30 63 | 64 | # Task scenario settings 65 | num_joints = 2 66 | num_reach_combinations = 17 # 16 radial targets + 1 home location 67 | 68 | # arm init parameters 69 | sho_ang = 32.6 70 | elb_ang = 84.2 71 | home_joint_state = torch.tensor([[np.deg2rad(sho_ang), np.deg2rad(elb_ang)]]) 72 | 73 | # large amplitude targets in joint space (5 cm in cartesian space) 74 | xtarg = np.array([0.4368, 0.5829, 0.7279, 0.8469, 0.9182, 0.9311, 0.8892, 0.8032, 0.6840, 0.5439, 0.4017,0.2857,0.2258,0.2371,0.3138,0.4368, 0.5689]) 75 | ytarg = np.array([1.4464,1.2781,1.1311,1.0333,1.0093,1.0661,1.1878,1.3469,1.5162,1.6705,1.7863,1.8425,1.8275,1.7444,1.6098,1.4464, 1.4697]) 76 | #small amplitude target displacement in joint space (2 cm in cartesian space) 77 | #xtarg2 = np.array([0.5102, 0.5670, 0.6239, 0.6712, 0.7011, 0.7088, 0.6938, 0.6586, 0.6087, 0.5516, 0.4969,0.4544,0.4326,0.4359,0.4636,0.5102, 0.5689]) 78 | #ytarg2 = np.array([1.4677,1.4013,1.3453,1.3098,1.3013,1.3215,1.3666,1.4282,1.4956,1.5574,1.6031,1.6249,1.6191,1.5866,1.5331,1.4677, 1.4697]) 79 | # Training mini-batch wise 80 | 81 | reach_train_angles = np.array(np.linspace(0, 360, 16)) 82 | xtargcart = 0.05*np.cos(np.deg2rad(reach_train_angles)) 83 | ytargcart = 0.05*np.sin(np.deg2rad(reach_train_angles)) 84 | xtargcart = np.concatenate((xtargcart, np.array([0.0])), axis=0) 85 | ytargcart = np.concatenate((ytargcart, np.array([0.0])), axis=0) 86 | #xtargcart2 = 0.02*np.cos(np.deg2rad(reach_train_angles)) 87 | #ytargcart2 = 0.02*np.sin(np.deg2rad(reach_train_angles)) 88 | #xtargcart2 = np.concatenate((xtargcart2, np.array([0.0])), axis=0) 89 | #ytargcart2 = np.concatenate((ytargcart2, np.array([0.0])), axis=0) 90 | 91 | # Define the tensors to carry task information. 92 | # each tensor is [T, C, N].Where 93 | # T = time sequence length 94 | # C = number of task conditions (in this case number of different perturbations) 95 | # N = signal dimensionality (number of neurons (or) number of sensory-feedback components) 96 | # input_targ_seq as network spatial target, perturb_seq as the external torques n [sho, elb] joint-directions 97 | input_targ_seq = np.zeros([time_seq.size, num_reach_combinations, num_joints]) 98 | cart_targ_seq = np.zeros([time_seq.size, num_reach_combinations, num_joints]) 99 | 100 | ### preparatory period 101 | input_targ_seq[:30, :, 0] = 0.5689 102 | input_targ_seq[:30, :, 1] = 1.4697 103 | ## Movement period 104 | input_targ_seq[30:, :, 0] = xtarg[:] 105 | input_targ_seq[30:, :, 1] = ytarg[:] 106 | ## preparatory period (x = x0; y0) 107 | cart_targ_seq[:30, :, 0] = -0.0059 108 | cart_targ_seq[:30, :, 1] = 0.3316 109 | # Movement period (x = r*cos(theta) - x0; y = r*sin(theta) - y0) 110 | cart_targ_seq[30:, :, 0] = xtargcart[:] - 0.0059 111 | cart_targ_seq[30:, :, 1] = ytargcart[:] + 0.3316 112 | 113 | 114 | ## wrap the numpy input sequence into tensors for torch 115 | input_targ_seq = torch.from_numpy(input_targ_seq) 116 | input_targ_seq = input_targ_seq.float().to(device) 117 | 118 | cart_targ_seq = torch.from_numpy(cart_targ_seq) 119 | cart_targ_seq = cart_targ_seq.float().to(device) 120 | 121 | 122 | ## simulation and file settings for training/optimizing the networks 123 | max_simulations = 1 124 | EPOCHS = 2000 125 | num_optimizations = 1 126 | file_name = 'Reach_' 127 | fb_type = 'posvelmus_fb_' 128 | 129 | 130 | 131 | # begin training 132 | num_sims = 1 133 | sim_number = '01' 134 | # The while loop is for training multiple networks 135 | # The for-loop inside is to train one network for fixed EPOCHS or until a reasonabe cost is obtained. 136 | while num_optimizations <= max_simulations: 137 | # initialize the control class 138 | reach_sim = feedback_controller(dh,home_joint_state) 139 | reach_sim.float().to(device) 140 | 141 | # fix the network parameters 142 | reach_sim.num_inplayer_neurons =500 143 | reach_sim.num_outplayer_neurons = 500 144 | reach_sim.num_muscles = 6 145 | reach_sim.feedback_delay = 5 # 50ms delay (or 5 time-steps) 146 | reach_sim.num_feedbacksignals = 12 # 2 target pos + 6 muscle_fb + 2 actual pos + 2 actual vel 147 | reach_sim.num_reach_combinations = num_reach_combinations 148 | reach_sim.num_network_layers = 2 149 | reach_sim.rec_conn = 'False' 150 | reach_sim.float() 151 | reach_sim.to(device) 152 | 153 | 154 | if reach_sim.num_network_layers == 1: 155 | print('Simulation using only one neural network layer...') 156 | if reach_sim.rec_conn == 'True': 157 | optim_params = list(reach_sim.inplayer.parameters()) + list(reach_sim.musclelayer.parameters()) #+ list(reach_sim.outplayer.parameters()) + list(reach_sim.m2layer.parameters()) 158 | optim_params += list(reach_sim.inplayerself.parameters()) #+ list(reach_sim.outplayerself.parameters()) + list(reach_sim.m2layerself.parameters()) 159 | print('REC connections exist') 160 | if reach_sim.rec_conn == 'False': 161 | optim_params = list(reach_sim.inplayer.parameters()) + list(reach_sim.musclelayer.parameters()) #+ list(reach_sim.outplayer.parameters()) + list(reach_sim.m2layer.parameters()) 162 | print('REC connections absent') 163 | 164 | if reach_sim.num_network_layers == 2: 165 | print('Simulation using two neural network layers...') 166 | if reach_sim.rec_conn == 'True': 167 | optim_params = list(reach_sim.inplayer.parameters()) + list(reach_sim.musclelayer.parameters()) #+ list(reach_sim.outplayer.parameters()) + list(reach_sim.m2layer.parameters()) 168 | optim_params += list(reach_sim.inplayerself.parameters()) + list(reach_sim.outplayer.parameters()) + list(reach_sim.outplayerself.parameters()) 169 | print('REC connections exist') 170 | if reach_sim.rec_conn == 'False': 171 | optim_params = list(reach_sim.inplayer.parameters()) + list(reach_sim.musclelayer.parameters()) #+ list(reach_sim.outplayer.parameters()) + list(reach_sim.m2layer.parameters()) 172 | optim_params += list(reach_sim.outplayer.parameters()) 173 | print('REC connections absent') 174 | lrate = 2.0e-4 175 | optimizer = optim.Adam(optim_params, lr=lrate, weight_decay=1e-8) 176 | 177 | # Loss value holders 178 | cost_curve_for_plotting = np.empty(0) 179 | total_loss_for_plotting = np.zeros(EPOCHS) 180 | 181 | # Run the optimization until the end of epochs (or can be modified to run 182 | # until a satisfactory error is reached) 183 | for epoch in range(1, EPOCHS): 184 | # set variable preparation time-delay 185 | variable_movinit_delay = np.random.randint(hold_cue_time, hold_cue_time + 1) 186 | input_targ_seq = np.zeros([time_seq.size, num_reach_combinations, num_joints]) 187 | 188 | # target is the home location until movement init signal is presented 189 | input_targ_seq[:variable_movinit_delay, :, 0] = 0.5689 190 | input_targ_seq[:variable_movinit_delay, :, 1] = 1.4697 191 | # radial targets after movement init signal is presented 192 | input_targ_seq[variable_movinit_delay:, :, 0] = xtarg[:] 193 | input_targ_seq[variable_movinit_delay:, :, 1] = ytarg[:] 194 | input_targ_seq = torch.from_numpy(input_targ_seq) 195 | input_targ_seq = input_targ_seq.float().to(device) 196 | 197 | reach_sim.resetsim() 198 | optimizer.zero_grad() 199 | 200 | joint_kinematics = reach_sim.forward(input_targ_seq, variable_movinit_delay) 201 | x_pos = joint_kinematics[:, :, 0] 202 | y_pos = joint_kinematics[:, :, 1] 203 | x_vel = joint_kinematics[: ,:, 2] 204 | y_vel = joint_kinematics[:, :, 3] 205 | 206 | # Compute the loss function defined by "costCriterionReaching" 207 | loss_x = costCriterionReaching(reach_sim, input_targ_seq[:, :, 0], x_pos, x_vel, variable_movinit_delay) 208 | loss_y = costCriterionReaching(reach_sim, input_targ_seq[:, :, 1], y_pos, y_vel, variable_movinit_delay) 209 | loss = loss_x + loss_y 210 | 211 | # Backpropagate the loss to compute loss gradients w.r.t network paramters 212 | loss.backward() 213 | cost_curve_for_plotting = np.append(cost_curve_for_plotting, loss.item()) 214 | 215 | # Update the newtork weights 216 | optimizer.step() 217 | 218 | total_loss_for_plotting[epoch] = loss.item() 219 | 220 | if epoch%100 == 0: 221 | print("Cur instance Loss: {:.6f}".format(loss.item()), end=' ') 222 | print(' after Epoch number: {}/{}...'.format(epoch, EPOCHS), end=' ') 223 | print('num_optimizations: {}/{}'.format(num_optimizations, max_simulations, )) 224 | 225 | if epoch%200 == 0: 226 | # Plot the deisred and followed arm trajectory 227 | plt.figure() 228 | plt.plot(reach_sim.collector_cartesianstate[:,:,0].data.cpu().numpy(), reach_sim.collector_cartesianstate[:,:,1].data.cpu().numpy()) 229 | plt.plot(cart_targ_seq[-1,:,0].data.cpu().numpy(), cart_targ_seq[-1,:,1].data.cpu().numpy(), 'o') 230 | plt.show() 231 | 232 | plt.figure() 233 | plt.plot(reach_sim.collector_jointstate[:,:,0].data.cpu().numpy(), reach_sim.collector_jointstate[:,:,1].data.cpu().numpy()) 234 | plt.plot(input_targ_seq[-1,:,0].data.cpu().numpy(), input_targ_seq[-1,:,1].data.cpu().numpy(), 'o') 235 | plt.show() 236 | 237 | plt.figure() 238 | plt.plot(reach_sim.collector_outplayeractivity[:, 0, :].data.cpu().numpy()) 239 | plt.show() 240 | 241 | plt.figure() 242 | plt.plot(reach_sim.collector_muscleactivity[:, 0, :].data.cpu().numpy()) 243 | plt.show() 244 | # 245 | plt.figure() 246 | plt.plot(reach_sim.collector_jointstate[:, 2, 0].data.cpu().numpy()) 247 | plt.plot(input_targ_seq[:, 2, 0].data.cpu().numpy(), '--') 248 | plt.plot(reach_sim.collector_jointstate[:, 16, 0].data.cpu().numpy()) 249 | plt.show() 250 | # 251 | 252 | if epoch%100 == 0: 253 | outplayer_data = reach_sim.collector_outplayeractivity.data.cpu().numpy() 254 | scipy.io.savemat('data/M1_'+file_name+sim_number+'.mat', {'m1data':outplayer_data}) 255 | 256 | muscle_data = reach_sim.collector_muscleactivity.data.cpu().numpy() 257 | scipy.io.savemat('data/Mus_'+file_name+sim_number+'.mat', {'musdata':muscle_data}) 258 | 259 | cartesiankin_data = reach_sim.collector_cartesianstate.data.cpu().numpy() 260 | scipy.io.savemat('data/Cartkin_'+file_name+sim_number+'.mat', {'cartkindata':cartesiankin_data}) 261 | 262 | jointkin_data = reach_sim.collector_jointstate.data.cpu().numpy() 263 | scipy.io.savemat('data/Jointkin_'+file_name+sim_number+'.mat', {'jointkindata':jointkin_data}) 264 | 265 | networkinp_data = reach_sim.collector_networkinputs.data.cpu().numpy() 266 | scipy.io.savemat('data/Inp_'+file_name+sim_number+'.mat', {'inpdata':networkinp_data}) 267 | 268 | inplayer_data = reach_sim.collector_inplayeractivity.data.cpu().numpy() 269 | scipy.io.savemat('data/S1_'+file_name+sim_number+'.mat', {'s1data':inplayer_data}) 270 | 271 | 272 | torch.save(reach_sim.state_dict(), 'ReachTrainednet_'+file_name+sim_number+'.pth') 273 | 274 | num_optimizations += 1 275 | sim_number = '0' + str(num_sims) 276 | -------------------------------------------------------------------------------- /posture task/NetworkClass.py: -------------------------------------------------------------------------------- 1 | # cpde fpr storing motor system network classes 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.optim as optim 6 | import numpy as np 7 | from muscularArmClass import muscular_arm 8 | from torch.distributions import normal 9 | 10 | use_cuda = 'false' 11 | device = torch.device('cuda:0' if use_cuda else 'cpu') 12 | device = 'cpu' 13 | 14 | class feedback_controller(nn.Module): 15 | def __init__(self, dh, home_joint_state): 16 | super(feedback_controller, self).__init__() 17 | # fixed control parameters - default values 18 | self.dh = dh # simulation time-step 19 | self.num_network_inputs = 12 20 | self.num_inplayer_neurons = 500 21 | self.num_outplayer_neurons = 500 22 | self.num_muscles = 6 23 | self.num_torque_combinations = 9 24 | self.rec_connection_status = 'True' 25 | 26 | self.home_joint_state = home_joint_state 27 | 28 | # Motor noise 29 | self.noise_neural = normal.Normal(0.0, 0.03) 30 | self.noise_muscle = normal.Normal(0.0, 0.03) 31 | 32 | # Intantiate the biomechanical arm dynamics at home location 33 | self.arm_dynamics = muscular_arm(dh) 34 | 35 | # Create neural network by means of torch functions 36 | # network config: 37 | # 1. inplayer 38 | # 2. outplayer 39 | # 3. muscle layer 40 | 41 | # Input layer receives sensory input + recurrent connections 42 | self.inplayer = nn.Linear(self.num_network_inputs, self.num_inplayer_neurons, bias=True) 43 | self.inplayer.bias = torch.nn.Parameter(0.0*torch.ones(self.num_inplayer_neurons)) 44 | # self/recurrent connections within input layer 45 | self.inplayerself = nn.Linear(self.num_inplayer_neurons, self.num_inplayer_neurons, bias=False) 46 | 47 | # Output layer receives inputs from inplayer and recurrent inputs 48 | self.outplayer = nn.Linear(self.num_inplayer_neurons, self.num_outplayer_neurons, bias=True) 49 | self.outplayer.bias = torch.nn.Parameter(0.0*torch.ones(self.num_outplayer_neurons)) 50 | # self/recurrent connections within output layer 51 | self.outplayerself = nn.Linear(self.num_outplayer_neurons, self.num_outplayer_neurons, bias=False) 52 | 53 | # Muscle inputs are computed as summed contributions from outputlayer neurons 54 | self.musclelayer = nn.Linear(self.num_outplayer_neurons, self.num_muscles, bias=False) 55 | 56 | # Activation functions for neurons are Tanh() 57 | self.inplayer_act = nn.Tanh() # activation function of layer neurons 58 | self.outplayer_act = nn.Tanh() # activation of layer neurons 59 | 60 | # Muscles only produce pull-force, hence use a ReLU activation function 61 | self.musclelayer_act = nn.ReLU() 62 | 63 | 64 | # initialize state information variables (joints and arm coordinates) 65 | self.joint_state = torch.zeros(self.num_torque_combinations, 4).to(device) 66 | self.cart_state = torch.zeros(self.num_torque_combinations, 4).to(device) 67 | self.joint_state[:, 0] = self.home_joint_state[:,0].to(device) # initial shoulder angle 68 | self.joint_state[:, 1] = self.home_joint_state[:,1].to(device) # initial elbow angle 69 | self.cart_state = self.arm_dynamics.armkin(self.joint_state) 70 | self.home_cart_state = self.cart_state 71 | self.home_joint_state = self.joint_state 72 | 73 | # set the containers for collecting simulation data 74 | self.collector_networkinputs = torch.empty(0, dtype=torch.float).to(device) 75 | self.collector_inplayeractivity = torch.empty(0, dtype=torch.float).to(device) 76 | self.collector_outplayeractivity = torch.empty(0, dtype=torch.float).to(device) 77 | self.collector_muscleactivity = torch.empty(0, dtype=torch.float).to(device) 78 | self.collector_jointstate = torch.empty(0, dtype=torch.float).to(device) 79 | self.collector_cartesianstate = torch.empty(0, dtype=torch.float).to(device) 80 | self.collector_jointtorques = torch.empty(0, dtype=torch.float).to(device) 81 | 82 | def forward(self, des_targ, perturb_seq): 83 | tau_h = 0.5 # neuronal discretized leak (time constant, tau=20ms, dt/tau = 0.01/0.02 = 0.5) 84 | tau_m = 0.2 # muscle activation discretized leak (time constant, tau=50ms, dt/tau = 0.01/0.05 = 0.2) 85 | 86 | # initialize the network inputs and neuronal states 87 | des_pos = 0*des_targ[0, :, :] 88 | joint_pos_fb = (self.joint_state[:, 0:2] - self.home_joint_state[:, 0:2])*0 89 | joint_vel_fb = self.joint_state[:, 2:4]*0 90 | muscle_fb = torch.zeros(self.num_torque_combinations, 6).to(device) 91 | network_inputs = torch.cat((des_pos.to(device), joint_pos_fb.to(device), 0.5*joint_vel_fb.to(device), muscle_fb.to(device)), 1) 92 | 93 | inplayer_outputs = self.inplayer(network_inputs) 94 | inplayer_outputs = self.inplayer_act(inplayer_outputs) 95 | 96 | outplayer_outputs = self.outplayer(inplayer_outputs) #+ self.init_m1_spontaneous 97 | outplayer_outputs = self.outplayer_act(outplayer_outputs) 98 | 99 | musclelayer_outputs = self.musclelayer(outplayer_outputs) 100 | musclelayer_outputs = self.musclelayer_act(musclelayer_outputs) 101 | torque_command = 0*self.joint_state[:, 2:4] 102 | 103 | # collect the initial states into the simulation-containers 104 | self.collector_networkinputs = torch.cat((self.collector_networkinputs, network_inputs.unsqueeze(0)),0) 105 | self.collector_inplayeractivity=torch.cat((self.collector_inplayeractivity, inplayer_outputs.unsqueeze(0)),0) 106 | self.collector_outplayeractivity=torch.cat((self.collector_outplayeractivity, outplayer_outputs.unsqueeze(0)),0) 107 | self.collector_muscleactivity=torch.cat((self.collector_muscleactivity, musclelayer_outputs.unsqueeze(0)),0) 108 | self.collector_jointstate = torch.cat((self.collector_jointstate, self.joint_state.unsqueeze(0)), 0) 109 | self.collector_cartesianstate = torch.cat((self.collector_cartesianstate, self.cartesian_state.unsqueeze(0)), 0) 110 | self.collector_jointtorques = torch.cat((self.collector_jointtorques, torque_command.unsqueeze(0)),0) 111 | 112 | # start control simulation over time - BODY of the code 113 | # des_targ.size(0) gives the value of time duration 'T' 114 | for i in range(des_targ.size(0)-1): 115 | # goal pos input 116 | des_pos = 0*des_targ[i+1, :, :] 117 | # feedback signals - pos and vel feedback joint coordinates 118 | if i >= 5: # to accomodate sensory processing delays 5 time-steps = 50ms 119 | jpos_fb = (self.collector_jointstate[i-5, :, 0:2]- self.home_joint_state[:, 0:2]) 120 | jvel_fb = self.collector_jointstate[i-5, :, 2:4] 121 | mus_fb = self.collector_muscleactivity[i-5, :, :] 122 | 123 | if i < 5: 124 | jpos_fb = (self.collector_jointstate[0, :, 0:2] - self.home_joint_state[:, 0:2]) 125 | jvel_fb = self.collector_jointstate[0, :, 2:4] 126 | mus_fb = self.collector_muscleactivity[0, :, :] 127 | 128 | # extract perturbation(at time instance 'i') from the perturbation sequence 129 | cur_perturbation = perturb_seq[i, :, :] 130 | 131 | # total controller inputs 132 | # can either use conditioned inputs (soft-normalized) within the range of joint motion 133 | # (useful in fast training of NOREC network) 134 | network_inputs = torch.cat((des_pos, 2*jpos_fb, 0.5*jvel_fb, mus_fb), 1) # [2, 0.5] is not strictly necessary for REC network, can also se [1,1] 135 | # or use raw sensory data from the muscular arm from next line 136 | # network_inputs = torch.cat((des_pos, jpos_fb, jvel_fb, mus_fb), 1) # if this line used for NOREC network instead of 134, the optimization takes very long time 137 | 138 | # activate the network layers with network_inputs 139 | prev_inplayer_outputs = inplayer_outputs 140 | prev_outplayer_outputs = outplayer_outputs 141 | prev_musclelayer_outputs = musclelayer_outputs 142 | 143 | if self.rec_connection_status == 'True': 144 | # dynamical leaky-integrator units 145 | inplayer_outputs = self.inplayer(network_inputs) + self.inplayerself(prev_inplayer_outputs) #+ self.init_filt_spontaneous 146 | inplayer_outputs = tau_h * self.inplayer_act(inplayer_outputs) + (1 - tau_h) * prev_inplayer_outputs 147 | inplayer_outputs += (self.noise_neural.sample([self.num_torque_combinations, self.num_inplayer_neurons]).to(device)* prev_inplayer_outputs*prev_inplayer_outputs).to(device) 148 | 149 | outplayer_outputs = self.outplayer(inplayer_outputs) + self.outplayerself(prev_outplayer_outputs) 150 | outplayer_outputs = tau_h * self.outplayer_act(outplayer_outputs) + (1 - tau_h) * prev_outplayer_outputs 151 | outplayer_outputs += (self.noise_neural.sample([self.num_torque_combinations, self.num_outplayer_neurons]).to(device)* prev_outplayer_outputs*prev_outplayer_outputs).to(device) 152 | else: 153 | inplayer_outputs = self.inplayer(network_inputs) + 0*self.inplayerself(prev_inplayer_outputs) #+ self.init_filt_spontaneous 154 | inplayer_outputs = tau_h * self.inplayer_act(inplayer_outputs) + (1 - tau_h) * prev_inplayer_outputs 155 | inplayer_outputs += (self.noise_neural.sample([self.num_torque_combinations, self.num_inplayer_neurons]).to(device)* prev_inplayer_outputs*prev_inplayer_outputs).to(device) 156 | 157 | outplayer_outputs = self.outplayer(inplayer_outputs) + 0*self.outplayerself(prev_outplayer_outputs) 158 | outplayer_outputs = tau_h * self.outplayer_act(outplayer_outputs) + (1 - tau_h) * prev_outplayer_outputs 159 | outplayer_outputs += (self.noise_neural.sample([self.num_torque_combinations, self.num_outplayer_neurons]).to(device)* prev_outplayer_outputs*prev_outplayer_outputs).to(device) 160 | 161 | # muscle outputs 162 | musclelayer_outputs = self.musclelayer(outplayer_outputs) 163 | musclelayer_outputs = tau_m * self.musclelayer_act(musclelayer_outputs) + (1 - tau_m) * prev_musclelayer_outputs 164 | musclelayer_outputs += (self.noise_muscle.sample([self.num_torque_combinations, self.num_muscles]).to(device)* prev_musclelayer_outputs*prev_musclelayer_outputs).to(device) 165 | 166 | # send muscle commands to the plant and get joint information 167 | self.joint_state, torque_output, mus_flv = self.arm_dynamics.forward(self.joint_state, musclelayer_outputs, cur_perturbation) 168 | 169 | # perform forward kinematic transformation to get arm state 170 | self.cartesian_state = self.arm_dynamics.armkin(self.joint_state) 171 | 172 | # append the current time simulation data to simulation collector variables 173 | self.collector_networkinputs = torch.cat((self.collector_networkinputs, network_inputs.unsqueeze(0)),0) 174 | self.collector_inplayeractivity=torch.cat((self.collector_inplayeractivity, inplayer_outputs.unsqueeze(0)),0) 175 | self.collector_outplayeractivity=torch.cat((self.collector_outplayeractivity, outplayer_outputs.unsqueeze(0)),0) 176 | self.collector_muscleactivity=torch.cat((self.collector_muscleactivity, musclelayer_outputs.unsqueeze(0)),0) 177 | self.collector_jointstate = torch.cat((self.collector_jointstate, self.joint_state.unsqueeze(0)), 0) 178 | self.collector_cartesianstate = torch.cat((self.collector_cartesianstate, self.cartesian_state.unsqueeze(0)), 0) 179 | self.collector_jointtorques = torch.cat((self.collector_jointtorques, torque_command.unsqueeze(0)),0) 180 | return self.collector_jointstate 181 | 182 | def resetsim(self): 183 | # state information (joints and arm coordinates) 184 | self.joint_state = torch.zeros(self.num_torque_combinations, 4).to(device) 185 | self.cartesian_state = torch.zeros(self.num_torque_combinations, 4).to(device) 186 | self.joint_state[:, 0] = self.home_joint_state[:,0] # initial shoulder angle 187 | self.joint_state[:, 1] = self.home_joint_state[:,1] # initial elbow angle 188 | self.cartesian_state = self.arm_dynamics.armkin(self.joint_state) 189 | self.home_cartesian_state = self.cartesian_state 190 | 191 | # re-set the simulation-containers for collecting simulation data 192 | self.collector_networkinputs = torch.empty(0, dtype=torch.float).to(device) 193 | self.collector_inplayeractivity = torch.empty(0, dtype=torch.float).to(device) 194 | self.collector_outplayeractivity = torch.empty(0, dtype=torch.float).to(device) 195 | self.collector_muscleactivity = torch.empty(0, dtype=torch.float).to(device) 196 | self.collector_jointstate = torch.empty(0, dtype=torch.float).to(device) 197 | self.collector_cartesianstate = torch.empty(0, dtype=torch.float).to(device) 198 | self.collector_jointtorques = torch.empty(0, dtype=torch.float).to(device) 199 | 200 | 201 | def costcriterionPosture(posture_sim, des_pos, actual_pos, actual_vel): 202 | num_torque_combinations = actual_pos.size(1) 203 | num_time = actual_pos.size(0) 204 | # to penalize displacements before the torque application (1 second) 205 | x_t1 = actual_pos[:100, :] 206 | xd_t1 = des_pos[:100, :] 207 | # to penalize arm not returbing within 1 second 208 | x_t2 = actual_pos[200:, :] 209 | xd_t2 = des_pos[200:, :] 210 | loss = (0.5 /(num_time-200))*torch.norm((x_t1 - xd_t1))**2 # displacement penalty pre-perturbation 211 | loss += (0.5 /(num_time-200))*torch.norm((x_t2 - xd_t2))**2 # displacement penalty post 1000ms after perturbation 212 | loss += (0.5 * 0.5/(num_time-200))*torch.norm(actual_vel[:100, :])**2 # velocity penalty pre-perturbation 213 | loss += (0.5 * 0.5/(num_time-200))*torch.norm(actual_vel[200:, :])**2 # velocity penalty post 1000ms after perturbation 214 | # penalize muscle and neural activities 215 | # (the penalty coefficients are example among a wide-range of plausible quantities that yield similar results) 216 | loss += (1.0e-2/(num_time-200))*(torch.norm(posture_sim.collector_muscleactivity[:100,:,:])**2) # penalty on high muscle activities before movement/perturbation 217 | loss += (1.0e-5/(num_time-200))*(torch.norm(posture_sim.collector_muscleactivity[100:200,:,:])**2) # penalty on high muscle activities during movement/perturbation 218 | loss += (1.0e-5/(num_time))*(torch.norm(posture_sim.collector_inplayeractivity[:,:,:])**2) # penalty on high neural activities 219 | loss += (1.0e-5/(num_time))*(torch.norm(posture_sim.collector_outplayeractivity[:,:,:])**2) # penalty on high neural activities 220 | return (0.1/0.05)*loss/num_torque_combinations 221 | -------------------------------------------------------------------------------- /reach task/NetworkClass.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import numpy as np 4 | from muscularArmClass import muscular_arm 5 | from torch.distributions import normal 6 | 7 | '''Modifications from the manuscript simulation settings for reach task: 8 | To enable relatively faster optimization, time durations have been reduced 9 | from the original article. In the article the hold_cue/GO_signal (that indicates the arm 10 | should stay at home even when target appears on screen) turns off at 800ms (80 time-steps), 11 | and total simulation runs for 300 time-steps. In this simulation, hold-cue does not 12 | exist. The simulated arm should start moving towards the target as soon as it is 13 | presented. Hence only step-targets signal is simulated here. ''' 14 | 15 | use_cuda = torch.cuda.is_available() 16 | device = torch.device('cuda:0' if use_cuda else 'cpu') 17 | device = 'cpu' 18 | 19 | class feedback_controller(nn.Module): 20 | def __init__(self, dh, home_joint_state): 21 | super(feedback_controller, self).__init__() 22 | # fixed control parameters 23 | self.dh = dh # sim-step 24 | self.num_network_inputs = 12 25 | self.num_inplayer_neurons = 500 26 | self.num_outplayer_neurons = 500 27 | self.num_muscles = 6 28 | self.num_reach_combinations = 17 29 | self.fb_delay = 5 30 | self.num_network_layers = 2 31 | self.rec_conn = 'True' 32 | 33 | self.home_joint_state = home_joint_state 34 | 35 | 36 | # Motor noise 37 | self.noise_neural = normal.Normal(0.0, 0.005) 38 | self.noise_muscle = normal.Normal(0.0, 0.005) 39 | 40 | 41 | # Intantiate the biomechanical arm dynamics at home location 42 | self.adyn = muscular_arm(dh) 43 | 44 | # Create neural network by means of torch functions 45 | # network config: 46 | # 1. inplayer 47 | # 2. outplayer 48 | # 3. muscle layer 49 | 50 | 51 | # Input layer receives sensory input + recurrent connections 52 | self.inplayer = nn.Linear(self.num_network_inputs, self.num_inplayer_neurons, bias=True) 53 | self.inplayer.bias = torch.nn.Parameter(torch.zeros(self.num_inplayer_neurons)) 54 | #self.inplayer.weight = torch.nn.Parameter(nn.init.normal_(torch.empty(num_inplayer_neurons, num_network_inputs)) * self.g**2) 55 | self.inplayerself = nn.Linear(self.num_inplayer_neurons, self.num_inplayer_neurons, bias=True) 56 | self.inplayerself.bias = torch.nn.Parameter(torch.zeros(self.num_inplayer_neurons)) 57 | 58 | # Output layer receives inputs from inplayer and recurrent inputs 59 | self.outplayer = nn.Linear(self.num_inplayer_neurons, self.num_outplayer_neurons, bias=True) 60 | self.outplayer.bias = torch.nn.Parameter(torch.zeros(self.num_outplayer_neurons)) 61 | #self.outplayer.weight = torch.nn.Parameter(nn.init.normal_(torch.empty(num_outplayer_neurons, self.num_inplayer_neurons)) * self.g**2) 62 | self.outplayerself = nn.Linear(self.num_outplayer_neurons, self.num_outplayer_neurons, bias=True) 63 | self.outplayerself.bias = torch.nn.Parameter(torch.zeros(self.num_outplayer_neurons)) 64 | #self.outplayerself.weight = torch.nn.Parameter(nn.init.normal_(torch.empty(num_outplayer_neurons, num_outplayer_neurons)) * self.g**2) 65 | 66 | # Muscle inputs are computed as summed contributions from outputlayer neurons 67 | self.musclelayer = nn.Linear(self.num_outplayer_neurons, self.num_muscles, bias=False) 68 | 69 | # Activation function for each network layer 70 | #self.musclelayer.weight = torch.nn.Parameter(nn.init.normal_(torch.empty(num_muscles, num_outplayer_neurons)) * self.g**2) 71 | self.inplayer_act = nn.Tanh() # activation function of layer neurons 72 | self.outplayer_act = nn.Tanh() # activation of layer neurons 73 | self.musclelayer_act = nn.ReLU() # muscle activation function only pull 74 | #self.musclelayer_act = nn.Tanh() # muscle activation function push-pull 75 | 76 | # initialize state information variables (joints and arm coordinates) 77 | self.joint_state = torch.zeros(self.num_reach_combinations, 4).to(device) 78 | self.cart_state = torch.zeros(self.num_reach_combinations, 4).to(device) 79 | self.joint_state[:, 0] = home_joint_state[0,0] # initial shoulder angle 80 | self.joint_state[:, 1] = home_joint_state[0,1] # initial elbow angle 81 | self.cart_state = self.adyn.armkin(self.joint_state) 82 | self.home_cart_state = self.cart_state 83 | self.home_joint_state = self.joint_state 84 | 85 | # set the containers for collecting simulation data 86 | self.collector_networkinputs = torch.empty(0, dtype=torch.float) 87 | self.collector_inplayeractivity = torch.empty(0, dtype=torch.float) 88 | self.collector_outplayeractivity = torch.empty(0, dtype=torch.float) 89 | self.collector_muscleactivity = torch.empty(0, dtype=torch.float) 90 | self.collector_jointstate = torch.empty(0, dtype=torch.float) 91 | self.collector_cartesianstate = torch.empty(0, dtype=torch.float) 92 | self.hold_data = torch.empty(0, dtype=torch.float) 93 | 94 | def forward(self, des_targ, variable_movinit_delay): 95 | tau_h = 0.5 # neuronal discretized leak (time constant, tau=20ms, dt/tau = 0.01/0.02 = 0.5) 96 | tau_m = 0.2 # muscle activation discretized leak (time constant, tau=50ms, dt/tau = 0.01/0.05 = 0.2) 97 | 98 | # initialize the network inputs and neuronal states 99 | des_pos = (des_targ[0, :, :] - self.home_joint_state[:, 0:2]) 100 | joint_pos_fb = (self.joint_state[:, 0:2] - des_targ[0, :, :]) 101 | joint_vel_fb = self.joint_state[:, 2:4] / 2 # usually joint-vel in the range of 0.6 rad/sec 102 | muscle_fb = torch.zeros(17, 6).to(device) 103 | network_inputs = torch.cat((des_pos, joint_pos_fb, joint_vel_fb, muscle_fb), 1) 104 | #network_inputs = torch.cat((hold_cmd, des_pos, joint_pos_fb, joint_vel_fb), 1) 105 | 106 | inplayer_outputs = self.inplayer(network_inputs) 107 | inplayer_outputs = tau_h*self.inplayer_act(inplayer_outputs) 108 | #inplayer_outputs = torch.clamp(inplayer_outputs, min=-0.0, max=0.5) 109 | outplayer_outputs = self.outplayer(inplayer_outputs) 110 | outplayer_outputs = tau_h*self.outplayer_act(outplayer_outputs) 111 | 112 | #outplayer_outputs = torch.clamp(outplayer_outputs, min=-0.0, max=0.5) 113 | musclelayer_outputs = self.musclelayer(outplayer_outputs) 114 | musclelayer_outputs = tau_m * self.musclelayer_act(musclelayer_outputs) 115 | 116 | 117 | # collect the initial states into the simulation-containers 118 | self.collector_networkinputs = torch.cat((self.collector_networkinputs,network_inputs.unsqueeze(0)),0) 119 | self.collector_inplayeractivity=torch.cat((self.collector_inplayeractivity,inplayer_outputs.unsqueeze(0)),0) 120 | self.collector_outplayeractivity=torch.cat((self.collector_outplayeractivity,outplayer_outputs.unsqueeze(0)),0) 121 | self.collector_muscleactivity=torch.cat((self.collector_muscleactivity,musclelayer_outputs.unsqueeze(0)),0) 122 | self.collector_jointstate = torch.cat((self.collector_jointstate,self.joint_state.unsqueeze(0)), 0) 123 | self.collector_cartesianstate = torch.cat((self.collector_cartesianstate,self.cart_state.unsqueeze(0)), 0) 124 | 125 | # start control simulation over time - BODY of the code 126 | # des_targ.size(0) gives the value of time duration 'T' 127 | for i in range(des_targ.size(0) - 1): 128 | 129 | if i > self.fb_delay and i <= 30: 130 | des_pos = 0*(des_targ[0, :, :] - self.home_joint_state[:, 0:2]) 131 | joint_pos_fb = (self.collector_jointstate[i - self.fb_delay, :, 0:2] - des_targ[0, :, :]) 132 | # or can use pure displacement information from home_location as pos_fb 133 | #joint_pos_fb = (self.collector_jointstate[i - self.fb_delay, :, 0:2] - self.home_joint_state[:, 0:2]) 134 | joint_vel_fb = self.collector_jointstate[i - self.fb_delay, :, 2:4]/2 135 | muscle_fb = self.collector_muscleactivity[i - self.fb_delay, :, :] 136 | 137 | if i > 30: 138 | des_pos = (des_targ[50, :, :] - self.home_joint_state[:, 0:2]) 139 | joint_pos_fb = (self.collector_jointstate[i - self.fb_delay, :, 0:2] - des_targ[0, :, :]) 140 | # or can use pure displacement information from home_location as pos_fb 141 | #joint_pos_fb = (self.collector_jointstate[i - self.fb_delay, :, 0:2] - self.home_joint_state[:, 0:2]) 142 | joint_vel_fb = self.collector_jointstate[i-self.fb_delay, :, 2:4]/2 143 | muscle_fb = self.collector_muscleactivity[i-self.fb_delay, :, :] 144 | 145 | if i < self.fb_delay: 146 | des_pos = (des_targ[0, :, :] - self.home_joint_state[:, 0:2]) 147 | joint_pos_fb = (self.collector_jointstate[0, :, 0:2] - des_targ[0, :, :]) 148 | # or can use pure displacement information from home_location as pos_fb 149 | #joint_pos_fb = (self.collector_jointstate[0, :, 0:2] - self.home_joint_state[:, 0:2]) 150 | joint_vel_fb = self.collector_jointstate[0, :, 2:4]/2 151 | muscle_fb = self.collector_muscleactivity[0, :, :] 152 | 153 | 154 | # total controller inputs 155 | network_inputs = torch.cat((des_pos, joint_pos_fb, joint_vel_fb, muscle_fb), 1) 156 | 157 | #network_inputs = torch.cat((hold_cmd, des_pos, joint_pos_fb, joint_vel_fb), 1) 158 | 159 | # activate the network layers with network_inputs 160 | prev_inplayer_outputs = inplayer_outputs 161 | prev_outplayer_outputs = outplayer_outputs 162 | prev_musclelayer_outputs = musclelayer_outputs 163 | 164 | if self.num_network_layers == 1: 165 | 166 | # dynamical leaky-integrator units 167 | if self.rec_conn == 'True': 168 | inplayer_outputs = self.inplayer(network_inputs) + self.inplayerself(prev_inplayer_outputs) 169 | if self.rec_conn == 'False': 170 | inplayer_outputs = self.inplayer(network_inputs) 171 | inplayer_outputs = tau_h * self.inplayer_act(inplayer_outputs) + (1 - tau_h) * prev_inplayer_outputs 172 | inplayer_outputs += self.noise_neural.sample([self.num_reach_combinations, self.num_inplayer_neurons]).to(device) * prev_inplayer_outputs*prev_inplayer_outputs 173 | 174 | # muscle outputs 175 | musclelayer_outputs = self.musclelayer(inplayer_outputs) 176 | musclelayer_outputs = tau_m * self.musclelayer_act(musclelayer_outputs) + (1 - tau_m) * prev_musclelayer_outputs 177 | musclelayer_outputs += (self.noise_muscle.sample([self.num_reach_combinations, self.num_muscles]).to(device)* prev_musclelayer_outputs*prev_musclelayer_outputs).to(device) 178 | 179 | if self.num_network_layers == 2: 180 | # dynamical leaky-integrator units 181 | if self.rec_conn == 'True': 182 | inplayer_outputs = self.inplayer(network_inputs) + self.inplayerself(prev_inplayer_outputs) 183 | if self.rec_conn == 'False': 184 | inplayer_outputs = self.inplayer(network_inputs) 185 | inplayer_outputs = tau_h * self.inplayer_act(inplayer_outputs) + (1 - tau_h) * prev_inplayer_outputs 186 | inplayer_outputs += self.noise_neural.sample([self.num_reach_combinations, self.num_inplayer_neurons]).to(device) * prev_inplayer_outputs*prev_inplayer_outputs 187 | 188 | if self.rec_conn == 'True': 189 | outplayer_outputs = self.outplayer(inplayer_outputs) + self.outplayerself(prev_outplayer_outputs) 190 | if self.rec_conn == 'False': 191 | outplayer_outputs = self.outplayer(inplayer_outputs) 192 | outplayer_outputs = tau_h * self.outplayer_act(outplayer_outputs) + (1 - tau_h) * prev_outplayer_outputs 193 | outplayer_outputs += (self.noise_neural.sample([self.num_reach_combinations, self.num_outplayer_neurons]).to(device)* prev_outplayer_outputs*prev_outplayer_outputs).to(device) 194 | 195 | # muscle outputs 196 | musclelayer_outputs = self.musclelayer(outplayer_outputs) 197 | musclelayer_outputs = tau_m * self.musclelayer_act(musclelayer_outputs) + (1 - tau_m) * prev_musclelayer_outputs 198 | musclelayer_outputs += (self.noise_muscle.sample([self.num_reach_combinations, self.num_muscles]).to(device)* prev_musclelayer_outputs*prev_musclelayer_outputs).to(device) 199 | 200 | # send muscle commands to the plant and get joint information 201 | self.joint_state, torque_output, mus_flv = self.adyn.forward(self.joint_state, musclelayer_outputs) 202 | 203 | # perform forward kinematic transformation to get arm state 204 | self.cart_state = self.adyn.armkin(self.joint_state) 205 | 206 | # append the current time simulation data to simulation collector variables 207 | self.collector_networkinputs = torch.cat((self.collector_networkinputs,network_inputs.unsqueeze(0)),0) 208 | self.collector_inplayeractivity = torch.cat((self.collector_inplayeractivity,inplayer_outputs.unsqueeze(0)),0) 209 | self.collector_outplayeractivity = torch.cat((self.collector_outplayeractivity,outplayer_outputs.unsqueeze(0)),0) 210 | self.collector_muscleactivity = torch.cat((self.collector_muscleactivity,musclelayer_outputs.unsqueeze(0)),0) 211 | self.collector_jointstate = torch.cat((self.collector_jointstate,self.joint_state.unsqueeze(0)),0) 212 | self.collector_cartesianstate = torch.cat((self.collector_cartesianstate,self.cart_state.unsqueeze(0)),0) 213 | return self.collector_jointstate 214 | 215 | def gaussianSmooth(self, t, variable_movinit_delay): # useful for generating a smooth-delayed 'GO' signal (not used in this code) 216 | sig = 2.5 217 | cur_val = (10/4) * 1/(np.sqrt(2*3.14)) * np.exp(-(t - variable_movinit_delay)**2/(2*(sig)**2)) 218 | return cur_val 219 | 220 | def resetsim(self): 221 | # state information (joints and arm coordinates) 222 | self.joint_state = torch.zeros(self.num_reach_combinations, 4).to(device) 223 | self.cart_state = torch.zeros(self.num_reach_combinations, 4).to(device) 224 | self.joint_state[:, 0] = self.home_joint_state[0,0] # initial shoulder angle 225 | self.joint_state[:, 1] = self.home_joint_state[0,1] # initial elbow angle 226 | self.cart_state = self.adyn.armkin(self.joint_state) 227 | self.home_cart_state = self.cart_state 228 | 229 | # re-set the simulation-containers for collecting simulation data 230 | self.collector_networkinputs = torch.empty(0, dtype=torch.float).to(device) 231 | self.collector_inplayeractivity = torch.empty(0, dtype=torch.float).to(device) 232 | self.collector_outplayeractivity = torch.empty(0, dtype=torch.float).to(device) 233 | self.collector_muscleactivity = torch.empty(0, dtype=torch.float).to(device) 234 | self.collector_jointstate = torch.empty(0, dtype=torch.float).to(device) 235 | self.collector_cartesianstate = torch.empty(0, dtype=torch.float).to(device) 236 | 237 | 238 | def costCriterionReaching(reach_sim, actual_pos, des_pos, actual_vel, variable_movinit_delay): 239 | # fast reaches T=75 end duration 240 | # slow reaches T=110 end duration 241 | # Normal reaches T=80 end duration 242 | num_reach_combinations = actual_pos.size(1) 243 | num_time = actual_pos.size(0) 244 | # extract the actual and desired position from 500ms after the movement initiation 245 | # (in this case from penalize the displacement error from T=80time-steps) 246 | x_fT = actual_pos[80:, :] 247 | xd_fT = des_pos[80:, :] 248 | #loss = (0.05/num_time)*torch.norm((x_T - xd_T))**2 # instantaneous penalization 249 | loss = (0.5/50)*torch.norm((x_fT - xd_fT))**2 250 | # penalize for non-zero velocity 500ms after movement initiation 251 | loss += (0.5/50)*torch.norm(actual_vel[80:, :])**2 252 | # penalize for non-zero velocity before the movement 'cue' is presented 253 | loss += (0.5/variable_movinit_delay)*torch.norm(actual_vel[:variable_movinit_delay, :])**2 254 | 255 | # penalize high muscle and neural activities 256 | loss += (1.0e-2/num_time)*(torch.norm(reach_sim.collector_muscleactivity[:variable_movinit_delay,:,:]))**2 257 | loss += (1.0e-4/num_time)*(torch.norm(reach_sim.collector_muscleactivity[variable_movinit_delay:,:,:]))**2 258 | loss += (1.0e-5/num_time)*(torch.norm(reach_sim.collector_outplayeractivity[:,:,:]))**2 259 | loss += (1.0e-5/num_time)*(torch.norm(reach_sim.collector_inplayeractivity[:,:,:]))**2 260 | #print(loss) 261 | # smoothness dynamics regularizer 262 | #loss += (1.0e-4/num_time)*(torch.norm((reach_sim.outplayerself((1 - reach_sim.collector_outplayeractivity[variable_movinit_delay:,:,:]**2))))**2) 263 | return (0.1/0.05)*loss/num_reach_combinations 264 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------