-
Notifications
You must be signed in to change notification settings - Fork 1
/
basic_fns_v12_delay_simplified_nodict.py
1357 lines (1033 loc) · 50.5 KB
/
basic_fns_v12_delay_simplified_nodict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Delay added to joint angle feedback.
from numpy import *
# for using np.sum and np.abs (since standard library has these as well)
import numpy as np
from scipy.linalg import solve
from scipy.integrate import solve_ivp, quad
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import numba
# for making and displaying animation
# from celluloid import Camera
from IPython.display import HTML
from sklearn.neighbors import KDTree
from datetime import datetime
from dask.distributed import Client, worker_client, as_completed, progress
from dask.dataframe import from_delayed
from dask_jobqueue import SLURMCluster
# from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import time
import os
import pickle
import sys
SCALE_OBJ_FN = True # Scales objective fn by reach length squared
# q = q1,q2,dq1,dq2 (dq1 = d/dt q1)
@numba.jit(nopython=True)
def make_M_inv(q, params):
# params is an instance of the parameters class
# M2 is the mass matrix M in block diagonal with the identity
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
c2 = cos(q[1])
M = array([[mA * (rhoA ** 2) + mB * (LA ** 2) + 2 * mB * LA * rhoB * c2 + mB * (rhoB ** 2) + IA + IB,
mB * LA * rhoB * c2 + mB * (rhoB ** 2) + IB],
[c2 * mB * rhoB * LA + (rhoB ** 2) * mB + IB, (rhoB ** 2) * mB + IB]])
M_inv = (1.0 / (M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0])) * array([[M[1, 1], -M[0, 1]], [-M[1, 0], M[0, 0]]])
return M_inv
@numba.jit(nopython=True)
def get_muscle_moment_arrays():
# torque muscle 1 exerts on each body (moment arm * unit torque vector)
# Unlike 3D case we just do everything in N_hat ref frame here bc the
# a3_hat, b3_hat, and n3_hat vectors are always aligned
m1A = 0.02 * array([0., 0., 1.])
m1B = array([0., 0., 0.])
# muscle 2
m2A = 0.02 * array([0., 0., -1.])
m2B = array([0., 0., 0.])
# muscle 3
m3B = 0.02 * array([0., 0., 1.])
m3A = -m3B
# muscle 4
m4B = 0.02 * array([0., 0., -1.])
m4A = -m4B
# muscle 5 (bijoint flexor: shoulder in + elbow flex)
m5A = 0.01 * array([0., 0., 1.])
m5B = 0.01 * array([0., 0., 1.])
# muscle 6 (bijoint extensor)
m6A = 0.01 * array([0., 0., -1.])
m6B = 0.01 * array([0., 0., -1.])
moment_arrayA = column_stack((m1A, m2A, m3A, m4A, m5A, m6A))
moment_arrayB = column_stack((m1B, m2B, m3B, m4B, m5B, m6B))
return moment_arrayA, moment_arrayB
@numba.jit(nopython=True)
def calc_torques(muscle_act, q, params):
# returns tauA and tauB
# muscle_act is vector of muscle activations
moment_arrayA, moment_arrayB = get_muscle_moment_arrays()
max_muscle_force = diag(array([params[9], params[10],
params[11], params[12],
params[20], params[21]]))
tauA_c, tauB_c = calc_constraint_moments(q, params)
# The constraint torque on B produces an equal neg torque on A. The constraint torque on A at the shoulder
# tauA_c, produces an equal neg torque on N, which we ignore since N is fixed
tauA = dot(moment_arrayA, dot(max_muscle_force, muscle_act)) + tauA_c - tauB_c # neg torque due to constraint!
tauB = dot(moment_arrayB, dot(max_muscle_force, muscle_act)) + tauB_c
return tauA, tauB
@numba.jit(nopython=True)
def calc_constraint_moments(q, params):
theta1_q1 = -pi / 4
theta2_q1 = 3*pi / 4
tauA_c = array([0, 0, 0.1 * exp(-5 * (q[0] - theta1_q1)) - 0.1 * exp(-5 * (theta2_q1 - q[0])) - 0.05 * q[2]])
theta1_q2 = 0.0
theta2_q2 = 3 * pi / 4
tauB_c = array([0, 0, 0.1 * exp(-5 * (q[1] - theta1_q2)) - 0.1 * exp(-5 * (theta2_q2 - q[1])) - 0.05 * q[3]])
return tauA_c, tauB_c
@numba.jit(nopython=True)
def make_rhs_arm(t, q, m, ext_force, params):
# m is a vector of muscle activations, not a fn
q1, q2, dq1, dq2 = q
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
c1 = cos(q1)
c2 = cos(q2)
s1 = sin(q1)
s2 = sin(q2)
f1, f2 = ext_force # external force
tauA, tauB = calc_torques(m, q, params)
F1 = -rhoA * mA * g * c1 + -mB * g * LA * c1 - mB * g * rhoB * (-s1 * s2 + c1 * c2) + \
f1 * (-LA * s1 + LB * (-c1 * s2 - s1 * c2)) + f2 * (LA * c1 + LB * (-s1 * s2 + c1 * c2)) + \
dot(tauA, array([0, 0, 1.0])) + dot(tauB, array([0, 0, 1.0]))
F2 = -rhoB * (-s1 * s2 + c1 * c2) * mB * g + f1 * LB * (-c1 * s2 - s1 * c2) + f2 * LB * (-s1 * s2 + c1 * c2) + \
dot(tauB, array([0, 0, 1.0]))
velocity_terms = array([mB * LA * rhoB * ((dq1 + dq2) ** 2) * s2 - mB * rhoB * LA * (dq1 ** 2) * s2,
-s2 * rhoB * mB * LA * (dq1 ** 2)])
M_inv = make_M_inv(q, params)
temp_rhs = array([F1 + velocity_terms[0], F2 + velocity_terms[1]]) # rhs before inverting the mass matrix
rhs = hstack((array([dq1, dq2]), dot(M_inv, temp_rhs)))
return rhs
@numba.jit(nopython=True)
def make_rhs_muscles(t, m, x, D0, D1, params):
rhs = (1.0 / params[13]) * (-m + sigma(D0 + dot(D1, x)))
return rhs
@numba.jit(nopython=True)
def make_rhs_brain(t, x, u1, u2, u3, u4, v1, v3, v4, A, B0, B1, B2, B3, B4, C1, C3, C4, params):
# x: "firing rate" of neurons
# p: parameters for A, B1, B2, B3, C as a vector [pA, pB1, pB2, pB3, pC]
# u1: vector giving the target position at time t (u1 evaluated at time t)
# u2: vector giving start position for current reach
# v1, v2, v3: vector of feedback information (v1, v2 evaluated at q) (v1 = pos hand, v2 = vel hand)
rhs = (dot(A, x) + B0 + dot(B1, u1) + dot(B2, u2) + dot(B3, u3) + dot(B4, u4)
+ dot(C1, v1) + dot(C3, v3) + dot(C4, v4))
return rhs
@numba.jit(nopython=True)
def make_rhs_forward(t, z, start, target, q_start, q_target,
A, B0, B1, B2, B3, B4, C1, C3, C4, D0, D1, params, dims):
# z is the concatenated variable of x (neuron states), m (muscle activation), and q (arm states)
# u1_fn is a fn of t, giving target position
# v1_fn is a fn of q, giving feedback (i.e. hand position)
x, m, q = z_to_xmq(z, dims)
u1 = u1_fn(t, target)
u2 = u2_fn(t, start)
u3 = u3_fn(t, q_target)
u4 = u4_fn(t, q_start)
ext_force = ext_force_fn(t)
v1 = v1_fn(q, params)
v3 = v3_fn(m)
v4 = v4_fn(q, params)
rhs1 = make_rhs_brain(t, x, u1, u2, u3, u4, v1, v3, v4,
A, B0, B1, B2, B3, B4, C1, C3, C4, params)
rhs2 = make_rhs_muscles(t, m, x, D0, D1, params)
rhs3 = make_rhs_arm(t, q, m, ext_force, params)
rhs_forward = hstack((rhs1, rhs2, rhs3))
return rhs_forward
@numba.jit(nopython=True)
def p_to_matrices_2D(p, dims):
# 2D version of reshape p into matrices A, B0, B1, B2, C1, C3, D0, D1, C2
# start and stop points on p
Ass = (0, dims[6])
B0ss = (Ass[1], Ass[1] + dims[7])
B1ss = (B0ss[1], B0ss[1] + dims[8])
C1ss = (B1ss[1], B1ss[1] + dims[9])
C3ss = (C1ss[1], C1ss[1] + dims[10])
D0ss = (C3ss[1], C3ss[1] + dims[11])
D1ss = (D0ss[1], D0ss[1] + dims[12])
# new stuff at the end
B2ss = (D1ss[1], D1ss[1] + dims[15])
B3ss = (B2ss[1], B2ss[1] + dims[18])
B4ss = (B3ss[1], B3ss[1] + dims[19])
C4ss = (B4ss[1], B4ss[1] + dims[20])
A = reshape(p[Ass[0]:Ass[1]], (dims[0], dims[0])) # reshape fills in row 1, then row 2, etc
B0 = reshape(p[B0ss[0]:B0ss[1]], (dims[0],))
B1 = reshape(p[B1ss[0]:B1ss[1]], (dims[0], dims[2]))
C1 = reshape(p[C1ss[0]:C1ss[1]], (dims[0], dims[3]))
C3 = reshape(p[C3ss[0]:C3ss[1]], (dims[0], dims[4]))
D0 = reshape(p[D0ss[0]:D0ss[1]], (dims[1],))
D1 = reshape(p[D1ss[0]:D1ss[1]], (dims[1], dims[0]))
B2 = reshape(p[B2ss[0]:B2ss[1]], (dims[0], dims[2]))
B3 = reshape(p[B3ss[0]:B3ss[1]], (dims[0], dims[16]))
B4 = reshape(p[B4ss[0]:B4ss[1]], (dims[0], dims[16]))
C4 = reshape(p[C4ss[0]:C4ss[1]], (dims[0], dims[17]))
# have to always return everything, bc a numba fn can't return different numbers of outputs depending on
# the input (i.e. can't have p_to_matrices(p, dims, ('A', 'B')) that returns only A and B.
return A, B0, B1, B2, B3, B4, C1, C3, C4, D0, D1
@numba.jit(nopython=True)
def z_to_xmq(z, dims):
# start stop locations
xss = (0, dims[0])
mss = (xss[1], xss[1] + dims[1])
qss = (mss[1], mss[1] + dims[5])
x = z[xss[0]:xss[1]]
m = z[mss[0]:mss[1]]
q = z[qss[0]:qss[1]]
return x, m, q
@numba.jit(nopython=True)
def pos_a0(q, params):
return array([0., 0, 0])
@numba.jit(nopython=True)
def pos_b0(q, params):
# Gives pos of endpoint of a1 in n_hat coords
q1, q2 = q[0:2]
LA = params[2]
# pos_a0 + LA*a1_hat
a1_hat = array([cos(q1), sin(q1), 0]) # in n_hat coords
pos = pos_a0(q, params) + LA * a1_hat
return pos
@numba.jit(nopython=True)
def pos_c0(q, params):
# Gives pos of endpoint of B in n_hat coords
# q can be either the full q or just q1, q2.
q1, q2 = q[0:2]
LB = params[3]
c1 = cos(q1)
c2 = cos(q2)
s1 = sin(q1)
s2 = sin(q2)
# pos_b0 + LB*b1_hat
b1_hat = array([c1 * c2 - s1 * s2, s1 * c2 + c1 * s2, 0]) # in n_hat coords
pos = pos_b0(q, params) + LB * b1_hat
return pos
@numba.jit(nopython=True)
def vel_c0(q, params):
# velocity of c0 in N
q1, q2, dq1, dq2 = q
LA = params[2]
LB = params[3]
a2hat = array([-sin(q1), cos(q1), 0])
b2hat = array([-sin(q1 + q2), cos(q1 + q2), 0])
vNC0 = (LA * a2hat + LB * b2hat) * dq1 + (LB * b2hat) * dq2
return vNC0
@numba.jit(nopython=True)
def ext_force_fn(t):
return array([0.0, 0.0])
# @numba.jit(nopython=True)
# def sigma(x):
# # x is a vector
# out = 1.0 / (1.0 + exp(-x))
# return out
#
# @numba.jit(nopython=True)
# def dsigma_dx(x):
# # x is a vector
# out = exp(-x)/((1.0 + exp(-x))**2)
# return diag(out)
@numba.jit(nopython=True)
def sigma(x):
# new version that's 0 at -1 and 1 at 1, with 0 derivative at both ends
# x is a vector
x1 = 0.5 * (x + 1.0)
out = -2.0 * (x1 ** 3) + 3.0 * (x1 ** 2)
out[x < -1.0] = 0.0
out[x > 1.0] = 1.0
return out
@numba.jit(nopython=True)
def dsigma_dx(x):
# x is a vector
x1 = 0.5 * (x + 1.0)
out = 0.5 * (-6.0 * (x1 ** 2) + 6.0 * x1)
out[x < -1.0] = 0.0
out[x > 1.0] = 0.0
return diag(out)
@numba.jit(nopython=True)
def u1_fn(t, target):
# constant u1; for each sample, use lambda t: u1(t, target[i]) as u1
# target should be 3D vector, since feedback and everything else is 3D vector
return target
@numba.jit(nopython=True)
def u2_fn(t, start):
# starting position 3D vector
return start
@numba.jit(nopython=True)
def u3_fn(t, q_target):
# q_target is 2D [q1,q2] target
return q_target
@numba.jit(nopython=True)
def u4_fn(t, q_start):
# q_start is 2D [q1,q2] start
return q_start
@numba.jit(nopython=True)
def v1_fn(q, params):
# feedback function 1
# Give position of hand in N_hat coords
q1, q2, dq1, dq2 = q
q_delay = params[23]
delayed_q = array([q1 - dq1*q_delay, q2 - dq2*q_delay])
out = pos_c0(delayed_q, params)
return out
@numba.jit(nopython=True)
def v2_fn(q, params):
# feedback function 2
# Give velocity of hand in N_hat coords
return vel_c0(q, params)
@numba.jit(nopython=True)
def v3_fn(m):
# feedback function 3
# muscle activity
return m
@numba.jit(nopython=True)
def v4_fn(q, params):
# feedback function 4
# hand pos in joint angle coords (q1, q2)
q1, q2, dq1, dq2 = q
q_delay = params[23]
delayed_q = array([q1 - dq1*q_delay, q2 - dq2*q_delay])
return delayed_q
def make_init_cond_list(n_samples, dims):
init_cond_list = []
x0 = zeros(dims[0])
m0 = zeros(dims[1])
for i in range(n_samples):
q1 = (pi * random.rand()) - (pi/4)
q2 = (3 * pi / 4) * random.rand()
dq1 = 0
dq2 = 0
q0 = array([q1, q2, dq1, dq2])
init_cond_list += [hstack((x0, m0, q0))]
return init_cond_list
def is_reachable(x, ex_kdtree):
# determine if x is within arm's reachable area by seeing if x is w/in
# 5 mm of a point in the kdtree
dist, indx = ex_kdtree.query(reshape(x, (1, 3)), k=1, return_distance=True)
dist = dist[0, 0]
indx = indx[0, 0]
if dist < 0.005: # in meters
return True
else:
return False
def allowable_point(x, ex_kdtree, reach_area=None):
# determines if point x is within allowed reach area
# ex_kdtree is a set of example points w/in the reachable area (see is_reachable())
# reach_area: if None, any point w/in the arm's reachable area is okay
# if (x_min, x_max, y_min, y_max), specifies a box within which reaches must lie
if is_reachable(x, ex_kdtree):
if reach_area == None:
return True
else:
# has form (x_min, x_max, y_min, y_max)
(x_min, x_max, y_min, y_max) = reach_area
if x[0] > x_min and x[0] < x_max and x[1] > y_min and x[1] < y_max:
return True
else:
return False
else:
return False
def draw_pts_from_reach_area(n_samples, ex_kdtree, reach_area=None):
# draw points uniformly from the specified reach area. If reach_area=None, draw
# points from the whole reachable space
if reach_area == None:
(x_min, x_max, y_min, y_max) = (-0.298, 0.298, -0.298, 0.298)
else:
(x_min, x_max, y_min, y_max) = reach_area
x_len = x_max - x_min
y_len = y_max - y_min
scaler = array([x_len, y_len, 0.0])
shift = array([x_min, y_min, 0.0])
pts = []
for i in range(n_samples):
is_bad = True # point is reachable or not
while is_bad:
# draw point from given reach box
pt = random.rand(3) * scaler + shift
if is_reachable(pt, ex_kdtree):
pts += [pt]
is_bad = False
return pts
def q_pos_obj_fn(q, pos, params):
# pos is 3D vector
# q = (q1,q2) here
return linalg.norm(pos_c0(q, params) - pos)
def get_q_for_pos(pos, ex_q, ex_pos, params, dims):
# get q1,q2 corresponding to a given pos in x,y,z coords
# pos: desired starting pos (x,y,z)
# ex_q: array of example q, each row a q1, q2
# ex_pos: array of example positions corresponding to the ex_q
# closest starting pos among samples
indx = argmin(linalg.norm(ex_pos - pos, axis=1))
# do a quick optimization to find best associated init cond
q = minimize(q_pos_obj_fn, ex_q[indx, :],
args=(pos, params), method='L-BFGS-B', bounds=((-pi/4, 3*pi/4), (0, 3*pi/4)))
return q.x
def make_targets_init_conds_from_distribution(n_samples, dist_sampler, reach_area,
ex_kdtree, params, dims):
# make list of targets and starting positions (and corresponding list of initial conditions)
# dist_sampler: dist_sampler() returns a samples from some distribution on reach lengths (in meters)
# reach_area: if None, any point w/in the arm's reachable area is okay
# if (x_min, x_max, y_min, y_max), specifies a box within which reaches must lie
# Targets are drawn uniformly from the reach_area
# ex_kdtree: a kdtree of example points in the reachable space, for determining when a new point is reachable or not
# make targets (drawn uniformly from the reach_area)
target_list = draw_pts_from_reach_area(n_samples, ex_kdtree, reach_area)
start_pos_list = []
for i in range(n_samples):
reach_len = dist_sampler()
is_bad = True
n_tries = 0
while is_bad:
# get point on circle of radius reach_len around target
theta = random.rand() * 2 * pi
pt = reach_len * array([cos(theta), sin(theta), 0.0]) + target_list[i]
if allowable_point(pt, ex_kdtree, reach_area):
start_pos_list += [pt]
is_bad = False
else:
n_tries += 1
if n_tries > 100:
# get a new reach_len, since the current one may be impossible from the given target
reach_len = dist_sampler()
# make some example q and corresponding positions
ex_q = column_stack(((pi * random.rand(200)) - pi/4, (3*pi/4)*random.rand(200)))
ex_pos = vstack([pos_c0(ex_q[i,:], params) for i in range(len(ex_q))])
# find initial conds to match start_pos_list, and q for target_list
x0 = zeros(dims[0])
m0 = zeros(dims[1])
init_cond_list = []
q_target_list = []
for i in range(n_samples):
q_init = get_q_for_pos(start_pos_list[i], ex_q, ex_pos, params, dims)
init_cond_list += [hstack((x0, m0, q_init, zeros(dims[5]//2)))]
q_target = get_q_for_pos(target_list[i], ex_q, ex_pos, params, dims)
q_target_list += [q_target]
return target_list, init_cond_list, start_pos_list, q_target_list
class unif_dist_sampler:
def __init__(self, low, high):
self.low = low
self.high = high
self.width = self.high - self.low
def __call__(self, n=None):
if n == None:
return self.width * random.rand() + self.low
else:
return self.width * random.rand(n) + self.low
class trunc_exp_sampler:
def __init__(self, scale, limit):
self.scale = scale # mean (if limit=inf; roughly still true if limit >= 4*scale)
self.limit = limit # where to truncate exponential distribution
def __call__(self):
while True:
out = random.exponential(self.scale)
if out < self.limit:
return out
def make_target_list(n_samples, params):
target_list = []
for i in range(n_samples):
q1 = (pi * random.rand()) - (pi / 4)
q2 = (3 * pi / 4) * random.rand()
dq1 = 0
dq2 = 0
q = array([q1, q2, dq1, dq2])
c0 = pos_c0(q, params)
target_list += [c0]
return target_list
def make_targets_init_cond_uniformly_from_reach_area(n_samples, reach_area, params, dims):
# draw start and stop points uniformly from the x,y,z reachable space rather than q1,q2 angle space
# reach_area = (x_min, x_max, y_min, y_max)
ex_pts = vstack(make_target_list(int(1e5), params))
ex_kdtree = KDTree(ex_pts)
# Draw uniformly pts from reach area
start_list = draw_pts_from_reach_area(n_samples, ex_kdtree, reach_area)
target_list = draw_pts_from_reach_area(n_samples, ex_kdtree, reach_area)
# make some example q and corresponding positions
ex_q = column_stack(((pi * random.rand(200)) - pi/4, (3 * pi / 4) * random.rand(200)))
ex_pos = vstack([pos_c0(ex_q[i, :], params) for i in range(len(ex_q))])
x0 = zeros(dims[0])
m0 = zeros(dims[1])
init_cond_list = [hstack((x0, m0, get_q_for_pos(start_list[i], ex_q, ex_pos, params, dims), zeros(dims[5]//2)))
for i in range(n_samples)]
q_start_list = [init_cond_list[i][-4:-2] for i in range(n_samples)]
q_target_list = [get_q_for_pos(target_list[i], ex_q, ex_pos, params, dims) for i in range(n_samples)]
return start_list, target_list, q_start_list, q_target_list, init_cond_list
# For plotting
def make_plot(q, params):
q1, q2, dq1, dq2 = q
a0 = pos_a0(q, params)
b0 = pos_b0(q, params)
c0 = pos_c0(q, params)
x = array([a0[0], b0[0], c0[0]])
y = array([a0[1], b0[1], c0[1]])
return x, y
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
# Stuff related to adjoint method calculations
@numba.jit(nopython=True)
def block_diag(*blocks):
# my version of block_diag to replace scipy's, since it doesn't
# compile with numba. Requires 2D arrays, so 1D row vectors need to be turned
# into 2D arrays. This is a numba limitation, since it can't even iterate over the
# *blocks arg if it's not all the same dimension.
n_blocks = len(blocks)
block_dims = zeros((n_blocks, 2), dtype=int64)
for i, block in enumerate(blocks):
block_dims[i, :] = shape(block)
out = zeros((sum(block_dims[:, 0]), sum(block_dims[:, 1])))
tl = array([0, 0]) # top left indices of current block (row, col)
for i, block in enumerate(blocks):
br = tl + block_dims[i, :]
out[tl[0]:br[0], tl[1]:br[1]] = block
tl = br
return out
@numba.jit(nopython=True)
def dv1_dr(q, params):
# v1(r) is pos_hand(r)
q1, q2, dq1, dq2 = q
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
q_delay = params[23]
c1 = cos(q1 - dq1*q_delay)
c2 = cos(q2 - dq2*q_delay)
s1 = sin(q1 - dq1*q_delay)
s2 = sin(q2 - dq2*q_delay)
df1_dq1 = (-1 * LA * s1 + LB * (-1 * c2 * s1 + -1 * c1 * s2))
df1_dq2 = LB * (-1 * c2 * s1 + -1 * c1 * s2)
df2_dq1 = (c1 * LA + LB * (c1 * c2 + -1 * s1 * s2))
df2_dq2 = LB * (c1 * c2 + -1 * s1 * s2)
out = array(
[[df1_dq1, df1_dq2, -df1_dq1*q_delay, -df1_dq2*q_delay, ],
[df2_dq1, df2_dq2, -df2_dq1*q_delay, -df2_dq2*q_delay, ],
[0.e-323, 0.e-323, 0.e-323, 0.e-323, ], ]
)
return out
@numba.jit(nopython=True)
def dv2_dr(q, params):
# v2(r) is the velocity of the hand
q1, q2, dq1, dq2 = q
c1 = cos(q1)
s1 = sin(q1)
LA = params[2]
LB = params[3]
out = array(
[[(-1 * dq2 * LB * cos((q1 + q2)) + dq1 * (-1 * c1 * LA + -1 * LB * cos((q1 + q2)))),
(-1 * dq1 * LB * cos((q1 + q2)) + -1 * dq2 * LB * cos((q1 + q2))), (-1 * LA * s1 + -1 * LB * sin((q1 + q2))),
-1 * LB * sin((q1 + q2)), ],
[(-1 * dq2 * LB * sin((q1 + q2)) + dq1 * (-1 * LA * s1 + -1 * LB * sin((q1 + q2)))),
(-1 * dq1 * LB * sin((q1 + q2)) + -1 * dq2 * LB * sin((q1 + q2))), (c1 * LA + LB * cos((q1 + q2))),
LB * cos((q1 + q2)), ], [0., 0., 0., 0., ], ]
)
return out
@numba.jit(nopython=True)
def dpos_error_dr(q, params):
# For objective fn, since pos_error() isn't the same as v1_fn anymore
q1, q2, dq1, dq2 = q
c1 = cos(q1)
c2 = cos(q2)
s1 = sin(q1)
s2 = sin(q2)
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
out = array(
[[(-1 * LA * s1 + LB * (-1 * c2 * s1 + -1 * c1 * s2)), LB * (-1 * c2 * s1 + -1 * c1 * s2), 0.e-323, 0.e-323, ],
[(c1 * LA + LB * (c1 * c2 + -1 * s1 * s2)), LB * (c1 * c2 + -1 * s1 * s2), 0.e-323, 0.e-323, ],
[0.e-323, 0.e-323, 0.e-323, 0.e-323, ], ]
)
return out
@numba.jit(nopython=True)
def dhr_dr(t, q, m, ext_force, params):
# ext_force is a vector
q1, q2, dq1, dq2 = q
c1 = cos(q1)
c2 = cos(q2)
s1 = sin(q1)
s2 = sin(q2)
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
f1, f2 = ext_force # components of external force
rhs = make_rhs_arm(t, q, m, ext_force, params)
ddq1, ddq2 = rhs[2:]
out = array(
[[0.e-323, 0.e-323, (-0.1e1), 0.e-323, ], [0.e-323, 0.e-323, 0.e-323, (-0.1e1), ], [((
-0.1e1) * g * LA * mB * s1 + (
(
-0.1e1) * g * mA * rhoA * s1 + (
g * mB * rhoB * (
(
-0.1e1) * c2 * s1 + (
-0.1e1) * c1 * s2) + (
(
-0.1e1) * f2 * (
(
-0.1e1) * LA * s1 + LB * (
(
-0.1e1) * c2 * s1 + (
-0.1e1) * c1 * s2)) + (
(
-0.1e1) * f1 * (
(
-0.1e1) * c1 * LA + LB * (
(
-0.1e1) * c1 * c2 + s1 * s2)) + (
0.5e0 * exp(
-5 * (
3 / 4 * pi + -1 * q1)) + 0.5e0 * exp(
-5 * (
1 / 4 * pi + q1)))))))),
(0.e-323 + (c2 * (dq1) ** (
2) * LA * mB * rhoB + ((
-0.1e1) * c2 * (
(
dq1 + dq2)) ** (
2) * LA * mB * rhoB + (
-2 * ddq1 * LA * mB * rhoB * s2 + (
(
-0.1e1) * ddq2 * LA * mB * rhoB * s2 + (
(
-0.1e1) * f2 * LB * (
(
-0.1e1) * c2 * s1 + (
-0.1e1) * c1 * s2) + (
g * mB * rhoB * (
(
-0.1e1) * c2 * s1 + (
-0.1e1) * c1 * s2) + (
-0.1e1) * f1 * LB * (
(
-0.1e1) * c1 * c2 + s1 * s2)))))))),
(0.5e-1 + (
2 * dq1 * LA * mB * rhoB * s2 + -2 * (
dq1 + dq2) * LA * mB * rhoB * s2)),
(0.e-323 + -2 * (
dq1 + dq2) * LA * mB * rhoB * s2), ],
[((-0.1e1) * f2 * LB * ((-0.1e1) * c2 * s1 + (-0.1e1) * c1 * s2) + (
g * mB * rhoB * ((-0.1e1) * c2 * s1 + (-0.1e1) * c1 * s2) + (-0.1e1) * f1 * LB * (
(-0.1e1) * c1 * c2 + s1 * s2))), (c2 * (dq1) ** (2) * LA * mB * rhoB + (
(-0.1e1) * ddq1 * LA * mB * rhoB * s2 + (
(-0.1e1) * f2 * LB * ((-0.1e1) * c2 * s1 + (-0.1e1) * c1 * s2) + (
g * mB * rhoB * ((-0.1e1) * c2 * s1 + (-0.1e1) * c1 * s2) + (
(-0.1e1) * f1 * LB * ((-0.1e1) * c1 * c2 + s1 * s2) + (
0.5e0 * exp(-5 * (3 / 4 * pi + -1 * q2)) + 0.5e0 * exp(-5 * (0.e-323 + q2)))))))),
(0.e-323 + 2 * dq1 * LA * mB * rhoB * s2), 0.5e-1, ], ]
)
return out
@numba.jit(nopython=True)
def dh_dr(t, q, m, ext_force, C1, C4, params, dims):
q_delay = params[23]
dv4_dr = hstack((eye(2), -q_delay * eye(2)))
dhx_dr = -(dot(C1, dv1_dr(q, params)) + dot(C4, dv4_dr))
dhm_dr = zeros((dims[1], dims[5]))
out = vstack((dhx_dr, dhm_dr, dhr_dr(t, q, m, ext_force, params)))
return out
@numba.jit(nopython=True)
def dR_dm(q, params, dims):
moment_arrayA, moment_arrayB = get_muscle_moment_arrays()
max_muscle_force = diag(array([params[9], params[10],
params[11], params[12],
params[20], params[21]]))
dR_dtauA = zeros((dims[5], 3), dtype=float64)
dR_dtauA[2, 2] = 1.0
dR_dtauB = zeros((dims[5], 3), dtype=float64)
dR_dtauB[2, 2] = 1.0
dR_dtauB[3, 2] = 1.0
dtauA_dm = dot(moment_arrayA, max_muscle_force)
dtauB_dm = dot(moment_arrayB, max_muscle_force)
out = dot(dR_dtauA, dtauA_dm) + dot(dR_dtauB, dtauB_dm)
return out
@numba.jit(nopython=True)
def dh_dm(q, C3, params, dims):
dhx_dm = -C3
dhm_dm = (1.0 / params[13]) * eye(dims[1])
dhr_dm = -dR_dm(q, params, dims)
out = vstack((dhx_dm, dhm_dm, dhr_dm))
return out
@numba.jit(nopython=True)
def dh_dx(x, A, D0, D1, params, dims):
sigma_prime = dsigma_dx(D0 + dot(D1, x))
dhx_dx = -A
dhm_dx = -(1.0 / params[13]) * dot(sigma_prime, D1)
dhr_dx = zeros((dims[5], dims[0]), dtype=float64)
out = vstack((dhx_dx, dhm_dx, dhr_dx))
return out
@numba.jit(nopython=True)
def dh_dz(t, x, m, q, ext_force, A, C1, C3, C4, D0, D1, params, dims):
out1 = dh_dx(x, A, D0, D1, params, dims)
out2 = dh_dm(q, C3, params, dims)
out3 = dh_dr(t, q, m, ext_force, C1, C4, params, dims)
return hstack((out1, out2, out3))
@numba.jit(nopython=True)
def dh_dzdot(q, params, dims):
q1, q2, dq1, dq2 = q
c1 = cos(q1)
c2 = cos(q2)
s1 = sin(q1)
s2 = sin(q2)
mA = params[0]
mB = params[1]
rhoA = params[4]
rhoB = params[5]
LA = params[2]
LB = params[3]
IA = params[6]
IB = params[7]
g = params[8]
dh_dxdot = vstack((eye(dims[0]),
zeros((dims[1], dims[0]), dtype=float64),
zeros((dims[5], dims[0]), dtype=float64)))
dh_dmdot = vstack((zeros((dims[0], dims[1]), dtype=float64),
eye(dims[1]),
zeros((dims[5], dims[1]), dtype=float64)))
M_temp = array([[mA * (rhoA ** 2) + mB * (LA ** 2) + 2 * mB * LA * rhoB * c2 + mB * (rhoB ** 2) + IA + IB,
mB * LA * rhoB * c2 + mB * (rhoB ** 2) + IB],
[c2 * mB * rhoB * LA + (rhoB ** 2) * mB + IB, (rhoB ** 2) * mB + IB]], dtype=float64)
M = block_diag(eye(2, dtype=float64), M_temp)
dh_drdot = vstack((zeros((dims[0], dims[5]), dtype=float64),
zeros((dims[1], dims[5]), dtype=float64),
M))
out = hstack((dh_dxdot, dh_dmdot, dh_drdot))
return out
@numba.jit(nopython=True)
def d_dt_dh_dzdot(q, params, dims):
q1, q2, dq1, dq2 = q
s2 = sin(q2)
mB = params[1]
rhoB = params[5]
LA = params[2]
# derivative of mass matrix
dM_dt = array(
[[-2 * dq2 * LA * mB * rhoB * s2,-1 * dq2 * LA * mB * rhoB * s2,],[-1 * dq2 * LA * mB * rhoB * s2,0,],]
)
dMtilde_dt = block_diag(zeros((2, 2)), dM_dt)
d_dt_dh_dxdot = zeros((dims[14], dims[0]))
d_dt_dh_dmdot = zeros((dims[14], dims[1]))
d_dt_dh_drdot = vstack((zeros((dims[0] + dims[1], dims[5])), dMtilde_dt))
out = hstack((d_dt_dh_dxdot, d_dt_dh_dmdot, d_dt_dh_drdot))
return out
@numba.jit(nopython=True)
def d_dpK(K, x):
nrows = len(K)
N = len(x)
ncols = nrows * N
out = zeros((nrows, ncols))
indx = 0
for i in range(nrows):
out[i, indx:indx + N] = x
indx += N
return out
@numba.jit(nopython=True)
def dh_dp(x, u1, u2, u3, u4, v1, v3, v4, A, B1, B2, B3, B4, C1, C3, C4, D0, D1, params, dims):