-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexploration_sim.py
2031 lines (1696 loc) · 97.8 KB
/
exploration_sim.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
"""Exploration Simulation
Simulation of a spacecraft exploring an asteroid
States are chosen to minimize a cost function tied to the uncertainty of the
shape. Full SE(3) dynamics and the polyhedron potential model is used
Author
------
Shankar Kulumani GWU [email protected]
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import pdb
import logging
import os
import tempfile
import argparse
from collections import defaultdict
import itertools
import subprocess
import h5py
import numpy as np
from scipy import integrate, interpolate, ndimage
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from lib import asteroid, surface_mesh, cgal, mesh_data, reconstruct
from lib import surface_mesh
from lib import controller as controller_cpp
from lib import stats
from lib import geodesic
from dynamics import dumbbell, eoms, controller
from point_cloud import wavefront
from kinematics import attitude
import utilities
from visualization import graphics, animation, publication
compression = 'gzip'
compression_opts = 9
max_steps = 15000
def initialize_asteroid(output_filename, ast_name="castalia"):
"""Initialize all the things for the simulation
Output_file : the actual HDF5 file to save the data/parameters to
"""
logger = logging.getLogger(__name__)
logger.info('Initialize asteroid and dumbbell objects')
AbsTol = 1e-9
RelTol = 1e-9
logger.info("Initializing Asteroid: {} ".format(ast_name))
# switch based on asteroid name
if ast_name == "castalia":
file_name = "castalia.obj"
v, f = wavefront.read_obj('./data/shape_model/CASTALIA/castalia.obj')
elif ast_name == "itokawa":
file_name = "itokawa_low.obj"
v, f = wavefront.read_obj('./data/shape_model/ITOKAWA/itokawa_low.obj')
elif ast_name == "eros":
file_name = "eros_low.obj"
v, f = wavefront.read_obj('./data/shape_model/EROS/eros_low.obj')
elif ast_name == "phobos":
file_name = "phobos_low.obj"
v, f = wavefront.read_obj('./data/shape_model/PHOBOS/phobos_low.obj')
elif ast_name == "lutetia":
file_name = "lutetia_low.obj"
v, f = wavefront.read_obj('./data/shape_model/LUTETIA/lutetia_low.obj')
elif ast_name == "geographos":
file_name = "1620geographos.obj"
v, f = wavefront.read_obj('./data/shape_model/RADAR/1620geographos.obj')
elif ast_name == "bacchus":
file_name = "2063bacchus.obj"
v, f = wavefront.read_obj('./data/shape_model/RADAR/2063bacchus.obj')
elif ast_name == "golevka":
file_name = "6489golevka.obj"
v, f = wavefront.read_obj('./data/shape_model/RADAR/6489golevka.obj')
elif ast_name == "52760":
file_name = "52760.obj"
v, f = wavefront.read_obj('./data/shape_model/RADAR/52760.obj')
else:
print("Incorrect asteroid name")
return 1
# true asteroid and dumbbell
true_ast_meshdata = mesh_data.MeshData(v, f)
true_ast = asteroid.Asteroid(ast_name, true_ast_meshdata)
dum = dumbbell.Dumbbell(m1=500, m2=500, l=0.003)
# estimated asteroid (starting as an ellipse)
if (ast_name == "castalia" or ast_name == "itokawa"
or ast_name == "golevka" or ast_name == "52760"):
surf_area = 0.01
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.03
max_distance = 0.5
elif ast_name == "geographos":
surf_area = 0.05
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.05
max_distance = 0.5
elif ast_name == "bacchus":
surf_area = 0.01
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.02
max_distance = 0.5
elif ast_name == "52760":
surf_area = 0.01
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.035
max_distance = 0.5
elif (ast_name == "phobos"):
surf_area = 0.1
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.006
max_distance = 0.1
elif (ast_name == "lutetia"):
surf_area = 1
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 1
max_distance = 1
elif (ast_name == "eros"):
surf_area = 0.1
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.2
max_distance = 0.01
ellipsoid = surface_mesh.SurfMesh(true_ast.get_axes()[0],
true_ast.get_axes()[1],
true_ast.get_axes()[2], min_angle,
max_radius, max_distance)
v_est = ellipsoid.get_verts()
f_est = ellipsoid.get_faces()
est_ast_meshdata = mesh_data.MeshData(v_est, f_est)
est_ast_rmesh = reconstruct.ReconstructMesh(est_ast_meshdata)
est_ast = asteroid.Asteroid(ast_name, est_ast_rmesh)
# controller functions
complete_controller = controller_cpp.Controller()
# lidar object
lidar = cgal.Lidar()
lidar = lidar.view_axis(np.array([1, 0, 0]))
lidar = lidar.up_axis(np.array([0, 0, 1]))
lidar = lidar.fov(np.deg2rad(np.array([7, 7]))).dist(2).num_steps(3)
# raycaster from c++
caster = cgal.RayCaster(v, f)
# save a bunch of parameters to the HDF5 file
with h5py.File(output_filename, 'w-') as hf:
sim_group = hf.create_group("simulation_parameters")
sim_group['AbsTol'] = AbsTol
sim_group['RelTol'] = RelTol
dumbbell_group = sim_group.create_group("dumbbell")
dumbbell_group["m1"] = 500
dumbbell_group["m2"] = 500
dumbbell_group['l'] = 0.003
true_ast_group = sim_group.create_group("true_asteroid")
true_ast_group.create_dataset("vertices", data=v, compression=compression,
compression_opts=compression_opts)
true_ast_group.create_dataset("faces", data=f, compression=compression,
compression_opts=compression_opts)
true_ast_group['name'] = file_name
est_ast_group = sim_group.create_group("estimate_asteroid")
est_ast_group['surf_area'] = surf_area
est_ast_group['max_angle'] = max_angle
est_ast_group['min_angle'] = min_angle
est_ast_group['max_distance'] = max_distance
est_ast_group['max_radius'] = max_radius
est_ast_group.create_dataset('initial_vertices', data=est_ast_rmesh.get_verts(), compression=compression,
compression_opts=compression_opts)
est_ast_group.create_dataset("initial_faces", data=est_ast_rmesh.get_faces(), compression=compression,
compression_opts=compression_opts)
est_ast_group.create_dataset("initial_weight", data=est_ast_rmesh.get_weights(), compression=compression,
compression_opts=compression_opts)
lidar_group = sim_group.create_group("lidar")
lidar_group.create_dataset("view_axis", data=lidar.get_view_axis())
lidar_group.create_dataset("up_axis", data=lidar.get_up_axis())
lidar_group.create_dataset("fov", data=lidar.get_fov())
return (true_ast_meshdata, true_ast, complete_controller, est_ast_meshdata,
est_ast_rmesh, est_ast, lidar, caster, max_angle,
dum, AbsTol, RelTol)
def initialize_refinement(output_filename, ast_name="castalia"):
"""Initialize all the things for the simulation to refine the landing site
Output_file : the actual HDF5 file to save the data/parameters to
This will load the estimated asteroid shape, the true asteroid and a bumpy
version for use with the raycaster
"""
logger = logging.getLogger(__name__)
logger.info('Initialize asteroid and dumbbell objects')
AbsTol = 1e-9
RelTol = 1e-9
logger.info("Initializing Refinement : {} ".format(ast_name))
# open the file and recreate the objects
with h5py.File(output_filename, 'r') as hf:
state_keys = np.array(utilities.sorted_nicely(list(hf['state'].keys())))
explore_tf = hf['time'][()][-1]
# explore_tf = int(state_keys[-1])
explore_state = hf['state/' + str(explore_tf)][()]
explore_Ra = hf['Ra/' + str(explore_tf)][()]
explore_v = hf['reconstructed_vertex/' + str(explore_tf)][()]
explore_f = hf['reconstructed_face/' + str(explore_tf)][()]
explore_w = hf['reconstructed_weight/' + str(explore_tf)][()]
explore_name = hf['simulation_parameters/true_asteroid/name'][()][:-4]
explore_m1 = hf['simulation_parameters/dumbbell/m1'][()]
explore_m2 = hf['simulation_parameters/dumbbell/m2'][()]
explore_l = hf['simulation_parameters/dumbbell/l'][()]
explore_AbsTol = hf['simulation_parameters/AbsTol'][()]
explore_RelTol = hf['simulation_parameters/RelTol'][()]
explore_true_vertices = hf['simulation_parameters/true_asteroid/vertices'][()]
explore_true_faces = hf['simulation_parameters/true_asteroid/faces'][()]
# switch based on asteroid name
if ast_name == "castalia":
refine_file_name = "castalia_bump.obj"
v, f = wavefront.read_obj('./data/shape_model/CASTALIA/castalia_bump_2.obj')
else:
print("Incorrect asteroid name")
return 1
# true asteroid and dumbbell
true_ast_meshdata = mesh_data.MeshData(explore_true_vertices, explore_true_faces)
true_ast = asteroid.Asteroid(explore_name, true_ast_meshdata)
dum = dumbbell.Dumbbell(m1=explore_m1, m2=explore_m2, l=explore_l)
# estimated asteroid (starting as an ellipse)
if (ast_name == "castalia" or ast_name == "itokawa"
or ast_name == "golevka" or ast_name == "52760"):
surf_area = 0.0005
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_radius = 0.03
max_distance = 0.5
est_ast_meshdata = mesh_data.MeshData(explore_v, explore_f)
# set the weight of everything to a big number
# new_w = np.full_like(explore_w, 10)
est_ast_rmesh = reconstruct.ReconstructMesh(est_ast_meshdata, explore_w)
est_ast = asteroid.Asteroid(ast_name, est_ast_rmesh)
# controller functions
complete_controller = controller_cpp.Controller()
# lidar object
lidar = cgal.Lidar()
lidar = lidar.view_axis(np.array([1, 0, 0]))
lidar = lidar.up_axis(np.array([0, 0, 1]))
lidar = lidar.fov(np.deg2rad(np.array([2, 2]))).dist(2).num_steps(3)
# raycaster from c++ using the bumpy asteroid
caster = cgal.RayCaster(v, f)
return (true_ast_meshdata, true_ast, complete_controller, est_ast_meshdata,
est_ast_rmesh, est_ast, lidar, caster, max_angle,
dum, AbsTol, RelTol)
def initialize_castalia(output_filename):
"""Initialize all the things for the simulation
Output_file : the actual HDF5 file to save the data/parameters to
"""
logger = logging.getLogger(__name__)
logger.info('Initialize asteroid and dumbbell objects')
AbsTol = 1e-9
RelTol = 1e-9
ast_name = "castalia"
file_name = "castalia.obj"
# true asteroid and dumbbell
v, f = wavefront.read_obj('./data/shape_model/CASTALIA/castalia.obj')
true_ast_meshdata = mesh_data.MeshData(v, f)
true_ast = asteroid.Asteroid(ast_name, true_ast_meshdata)
dum = dumbbell.Dumbbell(m1=500, m2=500, l=0.003)
# estimated asteroid (starting as an ellipse)
surf_area = 0.01
max_angle = np.sqrt(surf_area / true_ast.get_axes()[0]**2)
min_angle = 10
max_distance = 0.5
max_radius = 0.03
ellipsoid = surface_mesh.SurfMesh(true_ast.get_axes()[0], true_ast.get_axes()[1], true_ast.get_axes()[2],
min_angle, max_radius, max_distance)
v_est = ellipsoid.get_verts()
f_est = ellipsoid.get_faces()
est_ast_meshdata = mesh_data.MeshData(v_est, f_est)
est_ast_rmesh = reconstruct.ReconstructMesh(est_ast_meshdata)
est_ast = asteroid.Asteroid(ast_name, est_ast_rmesh)
# controller functions
complete_controller = controller_cpp.Controller()
# lidar object
lidar = cgal.Lidar()
lidar = lidar.view_axis(np.array([1, 0, 0]))
lidar = lidar.up_axis(np.array([0, 0, 1]))
lidar = lidar.fov(np.deg2rad(np.array([7, 7]))).dist(2).num_steps(3)
# raycaster from c++
caster = cgal.RayCaster(v, f)
# save a bunch of parameters to the HDF5 file
with h5py.File(output_filename, 'w-') as hf:
sim_group = hf.create_group("simulation_parameters")
sim_group['AbsTol'] = AbsTol
sim_group['RelTol'] = RelTol
dumbbell_group = sim_group.create_group("dumbbell")
dumbbell_group["m1"] = 500
dumbbell_group["m2"] = 500
dumbbell_group['l'] = 0.003
true_ast_group = sim_group.create_group("true_asteroid")
true_ast_group.create_dataset("vertices", data=v, compression=compression,
compression_opts=compression_opts)
true_ast_group.create_dataset("faces", data=f, compression=compression,
compression_opts=compression_opts)
true_ast_group['name'] = file_name
est_ast_group = sim_group.create_group("estimate_asteroid")
est_ast_group['surf_area'] = surf_area
est_ast_group['max_angle'] = max_angle
est_ast_group['min_angle'] = min_angle
est_ast_group['max_distance'] = max_distance
est_ast_group['max_radius'] = max_radius
est_ast_group.create_dataset('initial_vertices', data=est_ast_rmesh.get_verts(), compression=compression,
compression_opts=compression_opts)
est_ast_group.create_dataset("initial_faces", data=est_ast_rmesh.get_faces(), compression=compression,
compression_opts=compression_opts)
est_ast_group.create_dataset("initial_weight", data=est_ast_rmesh.get_weights(), compression=compression,
compression_opts=compression_opts)
lidar_group = sim_group.create_group("lidar")
lidar_group.create_dataset("view_axis", data=lidar.get_view_axis())
lidar_group.create_dataset("up_axis", data=lidar.get_up_axis())
lidar_group.create_dataset("fov", data=lidar.get_fov())
return (true_ast_meshdata, true_ast, complete_controller, est_ast_meshdata,
est_ast_rmesh, est_ast, lidar, caster, max_angle,
dum, AbsTol, RelTol)
def simulate(output_filename="/tmp/exploration_sim.hdf5"):
"""Actually run the simulation around the asteroid
"""
logger = logging.getLogger(__name__)
num_steps = int(max_steps)
time = np.arange(0, num_steps)
t0, tf = time[0], time[-1]
dt = time[1] - time[0]
# define the initial condition in the inertial frame
initial_pos = np.array([1.5, 0, 0])
initial_vel = np.array([0, 0, 0])
initial_R = attitude.rot3(np.pi / 2).reshape(-1)
initial_w = np.array([0, 0, 0])
initial_state = np.hstack((initial_pos, initial_vel, initial_R, initial_w))
# initialize the simulation objects
(true_ast_meshdata, true_ast, complete_controller,
est_ast_meshdata, est_ast_rmesh, est_ast, lidar, caster, max_angle, dum,
AbsTol, RelTol) = initialize(output_filename)
with h5py.File(output_filename, 'a') as hf:
hf.create_dataset('time', data=time, compression=compression,
compression_opts=compression_opts)
hf.create_dataset("initial_state", data=initial_state, compression=compression,
compression_opts=compression_opts)
v_group = hf.create_group("reconstructed_vertex")
f_group = hf.create_group("reconstructed_face")
w_group = hf.create_group("reconstructed_weight")
state_group = hf.create_group("state")
targets_group = hf.create_group("targets")
Ra_group = hf.create_group("Ra")
inertial_intersections_group = hf.create_group("inertial_intersections")
asteroid_intersections_group = hf.create_group("asteroid_intersections")
# initialize the ODE function
system = integrate.ode(eoms.eoms_controlled_inertial_pybind)
system.set_integrator("lsoda", atol=AbsTol, rtol=RelTol, nsteps=10000)
system.set_initial_value(initial_state, t0)
system.set_f_params(true_ast, dum, complete_controller, est_ast_rmesh)
point_cloud = defaultdict(list)
ii = 1
while system.successful() and system.t < tf:
# integrate the system
t = (system.t + dt)
state = system.integrate(system.t + dt)
logger.info("Step: {} Time: {}".format(ii, t))
if not (np.floor(t) % 1):
# logger.info("RayCasting at t: {}".format(t))
targets = lidar.define_targets(state[0:3],
state[6:15].reshape((3, 3)),
np.linalg.norm(state[0:3]))
# update the asteroid inside the caster
nv = true_ast.rotate_vertices(t)
Ra = true_ast.rot_ast2int(t)
# this also updates true_ast (both point to same data)
caster.update_mesh(nv, true_ast.get_faces())
# do the raycasting
intersections = caster.castarray(state[0:3], targets)
# reconstruct the mesh with new measurements
# convert the intersections to the asteroid frame
ast_ints = []
for pt in intersections:
if np.linalg.norm(pt) < 1e-9:
logger.info("No intersection for this point")
pt_ast = np.array([np.nan, np.nan, np.nan])
else:
pt_ast = Ra.T.dot(pt)
ast_ints.append(pt_ast)
# convert the intersections to the asteroid frame
ast_ints = np.array(ast_ints)
est_ast_rmesh.update(ast_ints, max_angle)
# save data to HDF5
v_group.create_dataset(str(ii), data=est_ast_rmesh.get_verts(), compression=compression,
compression_opts=compression_opts)
f_group.create_dataset(str(ii), data=est_ast_rmesh.get_faces(), compression=compression,
compression_opts=compression_opts)
w_group.create_dataset(str(ii), data=est_ast_rmesh.get_weights(), compression=compression,
compression_opts=compression_opts)
state_group.create_dataset(str(ii), data=state, compression=compression,
compression_opts=compression_opts)
targets_group.create_dataset(str(ii), data=targets, compression=compression,
compression_opts=compression_opts)
Ra_group.create_dataset(str(ii), data=Ra, compression=compression,
compression_opts=compression_opts)
inertial_intersections_group.create_dataset(str(ii), data=intersections, compression=compression,
compression_opts=compression_opts)
asteroid_intersections_group.create_dataset(str(ii), data=ast_ints, compression=compression,
compression_opts=compression_opts)
ii += 1
def simulate_control(output_filename="/tmp/exploration_sim.hdf5",
asteroid_name="castalia"):
"""Run the simulation with the control cost added in
"""
logger = logging.getLogger(__name__)
num_steps = int(max_steps)
time = np.arange(0, num_steps)
t0, tf = time[0], time[-1]
dt = time[1] - time[0]
# initialize the simulation objects
(true_ast_meshdata, true_ast, complete_controller,
est_ast_meshdata, est_ast_rmesh, est_ast, lidar, caster, max_angle, dum,
AbsTol, RelTol) = initialize_asteroid(output_filename, asteroid_name)
# change the initial condition based on the asteroid name
if true_ast.get_name() == "itokawa":
initial_pos = np.array([1.5, 0, 0]) # castalia
elif true_ast.get_name() == "castalia":
initial_pos = np.array([1.5, 0, 0]) # itokawa
elif true_ast.get_name() == "eros":
initial_pos = np.array([19, 0 , 0]) # eros needs more time (greater than 15000
elif true_ast.get_name() == "phobos":
initial_pos = np.array([70, 0, 0])
elif true_ast.get_name() == "lutetia":
initial_pos = np.array([70, 0, 0])
elif true_ast.get_name() == "geographos":
initial_pos = np.array([5, 0, 0])
elif true_ast.get_name() == "bacchus":
initial_pos = np.array([1.5, 0, 0])
elif true_ast.get_name() == "52760":
initial_pos = np.array([3, 0, 0])
else:
print("Incorrect asteroid selected")
return 1
# define the initial condition in the inertial frame
initial_vel = np.array([0, 0, 0])
initial_R = attitude.rot3(np.pi / 2).reshape(-1)
initial_w = np.array([0, 0, 0])
initial_state = np.hstack((initial_pos, initial_vel, initial_R, initial_w))
with h5py.File(output_filename, 'a') as hf:
hf.create_dataset('time', data=time, compression=compression,
compression_opts=compression_opts)
hf.create_dataset("initial_state", data=initial_state, compression=compression,
compression_opts=compression_opts)
v_group = hf.create_group("reconstructed_vertex")
f_group = hf.create_group("reconstructed_face")
w_group = hf.create_group("reconstructed_weight")
state_group = hf.create_group("state")
targets_group = hf.create_group("targets")
Ra_group = hf.create_group("Ra")
inertial_intersections_group = hf.create_group("inertial_intersections")
asteroid_intersections_group = hf.create_group("asteroid_intersections")
# initialize the ODE function
system = integrate.ode(eoms.eoms_controlled_inertial_control_cost_pybind)
system.set_integrator("lsoda", atol=AbsTol, rtol=RelTol, nsteps=10000)
# system.set_integrator("vode", nsteps=5000, method='bdf')
system.set_initial_value(initial_state, t0)
system.set_f_params(true_ast, dum, complete_controller, est_ast_rmesh, est_ast)
point_cloud = defaultdict(list)
ii = 1
while system.successful() and system.t < tf:
t = system.t + dt
# TODO Make sure the asteroid (est and truth) are being rotated by ROT3(t)
state = system.integrate(system.t + dt)
logger.info("Step: {} Time: {} Pos: {} Uncertainty: {}".format(ii, t,
state[0:3],
np.sum(est_ast_rmesh.get_weights())))
if not (np.floor(t) % 1):
targets = lidar.define_targets(state[0:3],
state[6:15].reshape((3, 3)),
np.linalg.norm(state[0:3]))
# update the asteroid inside the caster
nv = true_ast.rotate_vertices(t)
Ra = true_ast.rot_ast2int(t)
caster.update_mesh(nv, true_ast.get_faces())
# do the raycasting
intersections = caster.castarray(state[0:3], targets)
# reconstruct the mesh with new measurements
# convert the intersections to the asteroid frame
ast_ints = []
for pt in intersections:
if np.linalg.norm(pt) < 1e-9:
logger.info("No intersection for this point")
pt_ast = np.array([np.nan, np.nan, np.nan])
else:
pt_ast = Ra.T.dot(pt)
ast_ints.append(pt_ast)
ast_ints = np.array(ast_ints)
# this updates the estimated asteroid mesh used in both rmesh and est_ast
est_ast_rmesh.update(ast_ints, max_angle)
v_group.create_dataset(str(ii), data=est_ast_rmesh.get_verts(), compression=compression,
compression_opts=compression_opts)
f_group.create_dataset(str(ii), data=est_ast_rmesh.get_faces(), compression=compression,
compression_opts=compression_opts)
w_group.create_dataset(str(ii), data=est_ast_rmesh.get_weights(), compression=compression,
compression_opts=compression_opts)
state_group.create_dataset(str(ii), data=state, compression=compression,
compression_opts=compression_opts)
targets_group.create_dataset(str(ii), data=targets, compression=compression,
compression_opts=compression_opts)
Ra_group.create_dataset(str(ii), data=Ra, compression=compression,
compression_opts=compression_opts)
inertial_intersections_group.create_dataset(str(ii), data=intersections, compression=compression,
compression_opts=compression_opts)
asteroid_intersections_group.create_dataset(str(ii), data=ast_ints, compression=compression,
compression_opts=compression_opts)
ii += 1
logger.info("Exploration complete")
logger.info("All done")
def save_animation(filename, move_cam=False, mesh_weight=False,
output_path=tempfile.mkdtemp()):
"""Given a HDF5 file from simulate this will animate teh motion
"""
with h5py.File(filename, 'r') as hf:
# get the inertial state and asteroid mesh object
time = hf['time'][()]
state_group = hf['state']
state_keys = np.array(utilities.sorted_nicely(list(hf['state'].keys())))
intersections_group = hf['inertial_intersections']
# extract out the entire state and intersections
state = []
inertial_intersections = []
for key in state_keys:
state.append(state_group[key][()])
inertial_intersections.append(intersections_group[key][()])
state = np.array(state)
inertial_intersections = np.array(inertial_intersections)
# get the true asteroid from the HDF5 file
true_vertices = hf['simulation_parameters/true_asteroid/vertices'][()]
true_faces = hf['simulation_parameters/true_asteroid/faces'][()]
true_name = hf['simulation_parameters/true_asteroid/name'][()]
est_initial_vertices = hf['simulation_parameters/estimate_asteroid/initial_vertices'][()]
est_initial_faces = hf['simulation_parameters/estimate_asteroid/initial_faces'][()]
# think about a black background as well
mfig = graphics.mayavi_figure(bg=(0, 0, 0), size=(800,600), offscreen=True)
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces,
scalars=np.squeeze(hf['simulation_parameters/estimate_asteroid/initial_weight'][()]),
color=None, colormap='viridis')
else:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces)
xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0))
yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0))
zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1))
ast_axes = (xaxis, yaxis, zaxis)
# initialize a dumbbell object
dum = dumbbell.Dumbbell(hf['simulation_parameters/dumbbell/m1'][()],
hf['simulation_parameters/dumbbell/m2'][()],
hf['simulation_parameters/dumbbell/l'][()])
# com, dum_axes = graphics.draw_dumbbell_mayavi(state[0, :], dum, mfig)
if move_cam:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.02,
opacity=0.5)
else:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.1)
pc_points = graphics.mayavi_points3d(mfig, inertial_intersections[0],
color=(0, 0, 1), scale_factor=0.03)
# add some text objects
time_text = graphics.mlab.text(0.1, 0.1, "t: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
weight_text = graphics.mlab.text(0.1, 0.2, "w: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
# mayavi_objects = (mesh, ast_axes, com, dum_axes, pc_lines)
mayavi_objects = (mesh, com, pc_points, time_text, weight_text)
print("Images will be saved to {}".format(output_path))
animation.inertial_asteroid_trajectory_cpp_save(time, state, inertial_intersections,
filename, mayavi_objects, move_cam=move_cam,
mesh_weight=mesh_weight,
output_path=output_path,
magnification=4)
# now call ffmpeg
fps = 60
name = os.path.join(output_path, 'exploration.mp4')
ffmpeg_fname = os.path.join(output_path, '%07d.jpg')
cmd = "ffmpeg -framerate {} -i {} -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2' {}".format(fps, ffmpeg_fname, name)
print(cmd)
subprocess.check_output(['bash', '-c', cmd])
# remove folder now
for file in os.listdir(output_path):
file_path = os.path.join(output_path, file)
if file_path.endswith('.jpg'):
os.remove(file_path)
def animate(filename, move_cam=False, mesh_weight=False, save_animation=False):
"""Given a HDF5 file from simulate this will animate teh motion
"""
# TODO Animate the changing of the mesh itself as a function of time
with h5py.File(filename, 'r') as hf:
# get the inertial state and asteroid mesh object
# time = hf['time'][()]
state_group = hf['state']
state_keys = np.array(utilities.sorted_nicely(list(hf['state'].keys())))
time = [int(t) for t in state_keys];
intersections_group = hf['inertial_intersections']
# extract out the entire state and intersections
state = []
inertial_intersections = []
for key in state_keys:
state.append(state_group[key][()])
inertial_intersections.append(intersections_group[key][()])
state = np.array(state)
inertial_intersections = np.array(inertial_intersections)
# get the true asteroid from the HDF5 file
true_vertices = hf['simulation_parameters/true_asteroid/vertices'][()]
true_faces = hf['simulation_parameters/true_asteroid/faces'][()]
true_name = hf['simulation_parameters/true_asteroid/name'][()]
est_initial_vertices = hf['simulation_parameters/estimate_asteroid/initial_vertices'][()]
est_initial_faces = hf['simulation_parameters/estimate_asteroid/initial_faces'][()]
# think about a black background as well
mfig = graphics.mayavi_figure(size=(800,600), bg=(0, 0, 0))
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces,
scalars=np.squeeze(hf['simulation_parameters/estimate_asteroid/initial_weight'][()]),
color=None, colormap='viridis')
else:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces)
xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0))
yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0))
zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1))
ast_axes = (xaxis, yaxis, zaxis)
# initialize a dumbbell object
dum = dumbbell.Dumbbell(hf['simulation_parameters/dumbbell/m1'][()],
hf['simulation_parameters/dumbbell/m2'][()],
hf['simulation_parameters/dumbbell/l'][()])
# com, dum_axes = graphics.draw_dumbbell_mayavi(state[0, :], dum, mfig)
if move_cam:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.02,
opacity=0.5)
else:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.1)
pc_points = graphics.mayavi_points3d(mfig, inertial_intersections[0],
color=(0, 0, 1), scale_factor=0.03)
# add some text objects
time_text = graphics.mlab.text(0.1, 0.1, "t: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
weight_text = graphics.mlab.text(0.1, 0.2, "w: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
# mayavi_objects = (mesh, ast_axes, com, dum_axes, pc_lines)
mayavi_objects = (mesh, com, pc_points, time_text, weight_text)
animation.inertial_asteroid_trajectory_cpp(time, state, inertial_intersections,
filename, mayavi_objects, move_cam=move_cam,
mesh_weight=mesh_weight)
graphics.mlab.show()
def animate_refinement(filename, move_cam=False, mesh_weight=False, save_animation=False):
"""Given a HDF5 file from simulate this will animate teh motion
"""
# TODO Animate the changing of the mesh itself as a function of time
with h5py.File(filename, 'r') as hf:
# get the inertial state and asteroid mesh object
# time = hf['time'][()]
state_group = hf['refinement/state']
state_keys = np.array(utilities.sorted_nicely(list(hf['refinement/state'].keys())))
time = [int(t) for t in state_keys];
intersections_group = hf['refinement/inertial_intersections']
# extract out the entire state and intersections
state = []
inertial_intersections = []
for key in state_keys:
state.append(state_group[key][()])
inertial_intersections.append(intersections_group[key][()])
state = np.array(state)
inertial_intersections = np.array(inertial_intersections)
# get the true asteroid from the HDF5 file
true_vertices = hf['simulation_parameters/true_asteroid/vertices'][()]
true_faces = hf['simulation_parameters/true_asteroid/faces'][()]
true_name = hf['simulation_parameters/true_asteroid/name'][()]
est_initial_vertices = hf['simulation_parameters/estimate_asteroid/initial_vertices'][()]
est_initial_faces = hf['simulation_parameters/estimate_asteroid/initial_faces'][()]
# think about a black background as well
mfig = graphics.mayavi_figure(bg=(0, 0 ,0), size=(800,600))
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces,
scalars=np.squeeze(hf['simulation_parameters/estimate_asteroid/initial_weight'][()]),
color=None, colormap='viridis')
else:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces)
xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0))
yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0))
zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1))
ast_axes = (xaxis, yaxis, zaxis)
# initialize a dumbbell object
dum = dumbbell.Dumbbell(hf['simulation_parameters/dumbbell/m1'][()],
hf['simulation_parameters/dumbbell/m2'][()],
hf['simulation_parameters/dumbbell/l'][()])
# com, dum_axes = graphics.draw_dumbbell_mayavi(state[0, :], dum, mfig)
if move_cam:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.02,
opacity=0.5)
else:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.1)
pc_points = graphics.mayavi_points3d(mfig, inertial_intersections[0],
color=(0, 0, 1), scale_factor=0.03)
# add some text objects
time_text = graphics.mlab.text(0.1, 0.1, "t: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
weight_text = graphics.mlab.text(0.1, 0.2, "w: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
# mayavi_objects = (mesh, ast_axes, com, dum_axes, pc_lines)
mayavi_objects = (mesh, com, pc_points, time_text, weight_text)
animation.inertial_asteroid_refinement_cpp(time, state, inertial_intersections,
filename, mayavi_objects, move_cam=move_cam,
mesh_weight=mesh_weight)
graphics.mlab.show()
def animate_landing(filename, move_cam=False, mesh_weight=False):
"""Animation for the landing portion of simulation
"""
with h5py.File(filename, 'r') as hf:
time = hf['landing/time'][()]
state_group = hf['landing/state']
state_keys = np.array(utilities.sorted_nicely(list(state_group.keys())))
state = []
for key in state_keys:
state.append(state_group[key][()])
state=np.array(state)
mfig = graphics.mayavi_figure(bg=(0, 0, 0),size=(800, 600))
# option for the mesh weight
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, hf['landing/vertices'][()], hf['landing/faces'][()],
scalars=np.squeeze(hf['landing/weight'][()]),
color=None, colormap='viridis')
else:
mesh = graphics.mayavi_addMesh(mfig, hf['landing/vertices'][()], hf['landing/faces'][()])
xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0))
yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0))
zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1))
ast_axes = (xaxis, yaxis, zaxis)
if move_cam:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.02,
opacity=0.5)
else:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.1)
# add some text objects
time_text = graphics.mlab.text(0.1, 0.1, "t: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
weight_text = graphics.mlab.text(0.1, 0.2, "w: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
mayavi_objects = (mesh, com, time_text, weight_text)
animation.inertial_asteroid_landing_cpp(time, state, filename, mayavi_objects,
move_cam=move_cam, mesh_weight=mesh_weight)
graphics.mlab.show()
def save_animate_landing(filename,output_path,move_cam=False, mesh_weight=False):
"""Save the landing animation
"""
with h5py.File(filename, 'r') as hf:
time = hf['landing/time'][()]
state_group = hf['landing/state']
state_keys = np.array(utilities.sorted_nicely(list(state_group.keys())))
state = []
for key in state_keys:
state.append(state_group[key][()])
state=np.array(state)
mfig = graphics.mayavi_figure(bg=(0, 0, 0), size=(800, 600), offscreen=True)
# option for the mesh weight
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, hf['landing/vertices'][()], hf['landing/faces'][()],
scalars=np.squeeze(hf['landing/weight'][()]),
color=None, colormap='viridis')
else:
mesh = graphics.mayavi_addMesh(mfig, hf['landing/vertices'][()], hf['landing/faces'][()])
xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0))
yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0))
zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1))
ast_axes = (xaxis, yaxis, zaxis)
if move_cam:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.02,
opacity=0.5)
else:
com = graphics.mayavi_addPoint(mfig, state[0, 0:3],
color=(1, 0, 0), radius=0.1)
# add some text objects
time_text = graphics.mlab.text(0.1, 0.1, "t: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
weight_text = graphics.mlab.text(0.1, 0.2, "w: {:8.1f}".format(0), figure=mfig,
color=(1, 1, 1), width=0.05)
mayavi_objects = (mesh, com, time_text, weight_text)
print("Images will be saved to {}".format(output_path))
animation.inertial_asteroid_landing_cpp_save(time, state, filename, mayavi_objects,
move_cam=move_cam, mesh_weight=mesh_weight,
output_path=output_path,
magnification=4)
# now call ffmpeg
fps = 60
name = os.path.join(output_path, 'landing.mp4')
ffmpeg_fname = os.path.join(output_path, '%07d.jpg')
cmd = "ffmpeg -framerate {} -i {} -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2' {}".format(fps, ffmpeg_fname, name)
print(cmd)
subprocess.check_output(['bash', '-c', cmd])
# remove folder now
for file in os.listdir(output_path):
file_path = os.path.join(output_path, file)
if file_path.endswith('.jpg'):
os.remove(file_path)
def save_animate_refinement(filename, output_path, move_cam=False, mesh_weight=False):
"""Save the refinement animation
"""
# TODO Animate the changing of the mesh itself as a function of time
with h5py.File(filename, 'r') as hf:
# get the inertial state and asteroid mesh object
# time = hf['time'][()]
state_group = hf['refinement/state']
state_keys = np.array(utilities.sorted_nicely(list(hf['refinement/state'].keys())))
time = [int(t) for t in state_keys];
intersections_group = hf['refinement/inertial_intersections']
# extract out the entire state and intersections
state = []
inertial_intersections = []
for key in state_keys:
state.append(state_group[key][()])
inertial_intersections.append(intersections_group[key][()])
state = np.array(state)
inertial_intersections = np.array(inertial_intersections)
# get the true asteroid from the HDF5 file
true_vertices = hf['simulation_parameters/true_asteroid/vertices'][()]
true_faces = hf['simulation_parameters/true_asteroid/faces'][()]
true_name = hf['simulation_parameters/true_asteroid/name'][()]
est_initial_vertices = hf['simulation_parameters/estimate_asteroid/initial_vertices'][()]
est_initial_faces = hf['simulation_parameters/estimate_asteroid/initial_faces'][()]
# think about a black background as well
mfig = graphics.mayavi_figure(size=(800,600), offscreen=True, bg=(0 ,0 ,0))
if mesh_weight:
mesh = graphics.mayavi_addMesh(mfig, est_initial_vertices, est_initial_faces,
scalars=np.squeeze(hf['simulation_parameters/estimate_asteroid/initial_weight'][()]),
color=None, colormap='viridis')
else: