forked from google-deepmind/mujoco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindings_test.ts
More file actions
2658 lines (2380 loc) · 86.6 KB
/
bindings_test.ts
File metadata and controls
2658 lines (2380 loc) · 86.6 KB
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
// Copyright 2025 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'jasmine';
import {MainModule, MjContact, MjContactVec, MjData, MjLROpt, MjModel,
MjOption, MjsGeom, MjSolverStat, MjSpec, MjStatistic, MjTimerStat, MjvCamera,
MjvFigure, MjvGeom, MjvGLCamera, MjvLight, MjvOption, MjvPerturb, MjvScene,
MjWarningStat, MjVFS, Uint8Buffer} from '../dist/mujoco.js';
import loadMujoco from '../dist/mujoco.js'
function assertExists<T>(value: T | null | undefined, message?: string):
asserts value is T {
if (value === null || value === undefined) {
throw new Error(message ?? 'Expected value to be defined.');
}
}
// Corresponds to bindings_test.py:TEST_XML
const TEST_XML = `
<mujoco model="test">
<compiler coordinate="local" angle="radian" eulerseq="xyz"/>
<size nkey="2"/>
<option timestep="0.002" gravity="0 0 -9.81"/>
<visual>
<global fovy="50" />
<quality shadowsize="51" />
</visual>
<worldbody>
<geom name="myplane" type="plane" size="10 10 1" user="1 2 3"/>
<body name="mybox" pos="0 0 0.1">
<geom name="mybox" type="box" size="0.1 0.1 0.1" mass="0.25"/>
<freejoint name="myfree"/>
</body>
<body name="myhinge-body" pos="0 0 1">
<inertial pos="0 0 0" mass="1" diaginertia="1 1 1"/>
<site pos="0 0 -1" name="mysite" type="sphere"/>
<joint name="myhinge" type="hinge" axis="0 1 0" damping="1"/>
</body>
<body name="myball-body" pos="2 0 1">
<inertial pos="0 0 0" mass="1" diaginertia="1 1 1"/>
<joint name="myball" type="ball"/>
</body>
<body name="mocap-body" mocap="true" pos="42 0 42">
<geom name="mocap-sphere" type="sphere" size="0.1"/>
</body>
</worldbody>
<actuator>
<position name="myactuator" joint="myhinge"/>
</actuator>
<sensor>
<jointvel name="myjointvel" joint="myhinge"/>
<accelerometer name="myaccelerometer" site="mysite"/>
</sensor>
</mujoco>
`;
type TypedArray =|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|
Int32Array|Uint32Array|Float32Array|Float64Array;
function norm(arr: number[]): number {
return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));
}
function expectArraysClose(arr1: any, arr2: TypedArray, precision = 1) {
expect(arr1.length).toEqual(arr2.length);
for (let i = 0; i < arr1.length; i++) {
expect(arr1[i]).toBeCloseTo(arr2[i], precision);
}
}
function expectArraysEqual(arr1: any, arr2: TypedArray) {
expect(arr1.length).toEqual(arr2.length);
for (let i = 0; i < arr1.length; i++) {
expect(arr1[i]).toEqual(arr2[i]);
}
}
describe('MuJoCo WASM Bindings', () => {
let mujoco: MainModule;
let model: MjModel|null = null;
let data: MjData|null = null;
beforeAll(async () => {
mujoco = await loadMujoco();
});
function unlinkXMLFile(filename: string) {
try {
(mujoco as any).FS.unlink(filename);
} catch (e) {
console.warn(`Failed to unlink temporary XML file: ${e}`);
}
}
function writeXMLFile(filename: string, xmlContent: string) {
try {
(mujoco as any).FS.writeFile(filename, xmlContent);
} catch (e) {
throw new Error(`Failed to write temporary XML file: ${e}`);
}
}
beforeEach(() => {
const tempXmlFilename = '/tmp/model.xml';
writeXMLFile(tempXmlFilename, TEST_XML);
model = mujoco.MjModel!.mj_loadXML(tempXmlFilename);
if (!model) {
unlinkXMLFile(tempXmlFilename);
throw new Error('Failed to load model from XML');
}
unlinkXMLFile(tempXmlFilename);
data = new mujoco.MjData(model);
if (!data) {
throw new Error('Failed to create data from model');
}
});
afterEach(() => {
model?.delete();
data?.delete();
});
describe('Buffer API', () => {
it('should construct from an element count', () => {
const buf = new mujoco.DoubleBuffer(5);
expect(buf.GetElementCount()).toBe(5);
expect(buf.GetPointer()).toBeDefined();
expect(buf.GetView()).toBeDefined();
});
it('should construct from a Javascript array', () => {
const array: number[] = [0, 1, 4, 9, 16];
const buf = mujoco.DoubleBuffer.FromArray(array);
expect(buf.GetElementCount()).toBe(5);
expect(buf.GetPointer()).toBeDefined();
expect(buf.GetView()).toBeDefined();
expectArraysClose(buf.GetView(), new Float64Array(array));
});
it('should construct from Float64Array', () => {
const array = new Float64Array([1 / 11, 7 / 11]);
const buf = mujoco.DoubleBuffer.FromArray(array);
expect(buf.GetElementCount()).toBe(2);
expect(buf.GetPointer()).toBeDefined();
expect(buf.GetView()).toBeDefined();
expectArraysClose(buf.GetView(), array);
});
});
describe('mj_addM', () => {
let simpleModel: MjModel|null = null;
let simpleData: MjData|null = null;
const tempXmlFilename = '/tmp/simple_model.xml';
// A simpler model with nv=1 and nM=1 to avoid WASM binding bugs.
const simpleXmlContent = `
<mujoco>
<worldbody>
<body name="box" pos="0 0 0.5">
<joint type="slide" axis="1 0 0"/>
<geom type="box" size="0.1 0.1 0.1" mass="1"/>
</body>
</worldbody>
</mujoco>`;
beforeEach(() => {
writeXMLFile(tempXmlFilename, simpleXmlContent);
simpleModel = mujoco.MjModel!.mj_loadXML(tempXmlFilename);
assertExists(simpleModel);
simpleData = new mujoco.MjData(simpleModel);
assertExists(simpleData);
});
afterEach(() => {
simpleModel?.delete();
simpleData?.delete();
unlinkXMLFile(tempXmlFilename);
});
it('should compute the sparse inertia matrix', () => {
const nM = simpleModel!.nM;
const dstSparse = new mujoco.DoubleBuffer(nM);
try {
mujoco.mj_forward(simpleModel!, simpleData!);
mujoco.mj_addM(
simpleModel!, simpleData!, dstSparse, simpleModel!.M_rownnz,
simpleModel!.M_rowadr, simpleModel!.M_colind);
expect(dstSparse.GetView().length).toBe(1);
expect(dstSparse.GetView()[0]).toBeCloseTo(1.0);
} finally {
dstSparse.delete();
}
});
it('should throw an error for incorrect sparse matrix dimensions', () => {
const nM = simpleModel!.nM;
const dstSparse = new mujoco.DoubleBuffer(nM + 1);
try {
expect(
() => mujoco.mj_addM(
simpleModel!, simpleData!, dstSparse, simpleModel!.M_rownnz,
simpleModel!.M_rowadr, simpleModel!.M_colind))
.toThrowError(
'MuJoCo Error: [mj_addM] dst must have size 1, got 2');
} finally {
dstSparse.delete();
}
});
it('should compute the sparse inertia matrix with null pointers', () => {
const nM = simpleModel!.nM;
const dstSparse = new mujoco.DoubleBuffer(nM);
try {
mujoco.mj_forward(simpleModel!, simpleData!);
mujoco.mj_addM(simpleModel!, simpleData!, dstSparse, null, null, null);
expect(dstSparse.GetView().length).toBe(1);
} finally {
dstSparse.delete();
}
});
});
it('should compute geom distance without returning fromto', () => {
mujoco.mj_forward(model!, data!);
const dist = mujoco.mj_geomDistance(model!, data!, 0, 2, 200, null);
expect(dist).toEqual(41.9);
});
it('should handle box QP solver with null optionals', () => {
const n = 5;
const res = new mujoco.DoubleBuffer(n);
const r = new mujoco.DoubleBuffer(n * (n + 7));
const h = new mujoco.DoubleBuffer(n * n);
const g = mujoco.DoubleBuffer.FromArray(new Array(n).fill(1));
try {
for (let i = 0; i < n; i++) {
h.GetView()[i * (n + 1)] = 1;
}
const rank = mujoco.mju_boxQP(
res, r, null, h.GetView(), g.GetView(), null as any, null as any);
expect(rank).toBeGreaterThan(-1);
} finally {
res.delete();
r.delete();
h.delete();
g.delete();
}
});
// Corresponds to engine_core_constraint_test.cc:TEST_F(CoreConstraintTest,
// ConstraintUpdateImpl)
it('should correctly compute constraint cost', () => {
const xmlString = `
<mujoco>
<option>
<flag island="enable"/>
</option>
<default>
<geom size=".1"/>
</default>
<visual>
<headlight diffuse=".9 .9 .9"/>
</visual>
<worldbody>
<body>
<joint type="slide" axis="0 0 1" range="0 1" limited="true"/>
<geom/>
</body>
<body pos=".25 0 0">
<joint type="slide" axis="1 0 0"/>
<geom/>
</body>
<body pos="0 0 0.25">
<joint type="slide" axis="0 0 1"/>
<geom/>
<body pos="0 -.15 0">
<joint name="hinge1" axis="0 1 0"/>
<geom type="capsule" size="0.03" fromto="0 0 0 -.2 0 0"/>
<body pos="-.2 0 0">
<joint axis="0 1 0"/>
<geom type="capsule" size="0.03" fromto="0 0 0 -.2 0 0"/>
</body>
</body>
</body>
<body pos=".5 0 0">
<joint type="slide" axis="0 0 1" frictionloss="15"/>
<geom type="box" size=".08 .08 .02" euler="0 10 0"/>
</body>
<body pos="-.5 0 0">
<joint axis="0 1 0" frictionloss=".01"/>
<geom type="capsule" size="0.03" fromto="0 0 0 -.2 0 0"/>
</body>
<body pos="0 0 .5">
<joint name="hinge2" axis="0 1 0"/>
<geom type="box" size=".08 .02 .08"/>
</body>
<body pos=".5 0 .1">
<freejoint/>
<geom type="box" size=".03 .03 .03" pos="0.01 0.01 0.01"/>
</body>
<site name="0" pos="-.45 -.05 .35"/>
<body pos="-.5 0 .3" name="connect">
<freejoint/>
<geom type="box" size=".05 .05 .05"/>
<site name="1" pos=".05 -.05 .05"/>
</body>
</worldbody>
<equality>
<joint joint1="hinge1" joint2="hinge2"/>
<connect body1="connect" body2="world" anchor="-.05 -.05 .05"/>
<connect site1="0" site2="1"/>
</equality>
</mujoco>
`;
const tempXmlFilename = '/tmp/model_c.xml';
writeXMLFile(tempXmlFilename, xmlString);
const model = mujoco.MjModel!.mj_loadXML(tempXmlFilename);
expect(model).not.toBeNull();
const data = new mujoco.MjData(model!);
expect(data).not.toBeNull();
unlinkXMLFile(tempXmlFilename);
try {
mujoco.mj_resetData(model, data!);
let steps = 0;
while (data!.ncon === 0 && steps < 100) {
mujoco.mj_step(model!, data!);
steps++;
}
mujoco.mj_forward(model!, data!);
const res = new mujoco.DoubleBuffer(data!.nefc);
mujoco.mj_mulJacVec(model!, data!, res, data!.qacc);
mujoco.mju_subFrom(res, data!.efc_aref);
const cost = mujoco.DoubleBuffer.FromArray([0]);
mujoco.mj_constraintUpdate(
model!, data!, res.GetView(), cost, /*flg_coneHessian=*/ 1);
expect(cost.GetView()[0]).toBeCloseTo(3357.584);
res.delete();
cost.delete();
} finally {
data!.delete();
model!.delete();
}
});
it('should compute body jacobian', () => {
mujoco.mj_forward(model!, data!);
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const point = [0.1, 0.2, 0.3];
const jacp = new mujoco.DoubleBuffer(3 * model!.nv);
const jacr = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jac(model!, data!, jacp, jacr, point, bodyId);
expect(norm(jacp.GetView())).toBeGreaterThan(0);
expect(norm(jacr.GetView())).toBeGreaterThan(0);
expect(() => mujoco.mj_jac(model!, data!, null, null, point, bodyId))
.not.toThrow();
} finally {
jacp.delete();
jacr.delete();
}
});
it('should compute body frame jacobian', () => {
mujoco.mj_forward(model!, data!);
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const jacp = new mujoco.DoubleBuffer(3 * model!.nv);
const jacr = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jacBody(model!, data!, jacp, jacr, bodyId);
expect(norm(jacp.GetView())).toBeGreaterThan(0);
expect(norm(jacr.GetView())).toBeGreaterThan(0);
expect(() => mujoco.mj_jacBody(model!, data!, null, null, bodyId))
.not.toThrow();
} finally {
jacp.delete();
jacr.delete();
}
});
it('should compute body CoM jacobian', () => {
mujoco.mj_forward(model!, data!);
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const jacp = new mujoco.DoubleBuffer(3 * model!.nv);
const jacr = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jacBodyCom(model!, data!, jacp, jacr, bodyId);
expect(norm(jacp.GetView())).toBeGreaterThan(0);
expect(norm(jacr.GetView())).toBeGreaterThan(0);
expect(() => mujoco.mj_jacBodyCom(model!, data!, null, null, bodyId))
.not.toThrow();
} finally {
jacp.delete();
jacr.delete();
}
});
it('should compute geom jacobian', () => {
mujoco.mj_forward(model!, data!);
const geomId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_GEOM.value, 'mybox');
const jacp = new mujoco.DoubleBuffer(3 * model!.nv);
const jacr = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jacGeom(model!, data!, jacp, jacr, geomId);
expect(norm(jacp.GetView())).toBeGreaterThan(0);
expect(norm(jacr.GetView())).toBeGreaterThan(0);
expect(() => mujoco.mj_jacGeom(model!, data!, null, null, geomId))
.not.toThrow();
} finally {
jacp.delete();
jacr.delete();
}
});
it('should compute point-axis jacobian', () => {
mujoco.mj_forward(model!, data!);
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const point = [0.1, 0.2, 0.3];
const axis = [0, 0, 1];
const jacPoint = new mujoco.DoubleBuffer(3 * model!.nv);
const jacAxis = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jacPointAxis(
model!, data!, jacPoint, jacAxis, point, axis, bodyId);
expect(norm(jacPoint.GetView())).toBeGreaterThan(0);
expect(norm(jacAxis.GetView())).toBeGreaterThan(0);
expect(
() => mujoco.mj_jacPointAxis(
model!, data!, null, null, point, axis, bodyId))
.not.toThrow();
} finally {
jacPoint.delete();
jacAxis.delete();
}
});
it('should compute jacobian time derivative', () => {
mujoco.mj_forward(model!, data!);
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const point = [0.1, 0.2, 0.3];
const jacp = new mujoco.DoubleBuffer(3 * model!.nv);
const jacr = new mujoco.DoubleBuffer(3 * model!.nv);
try {
mujoco.mj_jacDot(model!, data!, jacp, jacr, point, bodyId);
expect(jacp.GetView().length).toBe(3 * model!.nv);
expect(jacr.GetView().length).toBe(3 * model!.nv);
expect(() => mujoco.mj_jacDot(model!, data!, null, null, point, bodyId))
.not.toThrow();
} finally {
jacp.delete();
jacr.delete();
}
});
it('should apply external force and torque', () => {
const force = [1, .5, 1];
const torque = [.3, 1, .22];
const point = [0, 0, 0];
const bodyId =
mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_BODY.value, 'mybox');
const qfrcTarget = new mujoco.DoubleBuffer(model!.nv);
try {
mujoco.mj_forward(model!, data!);
mujoco.mj_applyFT(
model!, data!, force, torque, point, bodyId, qfrcTarget);
expect(norm(qfrcTarget.GetView())).toBeGreaterThan(0);
qfrcTarget.GetView().fill(0);
mujoco.mj_applyFT(
model!, data!, null as any, null as any, point, bodyId, qfrcTarget);
expect(norm(qfrcTarget.GetView())).toEqual(0);
} finally {
qfrcTarget.delete();
}
});
it('should compute finite-differenced transition matrices', () => {
const eps = 1e-6;
const flg_centered = 0;
const dim = 2 * model!.nv + model!.na;
const A = new mujoco.DoubleBuffer(dim * dim);
const B = new mujoco.DoubleBuffer(dim * model!.nu);
const C = new mujoco.DoubleBuffer(model!.nsensordata * dim);
const D = new mujoco.DoubleBuffer(model!.nsensordata * model!.nu);
try {
mujoco.mjd_transitionFD(model!, data!, eps, flg_centered, A, B, C, D);
expect(norm(A.GetView())).toBeGreaterThan(0);
expect(norm(B.GetView())).toBeGreaterThan(0);
expect(norm(C.GetView())).toBeGreaterThan(0);
expect(
() => mujoco.mjd_transitionFD(
model!, data!, eps, flg_centered, null, null, null, null))
.not.toThrow();
} finally {
A.delete();
B.delete();
C.delete();
D.delete();
}
});
it('should solve a system of linear equations', () => {
const n = 2;
const mat = [4, 1, 1, 3];
const vec = [1, 2];
const res = new mujoco.DoubleBuffer(n);
const expected = new Float64Array([1 / 11, 7 / 11]);
const matFactor = mujoco.DoubleBuffer.FromArray(mat);
try {
const rank = mujoco.mju_cholFactor(matFactor, 1e-9);
expect(rank).toBe(n);
mujoco.mju_cholSolve(res, matFactor.GetView(), vec);
const result = res.GetView();
expect(result[0]).toBeCloseTo(expected[0]);
expect(result[1]).toBeCloseTo(expected[1]);
} finally {
res.delete();
matFactor.delete();
}
});
it('should update a Cholesky factorization', () => {
const n = 2;
const mat = [4, 1, 1, 3];
const x = [1, 1];
const matFactor = mujoco.DoubleBuffer.FromArray(mat);
const xBuf = mujoco.DoubleBuffer.FromArray(x);
const res = new mujoco.DoubleBuffer(n);
try {
// Factorize original matrix.
mujoco.mju_cholFactor(matFactor, 1e-9);
// Update factorization with x.
const flg_plus = 1;
mujoco.mju_cholUpdate(matFactor, xBuf.GetView(), flg_plus);
// Solve a system with the updated factor to verify.
// A' = A + x*x' = [[5, 2], [2, 4]]
// A' * y = vec => [[5, 2], [2, 4]] * y = [7, 6]
// Solution is y = [1, 1].
const vec = [7, 6];
mujoco.mju_cholSolve(res, matFactor.GetView(), vec);
const result = res.GetView();
const expectedSolution = new Float64Array([1, 1]);
expect(result[0]).toBeCloseTo(expectedSolution[0]);
expect(result[1]).toBeCloseTo(expectedSolution[1]);
} finally {
matFactor.delete();
xBuf.delete();
res.delete();
}
});
it('should multiply a transposed matrix by another matrix', () => {
const r1 = 3, c1 = 2, c2 = 2;
const mat1 = mujoco.DoubleBuffer.FromArray([1, 4, 2, 5, 3, 6]);
const mat2 = mujoco.DoubleBuffer.FromArray([7, 8, 9, 10, 11, 12]);
const res = new mujoco.DoubleBuffer(c1 * c2);
const expected = new Float64Array([58, 64, 139, 154]);
try {
mujoco.mju_mulMatTMat(res, mat1.GetView(), mat2.GetView(), r1, c1, c2);
expectArraysClose(res.GetView(), expected);
} finally {
mat1.delete();
mat2.delete();
res.delete();
}
});
it('should throw an error because of incompatible matrix sizes', () => {
const r1 = 3, c1 = 2, c2 = 2;
const mat1 = mujoco.DoubleBuffer.FromArray([1, 4, 2, 5, 3, 6]);
const mat2 = mujoco.DoubleBuffer.FromArray([7, 8, 9, 10, 11]);
const res = new mujoco.DoubleBuffer(c1 * c2);
try {
expect(
() => mujoco.mju_mulMatTMat(
res, mat1.GetView(), mat2.GetView(), r1, c1, c2))
.toThrowError(
'MuJoCo Error: [mju_mulMatTMat] mat2 must have size 6, got 5');
} finally {
mat1.delete();
mat2.delete();
res.delete();
}
});
it('should convert a dense matrix to sparse and return non-zero count',
() => {
const nr = 2;
const nc = 3;
const mat = [0.0, 1.0, 0.0, 2.0, 0.0, 3.0];
const rownnz = new mujoco.IntBuffer(nr);
const rowadr = new mujoco.IntBuffer(nr);
const colind = new mujoco.IntBuffer(nc);
const res = new mujoco.DoubleBuffer(nc);
try {
const nnz =
mujoco.mju_dense2sparse(res, mat, nr, nc, rownnz, rowadr, colind);
expectArraysEqual(res.GetView(), new Float64Array([1.0, 2.0, 3.0]));
expectArraysEqual(rownnz.GetView(), new Int32Array([1, 2]));
expectArraysEqual(rowadr.GetView(), new Int32Array([0, 1]));
expectArraysEqual(colind.GetView(), new Int32Array([1, 0, 2]));
} finally {
res.delete();
rownnz.delete();
rowadr.delete();
colind.delete();
}
});
it('should convert a sparse matrix to a dense matrix', () => {
const nr = 2;
const nc = 3;
const mat = [1.0, 2.0, 3.0];
const rownnz = [1, 2];
const rowadr = [0, 1];
const colind = [1, 0, 2];
const res = new mujoco.DoubleBuffer(nr * nc);
const expected = new Float64Array([0.0, 1.0, 0.0, 2.0, 0.0, 3.0]);
try {
mujoco.mju_sparse2dense(res, mat, nr, nc, rownnz, rowadr, colind);
expectArraysEqual(res.GetView(), expected);
} finally {
res.delete();
}
});
it('should throw an error when mju_eye is called with a null argument', () => {
expect(() => {
mujoco.mju_eye(null as any);
})
.toThrowError(
'MuJoCo Error: [mju_eye] Invalid argument. Expected a TypedArray or WasmBuffer, got null.');
});
it('should return undefined', () => {
const spec = mujoco.parseXMLString(TEST_XML);
const body = mujoco.mjs_findBody(spec, 'some_name_that_doesnt_exist');
expect(body).toBeUndefined();
body?.delete();
spec?.delete();
});
it('should check constants values', () => {
expect(mujoco.mjNEQDATA).toBe(11);
expect(mujoco.mjDISABLESTRING).toEqual([
'Constraint', 'Equality', 'Frictionloss', 'Limit', 'Contact', 'Spring',
'Damper', 'Gravity', 'Clampctrl', 'Warmstart', 'Filterparent',
'Actuation', 'Refsafe', 'Sensor', 'Midphase', 'Eulerdamp', 'AutoReset',
'NativeCCD', 'Island'
]);
expect(mujoco.mjRNDSTRING).toEqual([
['Shadow', '1', 'S'], ['Wireframe', '0', 'W'], ['Reflection', '1', 'R'],
['Additive', '0', 'L'], ['Skybox', '1', 'K'], ['Fog', '0', 'G'],
['Haze', '1', '/'], ['Depth', '0', ''], ['Segment', '0', ','],
['Id Color', '0', ''], ['Cull Face', '1', '']
]);
expect(mujoco.mjFRAMESTRING.length).toEqual(mujoco.mjtFrame.mjNFRAME.value);
expect(mujoco.mjVISSTRING.length)
.toEqual(mujoco.mjtVisFlag.mjNVISFLAG.value);
expect(mujoco.mjVISSTRING[mujoco.mjtVisFlag.mjVIS_INERTIA.value]).toEqual([
'Inertia', '0', 'I'
]);
});
it('should create a spec from XML', () => {
const spec = mujoco.parseXMLString(TEST_XML);
try {
expect(spec).toBeDefined();
expect(spec!.modelname).toEqual('test');
} finally {
spec?.delete();
}
});
it('should return the max value', () => {
expect(mujoco.mju_max(10, 2)).toEqual(10);
});
// Corresponds to bindings_test.py:test_mju_rotVecQuat
it('should rotate a vector by a quaternion', () => {
const res = mujoco.DoubleBuffer.FromArray([0, 0, 0]);
const vec = [1, 0, 0];
const angle = 7 * Math.PI / 12;
const quat = [Math.cos(angle), 0, 0, Math.sin(angle)];
const expected = new Float64Array([-0.8660377, -0.5, 0]);
try {
mujoco.mju_rotVecQuat(res, vec, quat);
expectArraysClose(res.GetView(), expected, 4);
} finally {
res.delete();
}
});
it('should get correct geom name', () => {
const spec = mujoco.parseXMLString(TEST_XML);
const geomEl =
mujoco.mjs_findElement(spec, mujoco.mjtObj.mjOBJ_GEOM, 'myplane');
try {
assertExists(geomEl);
const geom = mujoco.mjs_asGeom(geomEl);
assertExists(geom);
const geomName = mujoco.mjs_getName(geom.element);
expect(geomName).toEqual('myplane');
mujoco.mjs_setName(geom.element, 'myplane2');
expect(mujoco.mjs_getName(geom.element)).toEqual('myplane2');
} finally {
spec?.delete();
}
});
it('should override geom userdata', () => {
const spec = mujoco.parseXMLString(TEST_XML);
const geomEl =
mujoco.mjs_findElement(spec, mujoco.mjtObj.mjOBJ_GEOM, 'myplane');
try {
assertExists(geomEl);
const geom = mujoco.mjs_asGeom(geomEl);
assertExists(geom);
geom.userdata.set(0, 10);
expect(geom.userdata.get(0)).toEqual(10);
} finally {
spec.delete();
}
})
it('should override model geom_rgba', () => {
const newValues = new Float32Array([0.1, 0.2, 0.3, 0.4]);
model!.geom_rgba.set(newValues);
const expected = new Float32Array(
[0.1, 0.2, 0.3, 0.4, 0.5, 0.5, 0.5, 1, 0.5, 0.5, 0.5, 1]);
expectArraysClose(model!.geom_rgba, expected);
})
it('should add a scaled vector to another vector', () => {
const res = mujoco.DoubleBuffer.FromArray([1, 2, 3]);
const vec = [4, 5, 6];
const scale = 2;
const expected = new Float64Array([9, 12, 15]);
try {
mujoco.mju_addToScl(res, vec, scale);
expectArraysClose(res.GetView(), expected, 4);
} finally {
res.delete();
}
});
it('should throw an error when mju_addToScl is called with incompatible sizes',
() => {
const res = mujoco.DoubleBuffer.FromArray([1, 2, 3]);
const vec = [4, 5];
const scale = 2;
try {
expect(() => {
mujoco.mju_addToScl(res, vec, scale);
})
.toThrowError(
'MuJoCo Error: [mju_addToScl] res and vec must have equal size, got 3 and 2');
} finally {
res.delete();
}
});
it('should sort an array with insertion sort', () => {
const arr = mujoco.DoubleBuffer.FromArray([5, 2, 8, 1, 9]);
const expected = new Float64Array([1, 2, 5, 8, 9]);
try {
mujoco.mju_insertionSort(arr);
expectArraysEqual(arr.GetView(), expected);
} finally {
arr.delete();
}
});
it('should find the attached spec', () => {
const bXml = `
<mujoco>
<worldbody>
<body name="b" pos="0 0 0.1">
<geom rgba="0 .9 0 1" name="attached_geom_b" type="box" size="0.1 0.1 0.1" mass="0.25"/>
<freejoint name="bfree"/>
</body>
</worldbody>
</mujoco>
`;
const xmlWithAttachedSpec = `
<mujoco>
<asset>
<model name="b" file="b.xml" />
</asset>
<worldbody>
<attach model="b" body="b" prefix="b" />
</worldbody>
</mujoco>
`;
const mainXmlFilename = 'main.xml';
const bXmlFilename = 'b.xml';
writeXMLFile(mainXmlFilename, xmlWithAttachedSpec);
writeXMLFile(bXmlFilename, bXml);
const spec = mujoco.parseXMLString(xmlWithAttachedSpec);
const attachedSpec = mujoco.mjs_findSpec(spec, 'b');
try {
assertExists(attachedSpec);
const geomEl = mujoco.mjs_findElement(
attachedSpec, mujoco.mjtObj.mjOBJ_GEOM, 'attached_geom_b');
assertExists(geomEl);
const geom = mujoco.mjs_asGeom(geomEl);
expect(geom).toBeDefined();
expect(mujoco.mjs_getName(geom!.element)).toEqual('attached_geom_b');
} finally {
attachedSpec?.delete();
spec?.delete();
unlinkXMLFile(mainXmlFilename);
unlinkXMLFile(bXmlFilename);
}
});
// Corresponds to bindings_test.py:test_load_xml_can_handle_name_clash
it('should handle name clashes when loading XML with includes', () => {
const xml1 = `
<mujoco>
<worldbody>
<geom name="plane" type="plane" size="1 1 1"/>
<include file="model_.xml"/>
<include file="model__.xml"/>
</worldbody>
</mujoco>
`;
const xml2 = `<mujoco><geom name="box" type="box" size="1 1 1"/></mujoco>`;
const xml3 = `<mujoco><geom name="ball" type="sphere" size="1"/></mujoco>`;
const modelXmlFilename = 'model.xml';
const model1XmlFilename = 'model_.xml';
const model2XmlFilename = 'model__.xml';
writeXMLFile(modelXmlFilename, xml1);
writeXMLFile(model1XmlFilename, xml2);
writeXMLFile(model2XmlFilename, xml3);
const model = mujoco.MjModel!.mj_loadXML(modelXmlFilename);
try {
expect(model).toBeDefined();
expect(mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_GEOM.value, 'plane'))
.toBe(0);
expect(mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_GEOM.value, 'box'))
.toBe(1);
expect(mujoco.mj_name2id(model!, mujoco.mjtObj.mjOBJ_GEOM.value, 'ball'))
.toBe(2);
} finally {
model?.delete();
unlinkXMLFile(modelXmlFilename);
unlinkXMLFile(model1XmlFilename);
unlinkXMLFile(model2XmlFilename);
}
});
// Corresponds to bindings_test.py:test_can_read_array
it('should read an array from the model', () => {
const expected =
new Float64Array([0, 0, 0, 0, 0, 0.1, 0, 0, 1, 2, 0, 1, 42, 0, 42]);
const bodyPos = new Float64Array(model!.body_pos);
expectArraysEqual(bodyPos, expected);
});
// Corresponds to bindings_test.py:test_can_set_array
it('should set an array from the data', () => {
const value = 0.12345;
data!.qpos.fill(value);
const expected = new Float64Array(data!.qpos.length).fill(value);
expectArraysEqual(data!.qpos, expected);
});
// Corresponds to bindings_test.py:test_array_is_a_view
it('should check that array is a view', () => {
const qposRef = data!.qpos;
const value = 0.789;
data!.qpos.fill(value);
const expected = new Float64Array(data!.qpos.length).fill(value);
expectArraysEqual(qposRef, expected);
});
// Corresponds to bindings_test.py:test_mjmodel_can_read_and_write_opt
it('should read and write MjOption', () => {
expect(model!.opt.timestep).toEqual(0.002);
expectArraysEqual(model!.opt.gravity, new Float64Array([0, 0, -9.81]));
const optRef = model!.opt;
model!.opt.timestep = 0.001;
expect(optRef.timestep).toEqual(0.001);
const gravityRef = optRef.gravity;
model!.opt.gravity[1] = 0.1;
expectArraysEqual(gravityRef, new Float64Array([0, 0.1, -9.81]));
model!.opt.gravity.fill(0.2);
expectArraysEqual(gravityRef, new Float64Array([0.2, 0.2, 0.2]));
});
// Corresponds to bindings_test.py:test_mjmodel_can_read_and_write_stat
it('should read and write MjStat', () => {
expect(model!.stat.meanmass).not.toEqual(0);
const statRef = model!.stat;
model!.stat.meanmass = 1.2;
expect(statRef.meanmass).toEqual(1.2);
});
// Corresponds to bindings_test.py:test_mjmodel_can_read_and_write_vis
it('should read and write MjVis', () => {
expect(model!.vis.quality.shadowsize).toEqual(51);
const visRef = model!.vis;
model!.vis.quality.shadowsize = 100;
expect(visRef.quality.shadowsize).toEqual(100);
});
// Corresponds to bindings_test.py:test_mjmodel_can_access_names_directly
it('should access names directly from the model', () => {
const modelName = new TextDecoder().decode(
model!.names.slice(0, model!.names.indexOf(0)));
expect(modelName).toEqual('test');
const startGeomNameIndex = model!.name_geomadr[0];
const endGeomNameIndex = model!.names.indexOf(0, startGeomNameIndex);
const geomName = new TextDecoder().decode(
model!.names.slice(startGeomNameIndex, endGeomNameIndex));
expect(geomName).toEqual('myplane');
});
// Corresponds to bindings_test.py:test_mjmodel_names_doesnt_copy
it('should not copy names when accessing them multiple times', () => {
const names1 = model!.names;
const names2 = model!.names;
expect(names1).toEqual(names2);
});
// Corresponds to bindings_test.py:test_mjoption_can_make_default
it('should create a default MjOption', () => {
const opt = new mujoco.MjOption();
expect(opt.timestep).toEqual(0.002);
expectArraysEqual(opt.gravity, new Float64Array([0, 0, -9.81]));
});
// Corresponds to bindings_test.py:test_mjoption_can_copy
it('should copy MjOption', () => {
const opt1 = new mujoco.MjOption();
opt1.timestep = 0.001;
opt1.gravity.set([2, 2, 2]);
const opt2 = opt1.copy();
expect(opt2.timestep).toEqual(0.001);
expectArraysEqual(opt2.gravity, new Float64Array([2, 2, 2]));
opt1.timestep = 0.005;
opt1.gravity.set([5, 5, 5]);
expect(opt2.timestep).toEqual(0.001);
expectArraysEqual(opt2.gravity, new Float64Array([2, 2, 2]));