-
Notifications
You must be signed in to change notification settings - Fork 11
/
standalone.py
282 lines (230 loc) · 10.4 KB
/
standalone.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
#External Libraries
import numpy as np
from tqdm import tqdm
import os
import argparse
import sys
import time
def make_parser():
""" Input Parser """
parser = argparse.ArgumentParser(description='Standalone script for grasp filtering.')
parser.add_argument('--headless', type=bool, help='Running Program in headless mode',
default=False, action = argparse.BooleanOptionalAction)
parser.add_argument('--force_reset', type=bool, help='Force Reset of Isaac Sim',
default=False, action = argparse.BooleanOptionalAction)
parser.add_argument('--json_dir', type=str, help='Directory of Grasp Information', default='')
parser.add_argument('--gripper_dir', type=str, help='Directory of Gripper urdf/usd', default='')
parser.add_argument('--objects_dir', type=str, help='Directory of Object usd', default='')
parser.add_argument('--output_dir', type=str, help='Output directroy for filterd grasps', default='')
parser.add_argument('--num_w', type=int, help='Number of Workstations used in the simulation', default=150)
parser.add_argument('--device', type=int, help='Gpu to use', default=0)
parser.add_argument('--test_time', type=int, help='Total time for each grasp test', default=3)
parser.add_argument('--print_results', type=bool, help='Enable printing of grasp statistics after filtering a document',
default=False, action = argparse.BooleanOptionalAction)
parser.add_argument('--controller', type=str,
help='Gripper Controller to use while testing, should match the controller dictionary in the Manager Class',
default='default')
parser.add_argument('--/log/level', type=str, help='isaac sim logging arguments', default='', required=False)
parser.add_argument('--/log/fileLogLevel', type=str, help='isaac sim logging arguments', default='', required=False)
parser.add_argument('--/log/outputStreamLevel', type=str, help='isaac sim logging arguments', default='', required=False)
return parser
#Parser
parser = make_parser()
args = parser.parse_args()
head = args.headless
force_reset = args.force_reset
print(args.controller)
#launch Isaac Sim before any other imports
from omni.isaac.kit import SimulationApp
config= {
"headless": head,
'max_bounces':0,
'fast_shutdown': True,
'max_specular_transmission_bounces':0,
'physics_gpu': args.device,
'active_gpu': args.device
}
simulation_app = SimulationApp(config) # we can also run as headless.
#World Imports
from omni.isaac.core import World
from omni.isaac.core.utils.prims import define_prim
from omni.isaac.cloner import GridCloner # import Cloner interface
from omni.isaac.core.utils.stage import add_reference_to_stage
# Custom Classes
from managers import Manager
from views import View
#Omni Libraries
from omni.isaac.core.utils.stage import add_reference_to_stage,open_stage, save_stage
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.prims import get_prim_children, get_prim_path, get_prim_at_path
from omni.isaac.core.utils.transformations import pose_from_tf_matrix
def import_gripper(work_path,usd_path, EF_axis):
""" Imports Gripper to World
Args:
work_path: prim_path of workstation
usd_path: path to .usd file of gripper
EF_axis: End effector axis needed for proper positioning of gripper
"""
T_EF = np.array([[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]])
if (EF_axis == 1):
T_EF = np.array([[ 0,0,1,0],
[ 0,1,0,0],
[-1,0,0,0],
[0,0,0,1]])
elif (EF_axis == 2):
T_EF = np.array([[1, 0,0,0],
[0, 0,1,0],
[0,-1,0,0],
[0, 0,0,1]])
elif (EF_axis == 3):
T_EF = np.array([[1, 0, 0,0],
[0,-1, 0,0],
[0, 0,-1,0],
[0, 0, 0,1]])
elif (EF_axis == -1):
T_EF = np.array([[0,0,-1,0],
[0,1, 0,0],
[1,0, 0,0],
[0,0, 0,1]])
elif (EF_axis == -2):
T_EF = np.array([[1,0, 0,0],
[0,0,-1,0],
[0,1, 0,0],
[0,0, 0,1]])
#Robot Pose
gripper_pose= pose_from_tf_matrix(T_EF.astype(float))
# Adding Robot usd
add_reference_to_stage(usd_path=usd_path, prim_path=work_path+"/gripper")
robot = world.scene.add(Articulation(prim_path = work_path+"/gripper", name="gripper",
position = gripper_pose[0], orientation = gripper_pose[1], enable_dof_force_sensors = True))
robot.set_enabled_self_collisions(False)
return robot, T_EF
def import_object(work_path, usd_path):
""" Import Object .usd to World
Args:
work_path: prim_path to workstation
usd_path: path to .usd file of object
"""
add_reference_to_stage(usd_path=usd_path, prim_path=work_path+"/object")
object_parent = world.scene.add(GeometryPrim(prim_path = work_path+"/object", name="object"))
l = get_prim_children(object_parent.prim)
#print(l)
prim = get_prim_at_path(work_path+"/object"+ '/base_link/collisions/mesh_0')
'''
MassAPI = UsdPhysics.MassAPI.Get(world.stage, prim.GetPath())
try:
og_mass = MassAPI.GetMassAttr().Get()
if og_mass ==0:
og_mass = 1
print("Failure reading object mass, setting to default value of 1 kg.")
except:
og_mass = 1
print("Failure reading object mass, setting to default value of 1 kg.")
# Create Rigid Body attribute
og_mass = 1
'''
object_prim = RigidPrim(prim_path= get_prim_path(l[0]))
mass= 1 #Deprecated use of mass for gravity
return object_parent, mass
if __name__ == "__main__":
# Directories
json_directory = args.json_dir
grippers_directory = args.gripper_dir
objects_directory = args.objects_dir
output_directory = args.output_dir
if not os.path.exists(json_directory):
raise ValueError("Json directory not given correctly")
elif not os.path.exists(grippers_directory):
raise ValueError("Grippers directory not given correctly")
elif not os.path.exists(objects_directory):
raise ValueError("Objects directory not given correctly")
elif not os.path.exists(output_directory):
raise ValueError("Output directory not given correctly")
# Testing Hyperparameters
num_w = args.num_w
test_time = args.test_time
verbose = args.print_results
controller = args.controller
#physics_dt = 1/120
world = World(set_defaults = False)
#Debugging
render = not head
#Load json files
json_files = [pos_json for pos_json in os.listdir(json_directory) if pos_json.endswith('.json')]
for j in json_files:
#path to output .json file
out_path = os.path.join(output_directory,j)
if(os.path.exists(out_path)): #Skip completed
continue
# Initialize Manager
manager = Manager(os.path.join(json_directory,j), grippers_directory, objects_directory, controller)
#Create initial Workstation Prim
work_path = "/World/Workstation_0"
work_prim = define_prim(work_path)
#Contact names for collisions
contact_names = []
for i in manager.c_names:
contact_names.append(work_path[:-1]+"*"+"/gripper/" + i)
#Initialize Workstation
robot, T_EF = import_gripper(work_path, manager.gripper_path,manager.EF_axis)
object_parent, mass = import_object(work_path, manager.object_path)
#Clone
cloner = GridCloner(spacing = 1)
target_paths = []
for i in range(num_w):
target_paths.append(work_path[:-1]+str(i))
cloner.clone(source_prim_path = "/World/Workstation_0", prim_paths = target_paths,
copy_from_source = True, replicate_physics = True, base_env_path = "/World",
root_path = "/World/Workstation_")
# ISAAC SIM views initialization
viewer = View(work_path,contact_names,num_w, manager,world, test_time, mass)
#Reset World and create set first robot positions
world.reset()
# Print Robot DoFs
print(robot.dof_names)
viewer.dofs, viewer.current_poses, viewer.current_job_IDs = viewer.get_jobs(num_w)
# Set desired physics Context options
world.reset()
physicsContext = world.get_physics_context()
#physicsContext.set_solver_type("PGS")
physicsContext.set_physics_dt(manager.physics_dt)
physicsContext.enable_gpu_dynamics(True)
physicsContext.enable_stablization(True)
physicsContext.set_gravity(-9.81)
world.reset()
#Initialize views
viewer.grippers.initialize(world.physics_sim_view)
viewer.objects.initialize(world.physics_sim_view)
viewer.post_reset()
#world.pause()
#Run Sim
with tqdm(total=len(manager.completed)) as pbar:
while not all(manager.completed):
#print(mass)
world.step(render=render) # execute one physics step and one rendering step if not headless
#world.pause()
if pbar.n != np.sum(manager.completed): #Progress bar
pbar.update(np.sum(manager.completed)-pbar.n)
#Save new json with results
manager.save_json(out_path)
if (verbose):
manager.report_results()
#print("Reseting Environment")
#Reset World
if not force_reset:
print('Reseting Environment')
t = time.time()
world.stop()
world.clear_physics_callbacks()
world.clear()
t = time.time() -t
print('Reseted, time in seconds: ', t)
if force_reset:
os.execl(sys.executable, sys.executable, *sys.argv)
pass
simulation_app.close() # close Isaac Sim