file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
elharirymatteo/RANS/omniisaacgymenvs/tests/runner.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
from datetime import date
import sys
import unittest
import weakref
import omni.kit.test
from omni.kit.test import AsyncTestSuite
from omni.kit.test.async_unittest import AsyncTextTestRunner
import omni.ui as ui
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import btn_builder
from omni.kit.menu.utils import MenuItemDescription, add_menu_items
import omni.timeline
import omni.usd
from omniisaacgymenvs import RLExtension, get_instance
class GymRLTests(omni.kit.test.AsyncTestCase):
def __init__(self, *args, **kwargs):
super(GymRLTests, self).__init__(*args, **kwargs)
self.ext = get_instance()
async def _train(self, task, load=True, experiment=None, max_iterations=None):
task_idx = self.ext._task_list.index(task)
self.ext._task_dropdown.get_item_value_model().set_value(task_idx)
if load:
self.ext._on_load_world()
while True:
_, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status()
if files_loaded or total_files:
await omni.kit.app.get_app().next_update_async()
else:
break
for _ in range(100):
await omni.kit.app.get_app().next_update_async()
self.ext._render_dropdown.get_item_value_model().set_value(2)
overrides = None
if experiment is not None:
overrides = [f"experiment={experiment}"]
if max_iterations is not None:
if overrides is None:
overrides = [f"max_iterations={max_iterations}"]
else:
overrides += [f"max_iterations={max_iterations}"]
await self.ext._on_train_async(overrides=overrides)
async def test_train(self):
date_str = date.today()
tasks = self.ext._task_list
for task in tasks:
await self._train(task, load=True, experiment=f"{task}_{date_str}")
async def test_train_determinism(self):
date_str = date.today()
tasks = self.ext._task_list
for task in tasks:
for i in range(3):
await self._train(task, load=(i==0), experiment=f"{task}_{date_str}_{i}", max_iterations=100)
class TestRunner():
def __init__(self):
self._build_ui()
def _build_ui(self):
menu_items = [make_menu_item_description("RL Examples Tests", "RL Examples Tests", lambda a=weakref.proxy(self): a._menu_callback())]
add_menu_items(menu_items, "Isaac Examples")
self._window = omni.ui.Window(
"RL Examples Tests", width=250, height=0, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
main_stack = ui.VStack(spacing=5, height=0)
with main_stack:
dict = {
"label": "Run Tests",
"type": "button",
"text": "Run Tests",
"tooltip": "Run all tests",
"on_clicked_fn": self._run_tests,
}
btn_builder(**dict)
def _menu_callback(self):
self._window.visible = not self._window.visible
def _run_tests(self):
loader = unittest.TestLoader()
loader.SuiteClass = AsyncTestSuite
test_suite = AsyncTestSuite()
test_suite.addTests(loader.loadTestsFromTestCase(GymRLTests))
test_runner = AsyncTextTestRunner(verbosity=2, stream=sys.stdout)
async def single_run():
await test_runner.run(test_suite)
print("=======================================")
print(f"Running Tests")
print("=======================================")
asyncio.ensure_future(single_run())
TestRunner() | 4,254 | Python | 35.059322 | 141 | 0.607428 |
elharirymatteo/RANS/omniisaacgymenvs/utils/arrow3D.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional, Sequence
import numpy as np
from omni.isaac.core.materials.visual_material import VisualMaterial
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.core.materials import PhysicsMaterial
from omni.isaac.core.utils.string import find_unique_string_name
from pxr import UsdGeom, Gf
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omni.isaac.core.utils.stage import get_current_stage
from omniisaacgymenvs.utils.shape_utils import Arrow3D
class VisualArrow3D(XFormPrim, Arrow3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "visual_arrow".
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[float], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
Raises:
Exception: _description_
"""
def __init__(
self,
prim_path: str,
name: str = "visual_arrow",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
) -> None:
if visible is None:
visible = True
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
Arrow3D.__init__(
self, prim_path, body_radius, body_length, head_radius, head_length
)
self.setBodyRadius(body_radius)
self.setBodyLength(body_length)
self.setHeadRadius(head_radius)
self.setHeadLength(head_length)
self.updateExtent()
return
class FixedArrow3D(VisualArrow3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "fixed_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "fixed_arrow",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
) -> None:
if not is_prim_path_valid(prim_path):
# set default values if no physics material given
if physics_material is None:
static_friction = 0.2
dynamic_friction = 1.0
restitution = 0.0
physics_material_path = find_unique_string_name(
initial_name="/World/Physics_Materials/physics_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
physics_material = PhysicsMaterial(
prim_path=physics_material_path,
dynamic_friction=dynamic_friction,
static_friction=static_friction,
restitution=restitution,
)
VisualArrow3D.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
body_radius=body_radius,
body_length=body_length,
head_radius=head_radius,
head_length=head_length,
visual_material=visual_material,
)
# XFormPrim.set_collision_enabled(self, True)
# if physics_material is not None:
# FixedArrow.apply_physics_material(self, physics_material)
return
class DynamicArrow3D(RigidPrim, FixedArrow3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "dynamic_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
mass (Optional[float], optional): _description_. Defaults to None.
density (Optional[float], optional): _description_. Defaults to None.
linear_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
angular_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dynamic_sphere",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
mass: Optional[float] = None,
density: Optional[float] = None,
linear_velocity: Optional[Sequence[float]] = None,
angular_velocity: Optional[Sequence[float]] = None,
) -> None:
if not is_prim_path_valid(prim_path):
if mass is None:
mass = 0.02
FixedArrow3D.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
body_radius=body_radius,
body_length=body_length,
head_radius=head_radius,
head_length=head_length,
visual_material=visual_material,
physics_material=physics_material,
)
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
density=density,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 9,523 | Python | 40.051724 | 96 | 0.616297 |
elharirymatteo/RANS/omniisaacgymenvs/utils/plot_lab_data.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from matplotlib.ticker import AutoMinorLocator
from pathlib import Path
from utils.plot_experiment import plot_one_episode
import argparse
if __name__ == "__main__":
# Get load dir from arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"--load_dir", type=str, default=None, help="Directory to load data from"
)
args = parser.parse_args()
load_dir = Path(args.load_dir)
# load_dir = Path("./ros_lab_exp/7_9_23/dc_controller")
sub_dirs = [d for d in load_dir.iterdir() if d.is_dir()]
# sub_dirs = [d for d in sub_dirs if ("pose" not in str(d) and "kill3" not in str(d) and "new_pose" not in str(d))]
if sub_dirs:
latest_exp = max(sub_dirs, key=os.path.getmtime)
n_episodes = 1
else:
print("No experiments found in", load_dir)
exit()
for d in sub_dirs:
obs_path = os.path.join(d, "obs.npy")
actions_path = os.path.join(d, "act.npy")
if not os.path.exists(obs_path) or not os.path.exists(actions_path):
print("Required files not found in", d)
exit()
obs = np.load(obs_path, allow_pickle=True)
actions = np.load(actions_path)
# if obs is empty, skip this experiment and print warning
if not obs.any():
print(f"Empty obs file in {d}, skipping...")
continue
print("Plotting data for experiment:", d)
# transform the obs numpy array of dictionaries to numpy array of arrays
obs = np.array([o.flatten() for o in obs])
save_to = os.path.join(d, "plots/")
os.makedirs(save_to, exist_ok=True)
ep_data = {"act": actions, "obs": obs, "rews": []}
plot_one_episode(ep_data, save_to, show=False)
print("Done!")
| 2,145 | Python | 31.02985 | 119 | 0.614452 |
elharirymatteo/RANS/omniisaacgymenvs/utils/make_latex_table.py | import pandas as pd
import numpy as np
import os
RL_root = "RL"
DC_root = "DC-real"
exp_keys = ["AN","VN","UF","TD","RTF"]
ordered_metrics_keys = ["PA1","PA2","PSA","OA1","OA2","OSA","ALV","AAV","AAC","PT5","PT2","PT1","OT5","OT2","OT1"]
metrics_keys = ["PT5","PT2","PT1","OT5","OT2","OT1","ALV","AAV","AAC"]
colored_metrics = ["PT5","PT2","PT1","OT5","OT2","OT1"]
exp_names = os.listdir(RL_root)
exp_names.sort()
#columns = ["Controller","AN","ON","UF","TD","RTK","PA2","PA1","PSA","OA2","OA1","OSA","ALV","AAV","AAC","PT5","PT2","PT1","OT5","OT2","OT1"]
columns = ["Controller","AN","VN","UF","TD","RTF","PT5","PT2","PT1","OT5","OT2","OT1","ALV","AAV","AAC"]
table = pd.DataFrame(0, columns=columns, index=range(len(exp_names)*2))
ctable = pd.DataFrame("none", columns=columns, index=range(len(exp_names)*2))
colors_name = np.array(['ForestGreen',
'LimeGreen',
'Goldenrod',
'Orange',
'OrangeRed'])
cv1 = np.array([0,20,40,60,80])
cv2 = np.array([20,40,60,80,100])
i = 0
exp_name = "ideal"
exp_keys_names = []
exp_keys_values = []
table["Controller"][i] = "RL"
table["Controller"][i+len(exp_names)] = "LQR"
RL_baseline = np.load(os.path.join(RL_root,exp_name,"aggregated_results.npy"))
DC_baseline = np.load(os.path.join(DC_root,exp_name,"aggregated_results.npy"))
for j, metric in enumerate(ordered_metrics_keys):
if metric in metrics_keys:
if metric in colored_metrics:
table[metric][i] = int(RL_baseline[j]*100)
table[metric][i+len(exp_names)] = int(DC_baseline[j]*100)
ctable[metric][i] = 'black'
ctable[metric][i+len(exp_names)] = 'black'
else:
table[metric][i] = RL_baseline[j]
table[metric][i+len(exp_names)] = DC_baseline[j]
i = 1
for exp_name in exp_names:
if exp_name == "ideal":
continue
exp_keys_names = []
exp_keys_values = []
table["Controller"][i] = "RL"
table["Controller"][i+len(exp_names)] = "LQR"
for tmp in exp_name.split("-"):
exp_keys_name = tmp.split("_")[0]
exp_keys_values = float(tmp.split("_")[1])
table[exp_keys_name][i] = exp_keys_values
table[exp_keys_name][i+len(exp_names)] = exp_keys_values
RL_results = np.load(os.path.join(RL_root,exp_name,"aggregated_results.npy"))
DC_results = np.load(os.path.join(DC_root,exp_name,"aggregated_results.npy"))
RL_deltas = (RL_baseline - RL_results) / RL_baseline
DC_deltas = (DC_baseline - DC_results) / DC_baseline
for j, metric in enumerate(ordered_metrics_keys):
if metric in metrics_keys:
if metric in colored_metrics:
table[metric][i] = int(RL_results[j]*100)
table[metric][i+len(exp_names)] = int(DC_results[j]*100)
if RL_deltas[j] < 0:
RL_deltas[j] = 0
b1 = RL_deltas[j]*100 <= cv2
b2 = RL_deltas[j]*100 >= cv1
b = b1*b2
ctable[metric][i] = colors_name[b][0]
if DC_deltas[j] < 0:
DC_deltas[j] = 0
b1 = DC_deltas[j]*100 <= cv2
b2 = DC_deltas[j]*100 >= cv1
b = b1*b2
ctable[metric][i+len(exp_names)] = colors_name[b][0]
else:
table[metric][i] = RL_results[j]
table[metric][i+len(exp_names)] = DC_results[j]
i+=1
print(table)
print(ctable)
latex1 = table.to_latex(float_format="%.2f")
latex2 = ctable.to_latex(float_format="%.2f")
print(latex1)
print(latex2)
l1s = latex1.split("\n")
l2s = latex2.split("\n")
l3s = []
for i in range(4,40):
ll1s = l1s[i].split('&')
ll2s = l2s[i].split('&')
ll1s = [lll1s.strip() for lll1s in ll1s]
print(ll1s)
for j in range(2,7):
if (ll1s[j] == "0.00") or (ll1s[j] == "0"):
ll1s[j] = "-"
for j in range(7,13):
ll1s[j] = '\\textcolor{'+ll2s[j].strip()+'}{'+ll1s[j]+'}'
ll1s = ll1s[1:]
l3s.append('&'.join(ll1s))
l3s = l1s[:4]+l3s+l1s[40:]
header =["\\begin{tabular}{|l|l|ccccc|ccccccccc|}",
"\\toprule",
"\multirow{2}{*}{Conditions}& \multirow{2}{*}{Controllers} & \multicolumn{5}{c|}{Disturbances} & \multicolumn{9}{c|}{Metrics} \\",
"& & AN & VN & UF & TD & RTF & PT5 & PT2 & PT1 & OT5 & OT2 & OT1 & ALV & AAV & AAC \\",
"\midrule\hline",
]
data = [
'\multirow{2}{*}{Ideal} &'+l3s[4],
'&'+l3s[22]+'\hline\hline',
'\multirow{6}{*}{Velocity Noise} &'+l3s[19],
'&'+l3s[20],
'&'+l3s[21]+"\cline{2-16}",
'&'+l3s[37],
'&'+l3s[38],
'&'+l3s[39]+'\hline\hline',
'\multirow{8}{*}{Action Noise}&'+l3s[7],
'&'+l3s[8]+"\cline{2-16}",
'&'+l3s[25],
'&'+l3s[26]+'\hline\hline',
'\multirow{4}{*}{Constant Torque}&'+l3s[12],
'&'+l3s[13]+"\cline{2-16}",
'&'+l3s[30],
'&'+l3s[31]+'\hline\hline',
'\multirow{6}{*}{Constant Force}&'+l3s[14],
'&'+l3s[16],
'&'+l3s[18]+"\cline{2-16}",
'&'+l3s[32],
'&'+l3s[34],
'&'+l3s[36]+'\hline\hline',
'\multirow{4}{*}{Constant Force \& Torque}&'+l3s[15],
'&'+l3s[17]+"\cline{2-16}",
'&'+l3s[33],
'&'+l3s[35]+'\hline\hline',
'&'+l3s[9],
'&'+l3s[10],
'\multirow{6}{*}{Thruster Failures}&'+l3s[11]+"\cline{2-16}",
'&'+l3s[27],
'&'+l3s[28],
'&'+l3s[29]+'\hline\hline']
footer = ["\\bottomrule",
"\end{tabular}",
"}",
"\caption{",
"Description TBD. PT, OT higher",
"}",
"\label{tab:my_label}",
"\end{table*}",
]
latex3 = "\n".join(header+data+footer)
latexs = "\n".join(data)
print(latex3)
#print([ll1s[k] for k in range(7,13)])
#print([ll2s[k] for k in range(7,13)])
#print(['{\color{'+ll2s[k]+'}'+ll1s[k]+'}' for k in range(7,13)])
print(latexs)
| 5,632 | Python | 31.005682 | 141 | 0.543146 |
elharirymatteo/RANS/omniisaacgymenvs/utils/pin.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional, Sequence
import numpy as np
from omni.isaac.core.materials.visual_material import VisualMaterial
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.core.materials import PhysicsMaterial
from omni.isaac.core.utils.string import find_unique_string_name
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omniisaacgymenvs.utils.shape_utils import Pin
class VisualPin(XFormPrim, Pin):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "visual_arrow".
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[float], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
Raises:
Exception: _description_
"""
def __init__(
self,
prim_path: str,
name: str = "visual_pin",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
) -> None:
if visible is None:
visible = True
if visual_material is None:
if color is None:
color = np.array([0.5, 0.5, 0.5])
visual_prim_path = find_unique_string_name(
initial_name="/World/Looks/visual_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
visual_material = PreviewSurface(prim_path=visual_prim_path, color=color)
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
Pin.__init__(self, prim_path, ball_radius, poll_radius, poll_length)
VisualPin.apply_visual_material(self, visual_material)
self.setBallRadius(ball_radius)
self.setPollRadius(poll_radius)
self.setPollLength(poll_length)
return
class FixedPin(VisualPin):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "fixed_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "fixed_arrow",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
) -> None:
if not is_prim_path_valid(prim_path):
# set default values if no physics material given
if physics_material is None:
static_friction = 0.2
dynamic_friction = 1.0
restitution = 0.0
physics_material_path = find_unique_string_name(
initial_name="/World/Physics_Materials/physics_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
physics_material = PhysicsMaterial(
prim_path=physics_material_path,
dynamic_friction=dynamic_friction,
static_friction=static_friction,
restitution=restitution,
)
VisualPin.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
ball_radius=ball_radius,
poll_radius=poll_radius,
poll_length=poll_length,
visual_material=visual_material,
)
# XFormPrim.set_collision_enabled(self, True)
# if physics_material is not None:
# FixedArrow.apply_physics_material(self, physics_material)
return
class DynamicPin(RigidPrim, FixedPin):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "dynamic_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
mass (Optional[float], optional): _description_. Defaults to None.
density (Optional[float], optional): _description_. Defaults to None.
linear_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
angular_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dynamic_sphere",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
mass: Optional[float] = None,
density: Optional[float] = None,
linear_velocity: Optional[Sequence[float]] = None,
angular_velocity: Optional[Sequence[float]] = None,
) -> None:
if not is_prim_path_valid(prim_path):
if mass is None:
mass = 0.02
FixedPin.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
ball_radius=ball_radius,
poll_radius=poll_radius,
poll_length=poll_length,
visual_material=visual_material,
physics_material=physics_material,
)
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
density=density,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 9,545 | Python | 40.504348 | 96 | 0.612572 |
elharirymatteo/RANS/omniisaacgymenvs/utils/pin3D.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional, Sequence
import numpy as np
from omni.isaac.core.materials.visual_material import VisualMaterial
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.core.materials import PhysicsMaterial
from omni.isaac.core.utils.string import find_unique_string_name
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omniisaacgymenvs.utils.shape_utils import Pin3D
class VisualPin3D(XFormPrim, Pin3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "visual_arrow".
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[float], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
Raises:
Exception: _description_
"""
def __init__(
self,
prim_path: str,
name: str = "visual_pin",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
) -> None:
if visible is None:
visible = True
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
Pin3D.__init__(self, prim_path, ball_radius, poll_radius, poll_length)
self.setBallRadius(ball_radius)
self.setPollRadius(poll_radius)
self.setPollLength(poll_length)
return
class FixedPin3D(VisualPin3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "fixed_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "fixed_arrow",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
) -> None:
if not is_prim_path_valid(prim_path):
# set default values if no physics material given
if physics_material is None:
static_friction = 0.2
dynamic_friction = 1.0
restitution = 0.0
physics_material_path = find_unique_string_name(
initial_name="/World/Physics_Materials/physics_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
physics_material = PhysicsMaterial(
prim_path=physics_material_path,
dynamic_friction=dynamic_friction,
static_friction=static_friction,
restitution=restitution,
)
VisualPin3D.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
ball_radius=ball_radius,
poll_radius=poll_radius,
poll_length=poll_length,
visual_material=visual_material,
)
# XFormPrim.set_collision_enabled(self, True)
# if physics_material is not None:
# FixedArrow.apply_physics_material(self, physics_material)
return
class DynamicPin3D(RigidPrim, FixedPin3D):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "dynamic_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
mass (Optional[float], optional): _description_. Defaults to None.
density (Optional[float], optional): _description_. Defaults to None.
linear_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
angular_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dynamic_sphere",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
ball_radius: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
mass: Optional[float] = None,
density: Optional[float] = None,
linear_velocity: Optional[Sequence[float]] = None,
angular_velocity: Optional[Sequence[float]] = None,
) -> None:
if not is_prim_path_valid(prim_path):
if mass is None:
mass = 0.02
FixedPin3D.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
ball_radius=ball_radius,
poll_radius=poll_radius,
poll_length=poll_length,
visual_material=visual_material,
physics_material=physics_material,
)
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
density=density,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 9,104 | Python | 40.013513 | 96 | 0.615444 |
elharirymatteo/RANS/omniisaacgymenvs/utils/eval_metrics.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import pandas as pd
import numpy as np
def compute_average_linear_velocity(ep_data: dict) -> float:
"""Compute the average linear velocity of the agent.
Args:
ep_data (dict): Dictionary containing the data of an episode.
Returns:
float: Average linear velocity of the agent."""
return np.mean(np.linalg.norm(ep_data["obs"][:, :, 2:4], axis=2))
def compute_average_angular_velocity(ep_data: dict) -> float:
"""Compute the average angular velocity of the agent.
Args:
ep_data (dict): Dictionary containing the data of an episode.
Returns:
float: Average angular velocity of the agent."""
return np.mean(np.abs(ep_data["obs"][:, :, 4]))
def compute_average_action_count(ep_data: dict) -> float:
"""Compute the average number of actions taken by the agent.
Args:
ep_data (dict): Dictionary containing the data of an episode.
Returns:
float: Average number of actions taken by the agent."""
return np.mean(np.sum(ep_data["act"] != 0, axis=2))
def build_distance_dataframe(distances: np.ndarray, threshold: float) -> list:
distances_df = pd.DataFrame(
distances, columns=[f"Ep_{i}" for i in range(distances.shape[1])]
)
# get a boolean dataframe where True means that the distance is less than the threshold
less_than_thr_df = distances_df.lt(threshold)
threshold_2 = threshold / 2
less_than_thr2_df = distances_df.lt(threshold_2)
# get the index of the first True value for each episode and fill with -1 if there is no True value
first_less_than_thr_idxs = less_than_thr_df.idxmax().where(
less_than_thr_df.any(), -1
)
first_less_than_thr2_idxs = less_than_thr2_df.idxmax().where(
less_than_thr2_df.any(), -1
)
margin = threshold * 7.5
less_than_margin_df = distances_df.lt(margin)
return less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
def check_stay(
less_than_margin_df: pd.DataFrame,
first_less_than_thr_idxs: pd.DataFrame,
first_less_than_thr2_idxs: pd.DataFrame,
) -> list:
all_true_after_index = pd.DataFrame(index=less_than_margin_df.columns)
all_true_after_index["all_true"] = less_than_margin_df.apply(
lambda column: column.loc[first_less_than_thr_idxs[column.name] :].all(), axis=0
)
success_and_stay_rate = all_true_after_index.value_counts(normalize=True)
success_and_stay_rate = (
success_and_stay_rate[True] if True in success_and_stay_rate.index else 0
)
success_rate_thr = (first_less_than_thr_idxs > -1).mean() * 100
success_rate_thr2 = (first_less_than_thr2_idxs > -1).mean() * 100
return success_rate_thr, success_rate_thr2, success_and_stay_rate
def print_success(
success_rate_thr: float,
success_rate_thr2: float,
success_and_stay_rate: float,
threshold: float,
print_intermediate: bool = False,
) -> None:
if print_intermediate:
print(f"Success rate with threshold {threshold}: {success_rate_thr}")
print(f"Success rate with threshold {threshold/2}: {success_rate_thr2}")
print(
f"Success rate and stay with margin {threshold*7.5}: {success_and_stay_rate * 100}"
)
def get_GoToPose_success_rate_new(
ep_data: dict, threshold: float = 0.02, print_intermediate: bool = False
) -> dict:
"""Compute the success rate from the distances to the target.
Args:
distances (np.ndarray): Array of distances to the target for N episodes.
precision (float): Distance at which the target is considered reached.
Returns:
float: Success rate."""
distances = np.linalg.norm(ep_data["obs"][:, :, 6:8], axis=2)
dist = distances
avg_p005 = np.mean([dist < 0.05])
avg_p002 = np.mean([dist < 0.02])
avg_p001 = np.mean([dist < 0.01])
heading = np.abs(np.arctan2(ep_data["obs"][:, :, -1], ep_data["obs"][:, :, -2]))
avg_h005 = np.mean([heading < np.pi * 5 / 180])
avg_h002 = np.mean([heading < np.pi * 2 / 180])
avg_h001 = np.mean([heading < np.pi * 1 / 180])
if print_intermediate:
print(
"percentage of time spent under (5cm, 2cm, 1cm):",
avg_p005 * 100,
avg_p002 * 100,
avg_p001 * 100,
)
print(
"percentage of time spent under (5deg, 2deg, 1deg):",
avg_h005 * 100,
avg_h002 * 100,
avg_h001 * 100,
)
success_rate_df = pd.DataFrame(
{
"PT5": [avg_p005],
"PT2": [avg_p002],
"PT1": [avg_p001],
"OT5": [avg_h005],
"OT2": [avg_h002],
"OT1": [avg_h001],
}
)
return {"pose": success_rate_df}
def get_GoToXY_success_rate(
ep_data: dict, threshold: float = 0.02, print_intermediate: bool = False
) -> dict:
"""Compute the success rate from the distances to the target.
Args:
distances (np.ndarray): Array of distances to the target for N episodes.
precision (float): Distance at which the target is considered reached.
Returns:
float: Success rate."""
distances = np.linalg.norm(ep_data["obs"][:, :, 6:8], axis=2)
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(distances, threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
threshold,
print_intermediate,
)
success_rate_df = pd.DataFrame(
{
f"success_rate_{threshold}_m": [success_rate_thr],
f"success_rate_{threshold/2}_m": [success_rate_thr2],
f"success_and_stay_within_{threshold*7.5}_m": [success_and_stay_rate * 100],
}
)
return {"position": success_rate_df}
def get_GoToPose_results(
ep_data: dict,
position_threshold: float = 0.02,
heading_threshold: float = 0.087,
print_intermediate: bool = False,
) -> None:
new_SR = get_GoToPose_success_rate_new(ep_data, print_intermediate=False)
old_SR = get_GoToPose_success_rate(ep_data, print_intermediate=False)
alv = compute_average_linear_velocity(ep_data)
aav = compute_average_angular_velocity(ep_data)
aac = compute_average_action_count(ep_data) / 8
ordered_metrics_keys = [
"PA1",
"PA2",
"PSA",
"OA1",
"OA2",
"OSA",
"ALV",
"AAV",
"AAC",
"PT5",
"PT2",
"PT1",
"OT5",
"OT2",
"OT1",
]
ordered_metrics_descriptions = [
"Position reached below 0.02 m of the target",
"Position reached below 0.01 m of the target",
"Position success and stay within 0.15 m",
"Orientation reached below 0.087 rad of the target",
"Orientation reached below 0.0435 rad of the target",
"Orientation success and stay within 0.6525 rad",
"Average linear velocity",
"Average angular velocity",
"Average action count",
"Percentage of time spent within 0.05 m of the target",
"Percentage of time spent within 0.02 m of the target",
"Percentage of time spent within 0.01 m of the target",
"Percentage of time spent within 0.05 rad of the target",
"Percentage of time spent within 0.02 rad of the target",
"Percentage of time spent within 0.01 rad of the target",
]
ordered_metrics_units = [
"%",
"%",
"%",
"%",
"%",
"%",
"m/s",
"rad/s",
"N",
"%",
"%",
"%",
"%",
"%",
"%",
]
ordered_metrics_multipliers = [
1,
1,
1,
1,
1,
1,
1,
1,
1,
100,
100,
100,
100,
100,
100,
]
metrics = np.array(
[
old_SR["position"]["success_rate_0.02_m"][0], # PA1
old_SR["position"]["success_rate_0.01_m"][0], # PA2
old_SR["position"]["success_and_stay_within_0.15_m"][0], # PSA
old_SR["heading"]["success_rate_0.087_rad"][0], # OA1
old_SR["heading"]["success_rate_0.0435_rad"][0], # OA2
old_SR["heading"]["success_and_stay_within_0.6525_rad"][0], # OSA
alv, # ALV
aav, # AAV
aac, # AAC
new_SR["pose"]["PT5"][0], # PT5
new_SR["pose"]["PT2"][0], # PT2
new_SR["pose"]["PT1"][0], # PT1
new_SR["pose"]["OT5"][0], # OT5
new_SR["pose"]["OT2"][0], # OT2
new_SR["pose"]["OT1"][0], # OT1
]
)
# Print the metrics line by line
print(f"Metrics acquired using a sample of {ep_data['act'].shape[1]}:")
for i, (metric, unit, mult, desc) in enumerate(
zip(
ordered_metrics_keys,
ordered_metrics_units,
ordered_metrics_multipliers,
ordered_metrics_descriptions,
)
):
print(f" + {metric}: {metrics[i]*mult:.2f}{unit}. {desc}.")
return
def get_GoToPose_success_rate(
ep_data: dict,
position_threshold: float = 0.02,
heading_threshold: float = 0.087,
print_intermediate: bool = False,
) -> dict:
"""Compute the success rate from the distances to the target.
Args:
distances (np.ndarray): Array of distances to the target for N episodes.
precision (float): Distance at which the target is considered reached.
Returns:
float: Success rate."""
position_distances = np.linalg.norm(ep_data["obs"][:, :, 6:8], axis=2)
heading_distances = np.abs(
np.arctan2(ep_data["obs"][:, :, 9], ep_data["obs"][:, :, 8])
)
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(position_distances, position_threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
position_threshold,
print_intermediate,
)
position_success_rate_df = pd.DataFrame(
{
f"success_rate_{position_threshold}_m": [success_rate_thr],
f"success_rate_{position_threshold/2}_m": [success_rate_thr2],
f"success_and_stay_within_{position_threshold*7.5}_m": [
success_and_stay_rate * 100
],
}
)
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(heading_distances, heading_threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
heading_threshold,
print_intermediate,
)
heading_success_rate_df = pd.DataFrame(
{
f"success_rate_{heading_threshold}_rad": [success_rate_thr],
f"success_rate_{heading_threshold/2}_rad": [success_rate_thr2],
f"success_and_stay_within_{heading_threshold*7.5}_rad": [
success_and_stay_rate * 100
],
}
)
return {"position": position_success_rate_df, "heading": heading_success_rate_df}
def get_TrackXYVelocity_success_rate(
ep_data: dict, threshold: float = 0.15, print_intermediate: bool = False
) -> dict:
"""Compute the success rate from the distances to the target.
Args:
distances (np.ndarray): Array of distances to the target for N episodes.
precision (float): Distance at which the target is considered reached.
Returns:
float: Success rate."""
distances = np.linalg.norm(ep_data["obs"][:, :, 6:8], axis=2)
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(distances, threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
threshold,
print_intermediate,
)
success_rate_df = pd.DataFrame(
{
f"success_rate_{threshold}_m/s": [success_rate_thr],
f"success_rate_{threshold/2}_m/s": [success_rate_thr2],
f"success_and_stay_within_{threshold*7.5}_m/s": [
success_and_stay_rate * 100
],
}
)
return {"xy_velocity": success_rate_df}
def get_TrackXYOVelocity_success_rate(
ep_data: dict,
xy_threshold: float = 0.15,
omega_threshold: float = 0.3,
print_intermediate: bool = False,
) -> float:
"""Compute the success rate from the distances to the target.
Args:
distances (np.ndarray): Array of distances to the target for N episodes.
precision (float): Distance at which the target is considered reached.
Returns:
float: Success rate."""
xy_distances = np.linalg.norm(ep_data["obs"][:, :, 6:8], axis=2)
omega_distances = np.abs(ep_data["obs"][:, :, 8])
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(xy_distances, xy_threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
xy_threshold,
print_intermediate,
)
xy_success_rate_df = pd.DataFrame(
{
f"success_rate_{xy_threshold}_m/s": [success_rate_thr],
f"success_rate_{xy_threshold/2}_m/s": [success_rate_thr2],
f"success_and_stay_within_{xy_threshold*7.5}_m/s": [
success_and_stay_rate * 100
],
}
)
(
less_than_margin_df,
first_less_than_thr_idxs,
first_less_than_thr2_idxs,
) = build_distance_dataframe(omega_distances, omega_threshold)
success_rate_thr, success_rate_thr2, success_and_stay_rate = check_stay(
less_than_margin_df, first_less_than_thr_idxs, first_less_than_thr2_idxs
)
print_success(
success_rate_thr,
success_rate_thr2,
success_and_stay_rate,
omega_threshold,
print_intermediate,
)
omega_success_rate_df = pd.DataFrame(
{
f"success_rate_{omega_threshold}_rad/s": [success_rate_thr],
f"success_rate_{omega_threshold/2}_rad/s": [success_rate_thr2],
f"success_and_stay_within_{omega_threshold*7.5}_rad/s": [
success_and_stay_rate * 100
],
}
)
return {"xy_velocity": xy_success_rate_df, "omega_velocity": omega_success_rate_df}
def get_success_rate_table(success_rate_df: pd.DataFrame) -> None:
print(
success_rate_df.to_latex(
index=False,
formatters={"name": str.upper},
float_format="{:.1f}".format,
bold_rows=True,
caption="Success rate for each experiment.",
label="tab:success_rate",
)
)
| 16,078 | Python | 30.902778 | 103 | 0.582473 |
elharirymatteo/RANS/omniisaacgymenvs/utils/arrow.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional, Sequence
import numpy as np
from omni.isaac.core.materials.visual_material import VisualMaterial
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.core.materials import PhysicsMaterial
from omni.isaac.core.utils.string import find_unique_string_name
from pxr import UsdGeom, Gf
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omni.isaac.core.utils.stage import get_current_stage
from omniisaacgymenvs.utils.shape_utils import Arrow
class VisualArrow(XFormPrim, Arrow):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "visual_arrow".
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[float], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
Raises:
Exception: _description_
"""
def __init__(
self,
prim_path: str,
name: str = "visual_arrow",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
) -> None:
if visible is None:
visible = True
if visual_material is None:
if color is None:
color = np.array([0.5, 0.5, 0.5])
visual_prim_path = find_unique_string_name(
initial_name="/World/Looks/visual_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
visual_material = PreviewSurface(prim_path=visual_prim_path, color=color)
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
VisualArrow.apply_visual_material(self, visual_material)
Arrow.__init__(
self,
prim_path,
body_radius,
body_length,
poll_radius,
poll_length,
head_radius,
head_length,
)
self.setBodyRadius(body_radius)
self.setBodyLength(body_length)
self.setPollRadius(poll_radius)
self.setPollLength(poll_length)
self.setHeadRadius(head_radius)
self.setHeadLength(head_length)
self.updateExtent()
return
class FixedArrow(VisualArrow):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "fixed_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "fixed_arrow",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
) -> None:
if not is_prim_path_valid(prim_path):
# set default values if no physics material given
if physics_material is None:
static_friction = 0.2
dynamic_friction = 1.0
restitution = 0.0
physics_material_path = find_unique_string_name(
initial_name="/World/Physics_Materials/physics_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
physics_material = PhysicsMaterial(
prim_path=physics_material_path,
dynamic_friction=dynamic_friction,
static_friction=static_friction,
restitution=restitution,
)
VisualArrow.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
body_radius=body_radius,
body_length=body_length,
poll_radius=poll_radius,
poll_length=poll_length,
head_radius=head_radius,
head_length=head_length,
visual_material=visual_material,
)
# XFormPrim.set_collision_enabled(self, True)
# if physics_material is not None:
# FixedArrow.apply_physics_material(self, physics_material)
return
class DynamicArrow(RigidPrim, FixedArrow):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "dynamic_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
mass (Optional[float], optional): _description_. Defaults to None.
density (Optional[float], optional): _description_. Defaults to None.
linear_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
angular_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dynamic_sphere",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
color: Optional[np.ndarray] = None,
body_radius: Optional[float] = None,
body_length: Optional[float] = None,
poll_radius: Optional[float] = None,
poll_length: Optional[float] = None,
head_radius: Optional[float] = None,
head_length: Optional[float] = None,
visual_material: Optional[VisualMaterial] = None,
physics_material: Optional[PhysicsMaterial] = None,
mass: Optional[float] = None,
density: Optional[float] = None,
linear_velocity: Optional[Sequence[float]] = None,
angular_velocity: Optional[Sequence[float]] = None,
) -> None:
if not is_prim_path_valid(prim_path):
if mass is None:
mass = 0.02
FixedArrow.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
color=color,
body_radius=body_radius,
body_length=body_length,
poll_radius=poll_radius,
poll_length=poll_length,
head_radius=head_radius,
head_length=head_length,
visual_material=visual_material,
physics_material=physics_material,
)
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
density=density,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 10,576 | Python | 39.680769 | 96 | 0.608075 |
elharirymatteo/RANS/omniisaacgymenvs/utils/demo_util.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def initialize_demo(config, env, init_sim=True):
from omniisaacgymenvs.demos.anymal_terrain import AnymalTerrainDemo
# Mappings from strings to environments
task_map = {
"AnymalTerrain": AnymalTerrainDemo,
}
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
cfg = sim_config.config
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim)
return task | 2,167 | Python | 44.166666 | 107 | 0.757268 |
elharirymatteo/RANS/omniisaacgymenvs/utils/gate.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional, Sequence
import numpy as np
from omni.isaac.core.materials.visual_material import VisualMaterial
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.core.materials import PhysicsMaterial
from omni.isaac.core.utils.string import find_unique_string_name
from pxr import UsdGeom, Gf
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omni.isaac.core.utils.stage import get_current_stage
from omniisaacgymenvs.utils.shape_utils import Gate
class VisualGate(XFormPrim, Gate):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "visual_arrow".
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[float], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
Raises:
Exception: _description_
"""
def __init__(
self,
prim_path: str,
name: str = "visual_arrow",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
gate_width: Optional[float] = None,
gate_thickness: Optional[float] = None,
) -> None:
if visible is None:
visible = True
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
Gate.__init__(
self,
prim_path,
gate_width,
gate_thickness,
)
self.updateExtent()
return
class FixedGate(VisualGate):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "fixed_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "fixed_arrow",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
gate_width: Optional[float] = None,
gate_thickness: Optional[float] = None,
physics_material: Optional[PhysicsMaterial] = None,
) -> None:
if not is_prim_path_valid(prim_path):
# set default values if no physics material given
if physics_material is None:
static_friction = 0.2
dynamic_friction = 1.0
restitution = 0.0
physics_material_path = find_unique_string_name(
initial_name="/World/Physics_Materials/physics_material",
is_unique_fn=lambda x: not is_prim_path_valid(x),
)
physics_material = PhysicsMaterial(
prim_path=physics_material_path,
dynamic_friction=dynamic_friction,
static_friction=static_friction,
restitution=restitution,
)
VisualGate.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
gate_width=gate_width,
gate_thickness=gate_thickness,
)
self.applyCollisions()
# XFormPrim.set_collision_enabled(self, True)
# if physics_material is not None:
# FixedArrow.apply_physics_material(self, physics_material)
return
class DynamicGate(RigidPrim, FixedGate):
"""_summary_
Args:
prim_path (str): _description_
name (str, optional): _description_. Defaults to "dynamic_sphere".
position (Optional[np.ndarray], optional): _description_. Defaults to None.
translation (Optional[np.ndarray], optional): _description_. Defaults to None.
orientation (Optional[np.ndarray], optional): _description_. Defaults to None.
scale (Optional[np.ndarray], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to None.
color (Optional[np.ndarray], optional): _description_. Defaults to None.
radius (Optional[np.ndarray], optional): _description_. Defaults to None.
visual_material (Optional[VisualMaterial], optional): _description_. Defaults to None.
physics_material (Optional[PhysicsMaterial], optional): _description_. Defaults to None.
mass (Optional[float], optional): _description_. Defaults to None.
density (Optional[float], optional): _description_. Defaults to None.
linear_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
angular_velocity (Optional[Sequence[float]], optional): _description_. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dynamic_sphere",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: Optional[bool] = None,
gate_width: Optional[float] = None,
gate_thickness: Optional[float] = None,
physics_material: Optional[PhysicsMaterial] = None,
mass: Optional[float] = None,
density: Optional[float] = None,
linear_velocity: Optional[Sequence[float]] = None,
angular_velocity: Optional[Sequence[float]] = None,
) -> None:
if not is_prim_path_valid(prim_path):
if mass is None:
mass = 0.02
FixedGate.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
gate_width=gate_width,
gate_thickness=gate_thickness,
physics_material=physics_material,
)
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
density=density,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 8,527 | Python | 39.226415 | 96 | 0.613346 |
elharirymatteo/RANS/omniisaacgymenvs/utils/aggregate_and_eval_mujoco_batch_data.py | from argparse import ArgumentParser
from omniisaacgymenvs.utils.eval_metrics import (
get_GoToPose_success_rate_new,
get_GoToPose_success_rate,
compute_average_action_count,
compute_average_angular_velocity,
compute_average_linear_velocity,
)
import pandas as pd
import numpy as np
import os
def parse_args():
parser = ArgumentParser()
parser.add_argument("--folder_path", type=str, default=None)
parser.add_argument("--save_metrics", action="store_true")
parser.add_argument("--use_xyzw", action="store_true")
parser.add_argument("--use_wxyz", action="store_true")
parser.add_argument("--display_metrics", action="store_true")
return parser.parse_args()
args = parse_args()
if args.use_xyzw and args.use_wxyz:
raise ValueError("Cannot use both xyzw and wxyz")
if not args.use_xyzw and not args.use_wxyz:
raise ValueError("Must use either xyzw or wxyz")
folder_path = args.folder_path
save_metrics = args.save_metrics
files = os.listdir(folder_path)
csvs = [f for f in files if f.endswith(".csv")]
eps_data = {}
eps_data["obs"] = []
eps_data["act"] = []
obss = []
acts = []
for csv in csvs:
df = pd.read_csv(os.path.join(folder_path, csv))
# Replicate an observation buffer
obs = np.zeros((df.shape[0], 10))
# Position
x = df["x_position"].to_numpy()
y = df["y_position"].to_numpy()
tx = df["x_position_target"].to_numpy()
ty = df["y_position_target"].to_numpy()
# Velocities
vx = df["x_linear_velocity"].to_numpy()
vy = df["y_linear_velocity"].to_numpy()
vrz = df["z_angular_velocity"].to_numpy()
# Heading
if args.use_xyzw:
quat = np.column_stack(
[
df["x_quaternion"],
df["y_quaternion"],
df["z_quaternion"],
df["w_quaternion"],
]
)
elif args.use_wxyz:
quat = np.column_stack(
[
df["w_quaternion"],
df["x_quaternion"],
df["y_quaternion"],
df["z_quaternion"],
]
)
else:
raise ValueError("Must use either xyzw or wxyz")
th = df["heading_target"].to_numpy()
siny_cosp = 2 * (quat[:, 0] * quat[:, 3] + quat[:, 1] * quat[:, 2])
cosy_cosp = 1 - 2 * (quat[:, 2] * quat[:, 2] + quat[:, 3] * quat[:, 3])
orient_z = np.arctan2(siny_cosp, cosy_cosp)
heading_error = np.arctan2(np.sin(th - orient_z), np.cos(th - orient_z))
obs[:, 0] = np.cos(orient_z)
obs[:, 1] = np.sin(orient_z)
obs[:, 2] = vx
obs[:, 3] = vy
obs[:, 4] = vrz
obs[:, 5] = 1
obs[:, 6] = tx - x
obs[:, 7] = ty - y
obs[:, 8] = np.cos(heading_error)
obs[:, 9] = np.sin(heading_error)
act = np.column_stack(
[
df["t_0"].to_numpy(),
df["t_1"].to_numpy(),
df["t_2"].to_numpy(),
df["t_3"].to_numpy(),
df["t_4"].to_numpy(),
df["t_5"].to_numpy(),
df["t_6"].to_numpy(),
df["t_7"].to_numpy(),
]
)
acts.append([act])
obss.append([obs])
eps_data["act"] = np.concatenate(acts, axis=0)
eps_data["obs"] = np.concatenate(obss, axis=0)
new_SR = get_GoToPose_success_rate_new(eps_data, print_intermediate=False)
old_SR = get_GoToPose_success_rate(eps_data, print_intermediate=False)
alv = compute_average_linear_velocity(eps_data)
aav = compute_average_angular_velocity(eps_data)
aac = compute_average_action_count(eps_data) / 8
ordered_metrics_keys = [
"PA1",
"PA2",
"PSA",
"OA1",
"OA2",
"OSA",
"ALV",
"AAV",
"AAC",
"PT5",
"PT2",
"PT1",
"OT5",
"OT2",
"OT1",
]
ordered_metrics_descriptions = [
"Position reached below 0.02 m of the target",
"Position reached below 0.01 m of the target",
"Position success and stay within 0.15 m",
"Orientation reached below 0.087 rad of the target",
"Orientation reached below 0.0435 rad of the target",
"Orientation success and stay within 0.6525 rad",
"Average linear velocity",
"Average angular velocity",
"Average action count",
"Percentage of time spent within 0.05 m of the target",
"Percentage of time spent within 0.02 m of the target",
"Percentage of time spent within 0.01 m of the target",
"Percentage of time spent within 0.05 rad of the target",
"Percentage of time spent within 0.02 rad of the target",
"Percentage of time spent within 0.01 rad of the target",
]
ordered_metrics_units = [
"%",
"%",
"%",
"%",
"%",
"%",
"m/s",
"rad/s",
"N",
"%",
"%",
"%",
"%",
"%",
"%",
]
ordered_metrics_multipliers = [
1,
1,
1,
1,
1,
1,
1,
1,
1,
100,
100,
100,
100,
100,
100,
]
metrics = np.array(
[
old_SR["position"]["success_rate_0.02_m"][0], # PA1
old_SR["position"]["success_rate_0.01_m"][0], # PA2
old_SR["position"]["success_and_stay_within_0.15_m"][0], # PSA
old_SR["heading"]["success_rate_0.087_rad"][0], # OA1
old_SR["heading"]["success_rate_0.0435_rad"][0], # OA2
old_SR["heading"]["success_and_stay_within_0.6525_rad"][0], # OSA
alv, # ALV
aav, # AAV
aac, # AAC
new_SR["pose"]["PT5"][0], # PT5
new_SR["pose"]["PT2"][0], # PT2
new_SR["pose"]["PT1"][0], # PT1
new_SR["pose"]["OT5"][0], # OT5
new_SR["pose"]["OT2"][0], # OT2
new_SR["pose"]["OT1"][0], # OT1
]
)
np.save(os.path.join(folder_path, "aggregated_results.npy"), metrics)
# Print the metrics line by line
print(f"Metrics acquired using a sample of {eps_data['act'].shape[0]}:")
if args.display_metrics:
for i, (metric, unit, mult, desc) in enumerate(
zip(
ordered_metrics_keys,
ordered_metrics_units,
ordered_metrics_multipliers,
ordered_metrics_descriptions,
)
):
print(f" + {metric}: {metrics[i]*mult:.2f}{unit}. {desc}.")
| 6,081 | Python | 25.329004 | 76 | 0.551554 |
elharirymatteo/RANS/omniisaacgymenvs/utils/shape_utils.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from pxr import UsdGeom, Gf, UsdShade, Sdf, Usd, UsdPhysics
import omni
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omni.isaac.core.utils.string import find_unique_string_name
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.materials import PreviewSurface
import numpy as np
def setXformOp(prim, value, property):
xform = UsdGeom.Xformable(prim)
op = None
for xformOp in xform.GetOrderedXformOps():
if xformOp.GetOpType() == property:
op = xformOp
if op:
xform_op = op
else:
xform_op = xform.AddXformOp(property, UsdGeom.XformOp.PrecisionDouble, "")
xform_op.Set(value)
def setScale(prim, value):
setXformOp(prim, value, UsdGeom.XformOp.TypeScale)
def setTranslate(prim, value):
setXformOp(prim, value, UsdGeom.XformOp.TypeTranslate)
def setRotateXYZ(prim, value):
setXformOp(prim, value, UsdGeom.XformOp.TypeRotateXYZ)
def setOrient(prim, value):
setXformOp(prim, value, UsdGeom.XformOp.TypeOrient)
def setTransform(prim, value: Gf.Matrix4d):
setXformOp(prim, value, UsdGeom.XformOp.TypeTransform)
def applyTransforms(prim, translation, rotation, scale, material=None):
setTranslate(prim, Gf.Vec3d(translation))
setOrient(prim, Gf.Quatd(rotation[-1], Gf.Vec3d(rotation[:3])))
setScale(prim, Gf.Vec3d(scale))
if material is not None:
applyMaterial(prim, material)
def createPrim(prim_path, name="/body", geom_type=UsdGeom.Cylinder):
obj_prim_path = prim_path + name
if is_prim_path_valid(obj_prim_path):
prim = get_prim_at_path(obj_prim_path)
if not prim.IsA(geom_type):
raise Exception(
"The prim at path {} cannot be parsed as an arrow object".format(
obj_prim_path
)
)
geom = geom_type(prim)
else:
geom = geom_type.Define(get_current_stage(), obj_prim_path)
prim = get_prim_at_path(obj_prim_path)
return geom, prim
def createColor(stage: Usd.Stage, material_path: str, color: list):
"""
Creates a color material."""
material_path = omni.usd.get_stage_next_free_path(stage, material_path, False)
material = UsdShade.Material.Define(stage, material_path)
shader = UsdShade.Shader.Define(stage, material_path + "/shader")
shader.CreateIdAttr("UsdPreviewSurface")
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Float3).Set(Gf.Vec3f(color))
material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
return material
def applyMaterial(prim: Usd.Prim, material: UsdShade.Material) -> None:
"""
Applies a material to a prim."""
binder = UsdShade.MaterialBindingAPI.Apply(prim)
binder.Bind(material)
def getCurrentStage():
return omni.usd.get_context().get_stage()
def applyCollider(prim: Usd.Prim, enable: bool = False) -> UsdPhysics.CollisionAPI:
"""
Applies a ColliderAPI to a prim.
Args:
prim (Usd.Prim): The prim to apply the ColliderAPI.
enable (bool): Enable or disable the collider.
Returns:
UsdPhysics.CollisionAPI: The ColliderAPI.
"""
collider = UsdPhysics.CollisionAPI.Apply(prim)
collider.CreateCollisionEnabledAttr(enable)
return collider
class Pin:
def __init__(self, prim_path, ball_radius, poll_radius, poll_length):
if ball_radius is None:
ball_radius = 0.1
if poll_radius is None:
poll_radius = 0.02
if poll_length is None:
poll_length = 2
self.ball_geom, ball_prim = createPrim(
prim_path, name="/ball", geom_type=UsdGeom.Sphere
)
self.poll_geom, poll_prim = createPrim(
prim_path, name="/poll", geom_type=UsdGeom.Cylinder
)
applyTransforms(poll_prim, [0, 0, -poll_length / 2], [0, 0, 0, 1], [1, 1, 1])
applyTransforms(ball_prim, [0, 0, 0], [0, 0, 0, 1], [1, 1, 1])
def updateExtent(self):
radius = self.getBallRadius()
self.ball_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
radius = self.getPollRadius()
height = self.getPollLength()
self.poll_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
def setBallRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.ball_geom.GetRadiusAttr().Set(radius)
return
def getBallRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.ball_geom.GetRadiusAttr().Get()
def setPollRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll_geom.GetRadiusAttr().Set(radius)
return
def getPollRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll_geom.GetRadiusAttr().Get()
def setPollLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll_geom.GetHeightAttr().Set(radius)
return
def getPollLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll_geom.GetHeightAttr().Get()
class Pin3D:
def __init__(self, prim_path, ball_radius, poll_radius, poll_length):
if ball_radius is None:
ball_radius = 0.05
if poll_radius is None:
poll_radius = 0.02
if poll_length is None:
poll_length = 2
red_material = createColor(
getCurrentStage(), "/World/Looks/red_material", [1, 0, 0]
)
green_material = createColor(
getCurrentStage(), "/World/Looks/green_material", [0, 1, 0]
)
blue_material = createColor(
getCurrentStage(), "/World/Looks/blue_material", [0, 0, 1]
)
self.ball11_geom, ball11_prim = createPrim(
prim_path, name="/ball_11", geom_type=UsdGeom.Sphere
)
self.ball12_geom, ball12_prim = createPrim(
prim_path, name="/ball_12", geom_type=UsdGeom.Sphere
)
self.ball21_geom, ball21_prim = createPrim(
prim_path, name="/ball_21", geom_type=UsdGeom.Sphere
)
self.ball22_geom, ball22_prim = createPrim(
prim_path, name="/ball_22", geom_type=UsdGeom.Sphere
)
self.ball31_geom, ball31_prim = createPrim(
prim_path, name="/ball_31", geom_type=UsdGeom.Sphere
)
self.ball32_geom, ball32_prim = createPrim(
prim_path, name="/ball_32", geom_type=UsdGeom.Sphere
)
self.poll1_geom, poll1_prim = createPrim(
prim_path, name="/poll_1", geom_type=UsdGeom.Cylinder
)
self.poll2_geom, poll2_prim = createPrim(
prim_path, name="/poll_2", geom_type=UsdGeom.Cylinder
)
self.poll3_geom, poll3_prim = createPrim(
prim_path, name="/poll_3", geom_type=UsdGeom.Cylinder
)
# Z Axis
applyTransforms(poll1_prim, [0, 0, 0], [0, 0, 0, 1], [1, 1, 1], blue_material)
applyTransforms(
ball11_prim, [0, 0, poll_length / 2], [0, 0, 0, 1], [1, 1, 1], blue_material
)
applyTransforms(
ball12_prim,
[0, 0, -poll_length / 2],
[0, 0, 0, 1],
[1, 1, 1],
blue_material,
)
# Y Axis
applyTransforms(
poll2_prim, [0, 0, 0], [0.707, 0, 0, 0.707], [1, 1, 1], green_material
)
applyTransforms(
ball21_prim,
[0, poll_length / 2, 0],
[0, 0, 0, 1],
[1, 1, 1],
green_material,
)
applyTransforms(
ball22_prim,
[0, -poll_length / 2, 0],
[0, 0, 0, 1],
[1, 1, 1],
green_material,
)
# X Axis
applyTransforms(
poll3_prim, [0, 0, 0], [0, 0.707, 0, 0.707], [1, 1, 1], red_material
)
applyTransforms(
ball31_prim,
[poll_length / 2.0, 0, 0],
[0, 0.707, 0, 0.707],
[1, 1, 1],
red_material,
)
applyTransforms(
ball32_prim,
[-poll_length / 2.0, 0, 0],
[0, 0.707, 0, 0.707],
[1, 1, 1],
red_material,
)
def updateExtent(self):
radius = self.getBallRadius()
self.ball11_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
self.ball21_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
self.ball31_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
self.ball12_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
self.ball22_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
self.ball32_geom.GetExtentAttr().Set(
[Gf.Vec3f([-radius, -radius, -radius]), Gf.Vec3f([radius, radius, radius])]
)
radius = self.getPollRadius()
height = self.getPollLength()
self.poll1_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.poll2_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.poll3_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
def setBallRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.ball11_geom.GetRadiusAttr().Set(radius)
self.ball21_geom.GetRadiusAttr().Set(radius)
self.ball31_geom.GetRadiusAttr().Set(radius)
self.ball12_geom.GetRadiusAttr().Set(radius)
self.ball22_geom.GetRadiusAttr().Set(radius)
self.ball32_geom.GetRadiusAttr().Set(radius)
return
def getBallRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.ball11_geom.GetRadiusAttr().Get()
def setPollRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll1_geom.GetRadiusAttr().Set(radius)
self.poll2_geom.GetRadiusAttr().Set(radius)
self.poll3_geom.GetRadiusAttr().Set(radius)
return
def getPollRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll1_geom.GetRadiusAttr().Get()
def setPollLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll1_geom.GetHeightAttr().Set(radius)
self.poll2_geom.GetHeightAttr().Set(radius)
self.poll3_geom.GetHeightAttr().Set(radius)
return
def getPollLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll1_geom.GetHeightAttr().Get()
class Arrow:
def __init__(
self,
prim_path,
body_radius,
body_length,
poll_radius,
poll_length,
head_radius,
head_length,
):
if body_radius is None:
body_radius = 0.1
if body_length is None:
body_length = 0.5
if poll_radius is None:
poll_radius = 0.02
if poll_length is None:
poll_length = 2
if head_radius is None:
head_radius = 0.25
if head_length is None:
head_length = 0.5
# createPrim()
self.body_geom, body_prim = createPrim(
prim_path, name="/body", geom_type=UsdGeom.Cylinder
)
self.poll_geom, poll_prim = createPrim(
prim_path, name="/poll", geom_type=UsdGeom.Cylinder
)
self.head_geom, head_prim = createPrim(
prim_path, name="/head", geom_type=UsdGeom.Cone
)
applyTransforms(poll_prim, [0, 0, -poll_length / 2], [0, 0, 0, 1], [1, 1, 1])
applyTransforms(
body_prim, [body_length / 2, 0, 0], [0, 0.707, 0, 0.707], [1, 1, 1]
)
applyTransforms(
head_prim,
[body_length + head_length / 2, 0, 0],
[0, 0.707, 0, 0.707],
[1, 1, 1],
)
def updateExtent(self):
radius = self.getBodyRadius()
height = self.getBodyLength()
self.body_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
radius = self.getPollRadius()
height = self.getPollLength()
self.poll_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
radius = self.getHeadRadius()
height = self.getHeadLength()
self.head_geom.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
return
def setBodyRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.body_geom.GetRadiusAttr().Set(radius)
return
def getBodyRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.body_geom.GetRadiusAttr().Get()
def setBodyLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.body_geom.GetHeightAttr().Set(radius)
return
def getBodyLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.body_geom.GetHeightAttr().Get()
def setPollRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll_geom.GetRadiusAttr().Set(radius)
return
def getPollRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll_geom.GetRadiusAttr().Get()
def setPollLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.poll_geom.GetHeightAttr().Set(radius)
return
def getPollLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.poll_geom.GetHeightAttr().Get()
def setHeadRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.head_geom.GetRadiusAttr().Set(radius)
return
def getHeadRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.head_geom.GetRadiusAttr().Get()
def setHeadLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.head_geom.GetHeightAttr().Set(radius)
return
def getHeadLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.head_geom.GetHeightAttr().Get()
class Arrow3D:
def __init__(self, prim_path, body_radius, body_length, head_radius, head_length):
if body_radius is None:
body_radius = 0.1
if body_length is None:
body_length = 0.5
if head_radius is None:
head_radius = 0.25
if head_length is None:
head_length = 0.5
red_material = createColor(
getCurrentStage(), "/World/Looks/red_material", [1, 0, 0]
)
green_material = createColor(
getCurrentStage(), "/World/Looks/green_material", [0, 1, 0]
)
blue_material = createColor(
getCurrentStage(), "/World/Looks/blue_material", [0, 0, 1]
)
# createPrim()
self.body_geom1, body_prim1 = createPrim(
prim_path, name="/body1", geom_type=UsdGeom.Cylinder
)
self.body_geom2, body_prim2 = createPrim(
prim_path, name="/body2", geom_type=UsdGeom.Cylinder
)
self.body_geom3, body_prim3 = createPrim(
prim_path, name="/body3", geom_type=UsdGeom.Cylinder
)
self.head_geom1, head_prim1 = createPrim(
prim_path, name="/head1", geom_type=UsdGeom.Cone
)
self.head_geom2, head_prim2 = createPrim(
prim_path, name="/head2", geom_type=UsdGeom.Cone
)
self.head_geom3, head_prim3 = createPrim(
prim_path, name="/head3", geom_type=UsdGeom.Cone
)
# Z Axis
applyTransforms(
body_prim1,
[0, 0, body_length / 2],
[0, 0, 0, 1.0],
[1, 1, 1],
material=blue_material,
)
applyTransforms(
head_prim1,
[0, 0, body_length + head_length / 2],
[0, 0, 0, 1.0],
[1, 1, 1],
material=blue_material,
)
# Y Axis
applyTransforms(
body_prim2,
[0, body_length / 2, 0],
[0.707, 0, 0, 0.707],
[1, 1, 1],
material=green_material,
)
applyTransforms(
head_prim2,
[0, body_length + head_length / 2, 0],
[-0.707, 0, 0, 0.707],
[1, 1, 1],
material=green_material,
)
# X Axis
applyTransforms(
body_prim3,
[body_length / 2, 0, 0],
[0, 0.707, 0, 0.707],
[1, 1, 1],
material=red_material,
)
applyTransforms(
head_prim3,
[body_length + head_length / 2, 0, 0],
[0, 0.707, 0, 0.707],
[1, 1, 1],
material=red_material,
)
def updateExtent(self):
radius = self.getBodyRadius()
height = self.getBodyLength()
self.body_geom1.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.body_geom2.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.body_geom3.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
radius = self.getHeadRadius()
height = self.getHeadLength()
self.head_geom1.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.head_geom2.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
self.head_geom3.GetExtentAttr().Set(
[
Gf.Vec3f([-radius, -radius, -height / 2.0]),
Gf.Vec3f([radius, radius, height / 2.0]),
]
)
return
def setBodyRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.body_geom1.GetRadiusAttr().Set(radius)
self.body_geom2.GetRadiusAttr().Set(radius)
self.body_geom3.GetRadiusAttr().Set(radius)
return
def getBodyRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.body_geom1.GetRadiusAttr().Get()
def setBodyLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.body_geom1.GetHeightAttr().Set(radius)
self.body_geom2.GetHeightAttr().Set(radius)
self.body_geom3.GetHeightAttr().Set(radius)
return
def getBodyLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.body_geom1.GetHeightAttr().Get()
def setHeadRadius(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.head_geom1.GetRadiusAttr().Set(radius)
self.head_geom2.GetRadiusAttr().Set(radius)
self.head_geom3.GetRadiusAttr().Set(radius)
return
def getHeadRadius(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.head_geom1.GetRadiusAttr().Get()
def setHeadLength(self, radius: float) -> None:
"""[summary]
Args:
radius (float): [description]
"""
self.head_geom1.GetHeightAttr().Set(radius)
self.head_geom2.GetHeightAttr().Set(radius)
self.head_geom3.GetHeightAttr().Set(radius)
return
def getHeadLength(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.head_geom1.GetHeightAttr().Get()
class Gate:
def __init__(
self,
prim_path,
gate_width,
gate_thickness,
):
if gate_width is None:
gate_width = 1.0
if gate_thickness is None:
gate_thickness = 0.2
# Front
self.bottom_front_geom, self.bottom_front_prim = createPrim(
prim_path, name="/bottom_front", geom_type=UsdGeom.Cube
)
self.top_front_geom, self.top_front_prim = createPrim(
prim_path, name="/top_front", geom_type=UsdGeom.Cube
)
self.left_front_geom, self.left_front_prim = createPrim(
prim_path, name="/left_front", geom_type=UsdGeom.Cube
)
self.right_front_geom, self.right_front_prim = createPrim(
prim_path, name="/right_ftont", geom_type=UsdGeom.Cube
)
# Back
self.bottom_back_geom, self.bottom_back_prim = createPrim(
prim_path, name="/bottom_back", geom_type=UsdGeom.Cube
)
self.top_back_geom, self.top_back_prim = createPrim(
prim_path, name="/top_back", geom_type=UsdGeom.Cube
)
self.left_back_geom, self.left_back_prim = createPrim(
prim_path, name="/left_back", geom_type=UsdGeom.Cube
)
self.right_back_geom, self.right_back_prim = createPrim(
prim_path, name="/right_back", geom_type=UsdGeom.Cube
)
# Corners
self.top_right_corner_geom, self.top_right_corner_prim = createPrim(
prim_path, name="/top_right_corner", geom_type=UsdGeom.Cube
)
self.top_left_corner_geom, self.top_left_corner_prim = createPrim(
prim_path, name="/top_left_corner", geom_type=UsdGeom.Cube
)
self.bottom_left_corner_geom, self.bottom_left_corner_prim = createPrim(
prim_path, name="/bottom_left_corner", geom_type=UsdGeom.Cube
)
self.bottom_right_corner_geom, self.bottom_right_corner_prim = createPrim(
prim_path, name="/bottom_right_corner", geom_type=UsdGeom.Cube
)
# Colors
self.red_material = createColor(
getCurrentStage(), "/World/Looks/red_material", [1, 0, 0]
)
self.blue_material = createColor(
getCurrentStage(), "/World/Looks/blue_material", [0, 0, 1]
)
self.white_material = createColor(
getCurrentStage(), "/World/Looks/white_material", [1, 1, 1]
)
self.gate_thickness = gate_thickness
self.gate_width = gate_width
self.setThicknessInternal(gate_thickness)
self.applyTransformsInternal(gate_thickness, gate_width)
def applyTransformsInternal(self, gate_thickness, gate_width):
ratio = gate_width / gate_thickness
# Front (Red)
applyTransforms(
self.top_front_prim,
[gate_thickness / 4, 0, gate_width / 2 + gate_thickness / 2],
[0, 0, 0, 1],
[0.5, ratio, 1],
material=self.red_material,
)
applyTransforms(
self.bottom_front_prim,
[gate_thickness / 4, 0, -gate_width / 2 - gate_thickness / 2],
[0, 0, 0, 1],
[0.5, ratio, 1],
material=self.red_material,
)
applyTransforms(
self.left_front_prim,
[gate_thickness / 4, -gate_width / 2 - gate_thickness / 2, 0],
[0, 0, 0, 1],
[0.5, 1, ratio],
material=self.red_material,
)
applyTransforms(
self.right_front_prim,
[gate_thickness / 4, gate_width / 2 + gate_thickness / 2, 0],
[0, 0, 0, 1],
[0.5, 1, ratio],
material=self.red_material,
)
# Back (Blue)
applyTransforms(
self.top_back_prim,
[-gate_thickness / 4, 0, gate_width / 2 + gate_thickness / 2],
[0, 0, 0, 1],
[0.5, ratio, 1],
material=self.blue_material,
)
applyTransforms(
self.bottom_back_prim,
[-gate_thickness / 4, 0, -gate_width / 2 - gate_thickness / 2],
[0, 0, 0, 1],
[0.5, ratio, 1],
material=self.blue_material,
)
applyTransforms(
self.left_back_prim,
[-gate_thickness / 4, -gate_width / 2 - gate_thickness / 2, 0],
[0, 0, 0, 1],
[0.5, 1, ratio],
material=self.blue_material,
)
applyTransforms(
self.right_back_prim,
[-gate_thickness / 4, gate_width / 2 + gate_thickness / 2, 0],
[0, 0, 0, 1],
[0.5, 1, ratio],
material=self.blue_material,
)
# Corners (White)
applyTransforms(
self.top_right_corner_prim,
[
0,
gate_width / 2 + gate_thickness / 2,
gate_width / 2 + gate_thickness / 2,
],
[0, 0, 0, 1],
[1, 1, 1],
material=self.white_material,
)
applyTransforms(
self.top_left_corner_prim,
[
0,
-gate_width / 2 - gate_thickness / 2,
gate_width / 2 + gate_thickness / 2,
],
[0, 0, 0, 1],
[1, 1, 1],
material=self.white_material,
)
applyTransforms(
self.bottom_left_corner_prim,
[
0,
-gate_width / 2 - gate_thickness / 2,
-gate_width / 2 - gate_thickness / 2,
],
[0, 0, 0, 1],
[1, 1, 1],
material=self.white_material,
)
applyTransforms(
self.bottom_right_corner_prim,
[
0,
gate_width / 2 + gate_thickness / 2,
-gate_width / 2 - gate_thickness / 2,
],
[0, 0, 0, 1],
[1, 1, 1],
material=self.white_material,
)
def setThicknessInternal(self, thickness):
# Front
self.top_front_geom.GetSizeAttr().Set(thickness)
self.bottom_front_geom.GetSizeAttr().Set(thickness)
self.left_front_geom.GetSizeAttr().Set(thickness)
self.right_front_geom.GetSizeAttr().Set(thickness)
# Back
self.top_back_geom.GetSizeAttr().Set(thickness)
self.bottom_back_geom.GetSizeAttr().Set(thickness)
self.left_back_geom.GetSizeAttr().Set(thickness)
self.right_back_geom.GetSizeAttr().Set(thickness)
# Corners
self.top_right_corner_geom.GetSizeAttr().Set(thickness)
self.top_left_corner_geom.GetSizeAttr().Set(thickness)
self.bottom_left_corner_geom.GetSizeAttr().Set(thickness)
self.bottom_right_corner_geom.GetSizeAttr().Set(thickness)
def updateExtent(self):
return
def applyCollisions(self):
applyCollider(self.top_front_prim, True)
applyCollider(self.bottom_front_prim, True)
applyCollider(self.left_front_prim, True)
applyCollider(self.right_front_prim, True)
applyCollider(self.top_back_prim, True)
applyCollider(self.bottom_back_prim, True)
applyCollider(self.left_back_prim, True)
applyCollider(self.right_back_prim, True)
applyCollider(self.top_right_corner_prim, True)
applyCollider(self.top_left_corner_prim, True)
applyCollider(self.bottom_left_corner_prim, True)
applyCollider(self.bottom_right_corner_prim, True)
def setGateThickness(self, thickness: float) -> None:
"""[summary]
Args:
thickness (float): [description]
"""
self.gate_thickness = thickness
self.setThicknessInternal(self.gate_thickness)
self.applyTransformsInternal(self.gate_thickness, self.gate_width)
return
def getGateThickness(self) -> float:
"""[summary]
Returns:
thickness: [description]
"""
return self.gate_thickness
def setGateThickness(self, width: float) -> None:
"""[summary]
Args:
width (float): [description]
"""
self.gate_width = width
self.setThicknessInternal(self.gate_thickness)
self.applyTransformsInternal(self.gate_thickness, self.gate_width)
return
def getGateWidth(self) -> float:
"""[summary]
Returns:
float: [description]
"""
return self.gate_width
| 31,432 | Python | 29.39942 | 88 | 0.530892 |
elharirymatteo/RANS/omniisaacgymenvs/utils/dock.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import os
from typing import Optional, Sequence
from dataclasses import dataclass
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.articulations import Articulation, ArticulationView
@dataclass
class DockParameters:
"""
Docking station parameters.
Args:
usd_path (str): path to the usd file
show_axis (bool): show the axis of the docking station
mass (float): mass of the docking station
"""
usd_path: str = None
show_axis: bool = False
mass: float = 5.0
enable_collision: bool = True
class Dock(Articulation):
"""
Class to create xform prim for a docking station.
See parent class for more details about the arguments.
Args:
prim_path (str): path to the prim
name (str): name of the prim
position (Optional[Sequence[float]], optional): _description_. Defaults to None.
translation (Optional[Sequence[float]], optional): _description_. Defaults to None.
orientation (Optional[Sequence[float]], optional): _description_. Defaults to None.
scale (Optional[Sequence[float]], optional): _description_. Defaults to None.
visible (Optional[bool], optional): _description_. Defaults to True.
dock_params (dict, optional): dictionary of DockParameters. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "dock",
position: Optional[Sequence[float]] = None,
translation: Optional[Sequence[float]] = None,
orientation: Optional[Sequence[float]] = None,
scale: Optional[Sequence[float]] = None,
visible: Optional[bool] = True,
dock_params: dict = None,
):
self.dock_params = DockParameters(**dock_params)
self.stage = get_current_stage()
self.joints_path = "joints"
self.create_articulation_root(prim_path)
super().__init__(
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
self.build()
return
def create_articulation_root(self, prim_path)->None:
"""
Create a root xform and link usd to it.
Args:
prim_path (str): path to the prim
"""
createArticulation(self.stage, prim_path)
add_reference_to_stage(os.path.join(os.getcwd(), self.dock_params.usd_path), prim_path)
axis_prim = get_prim_at_path(prim_path+"/dock/axis")
if self.dock_params.show_axis:
axis_prim.GetAttribute("visibility").Set("visible")
else:
axis_prim.GetAttribute("visibility").Set("invisible")
def build(self)->None:
"""
Apply RigidBody API, Collider, mass, and PlaneLock joints.
"""
self.joints_path, self.joints_prim = createXform(
self.stage, self.prim_path + "/" + self.joints_path
)
self.configure_core_prim()
self.createXYPlaneLock()
def createXYPlaneLock(self) -> None:
"""
Creates a set of joints to constrain the platform to the XY plane.
3DoF: translation on X and Y, rotation on Z.
"""
# Create anchor to world. It's fixed.
anchor_path, anchor_prim = createXform(
self.stage, self.prim_path + "/world_anchor"
)
setTranslate(anchor_prim, Gf.Vec3d(0, 0, 0))
setOrient(anchor_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(anchor_prim)
applyMass(anchor_prim, 0.0000001)
fixed_joint = createFixedJoint(
self.stage, self.joints_path, body_path2=anchor_path
)
# Create the bodies & joints allowing translation
x_tr_path, x_tr_prim = createXform(
self.stage, self.prim_path + "/x_translation_body"
)
y_tr_path, y_tr_prim = createXform(
self.stage, self.prim_path + "/y_translation_body"
)
setTranslate(x_tr_prim, Gf.Vec3d(0, 0, 0))
setOrient(x_tr_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(x_tr_prim)
applyMass(x_tr_prim, 0.0000001)
setTranslate(y_tr_prim, Gf.Vec3d(0, 0, 0))
setOrient(y_tr_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(y_tr_prim)
applyMass(y_tr_prim, 0.0000001)
tr_joint_x = createPrismaticJoint(
self.stage,
self.joints_path + "/dock_world_joint_x",
body_path1=anchor_path,
body_path2=x_tr_path,
axis="X",
enable_drive=False,
)
tr_joint_y = createPrismaticJoint(
self.stage,
self.joints_path + "/dock_world_joint_y",
body_path1=x_tr_path,
body_path2=y_tr_path,
axis="Y",
enable_drive=False,
)
# Adds the joint allowing for rotation
rv_joint_z = createRevoluteJoint(
self.stage,
self.joints_path + "/dock_world_joint_z",
body_path1=y_tr_path,
body_path2=self.core_path,
axis="Z",
enable_drive=False,
)
def configure_core_prim(self):
"""
Configures the body of the platform.
"""
self.core_path = self.prim_path+"/dock"
core = get_prim_at_path(self.core_path)
applyRigidBody(core)
applyCollider(core, self.dock_params.enable_collision)
applyMass(core, self.dock_params.mass)
class DockView(ArticulationView):
def __init__(
self, prim_paths_expr: str,
name: Optional[str] = "DockView",
) -> None:
"""[summary]"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.base = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/dock/dock",
name="dock_base_view",
)
def get_plane_lock_indices(self):
self.lock_indices = [
self.get_dof_index("dock_world_joint_x"),
self.get_dof_index("dock_world_joint_y"),
self.get_dof_index("dock_world_joint_z"),
] | 6,804 | Python | 34.815789 | 95 | 0.585097 |
elharirymatteo/RANS/omniisaacgymenvs/utils/plot_experiment.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import array
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, mark_inset
import seaborn as sns
from matplotlib.collections import LineCollection
def plot_episode_data_virtual(
ep_data: dict, save_dir: str, all_agents: bool = False
) -> None:
"""
Plots the evaluation data for a single agent across a set of evaluation episodes.
The following metrics are aggregated across all epsiodes:
- distance to the goal
- reward
- velocities (angular and linear)
- actions
- trajectories: XY positions, no heading.
Args:
ep_data: dict: dictionary containing episode data
save_dir: str: directory where to save the plots
all_agents: bool: if True, plot average results over all agents, if False only the first agent is plotted
"""
reward_history = ep_data["rews"]
control_history = ep_data["act"]
state_history = ep_data["obs"]
# Overrides the user arg is there is only one episode
all_agents = False if reward_history.shape[1] == 1 else all_agents
fig_count = 0
if all_agents:
best_agent = np.argmax(reward_history.sum(axis=0))
worst_agent = np.argmin(reward_history.sum(axis=0))
rand_agent = np.random.choice(
list(
set(range(0, reward_history.shape[1])) - set([best_agent, worst_agent])
)
)
print(
"Best agent: ",
best_agent,
"| Worst agent: ",
worst_agent,
"| Random Agent",
rand_agent,
)
# plot best and worst episodes data
plot_one_episode(
{k: np.array([v[best_agent] for v in vals]) for k, vals in ep_data.items()},
save_dir + "best_ep/",
)
plot_one_episode(
{
k: np.array([v[worst_agent] for v in vals])
for k, vals in ep_data.items()
},
save_dir + "worst_ep/",
)
plot_one_episode(
{k: np.array([v[rand_agent] for v in vals]) for k, vals in ep_data.items()},
save_dir + f"rand_ep_{rand_agent}/",
)
tgrid = np.linspace(0, len(reward_history), len(control_history))
args = {
"best_agent": best_agent,
"worst_agent": worst_agent,
"rand_agent": rand_agent,
"fig_count": fig_count,
"save_dir": save_dir,
"reward_history": reward_history,
"control_history": control_history,
"state_history": state_history,
"tgrid": tgrid,
}
shared_metrics = [plot_reward, plot_velocities, plot_actions_box_plot]
task_metrics = []
task_flag = state_history[0, 0, 5].astype(int)
task_metrics = []
if task_flag == 0: # GoToXY
task_metrics = [
plot_trajectories_GoToXY,
plot_distance_GoToXY,
plot_all_distances_GoToXY,
]
elif task_flag == 1: # GoToPose
task_metrics = [
plot_trajectories_GoToXY,
plot_distance_GoToPose,
plot_all_distances_GoToPose,
]
elif task_flag == 2: # TrackXYVelocity
task_metrics = [
plot_distance_TrackXYVelocity,
plot_all_distances_TrackXYVelocity,
]
elif task_flag == 3: # TrackXYOVelocity
task_metrics = [
plot_distance_TrackXYOVelocity,
plot_all_distances_TrackXYOVelocity,
]
else:
task_metrics = []
metrics = shared_metrics + task_metrics
for metric in metrics:
fig_count = metric(**args)
args["fig_count"] = fig_count
else:
fig_count = plot_one_episode(
{k: np.array([v[0] for v in vals]) for k, vals in ep_data.items()},
save_dir + "first_ep/",
)
def plot_distance_GoToXY(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst distance over all episodes."""
all_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_distances.mean(axis=1) - all_distances.std(axis=1),
all_distances.mean(axis=1) + all_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_distances.mean(axis=1) - 2 * all_distances.std(axis=1),
all_distances.mean(axis=1) + 2 * all_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(f"Mean, best and worst distances over {all_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "mean_best_worst_position_distances")
return fig_count
def plot_all_distances_GoToXY(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
**kwargs,
) -> int:
"""
Plot all distances over all episodes."""
all_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_distances.shape[1]):
ax.plot(
tgrid, all_distances[:, j], alpha=1.0, color=cmap(j % cmap.N), linewidth=1.0
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.title(f"All distances over {all_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_position_distances")
return fig_count
def plot_distance_GoToPose(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst distance over all episodes."""
all_position_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
shape = state_history.shape[:-1]
all_heading_distances = np.arctan2(
state_history[:, :, 9].flatten(), state_history[:, :, 8].flatten()
)
all_heading_distances = all_heading_distances.reshape(shape)
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_position_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_position_distances.mean(axis=1) - all_position_distances.std(axis=1),
all_position_distances.mean(axis=1) + all_position_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_position_distances.mean(axis=1) - 2 * all_position_distances.std(axis=1),
all_position_distances.mean(axis=1) + 2 * all_position_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_position_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_position_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(
f"Mean, best and worst distances over {all_position_distances.shape[1]} episodes"
)
plt.grid()
plt.savefig(save_dir + "mean_best_worst_position_distances")
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_heading_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_heading_distances.mean(axis=1) - all_heading_distances.std(axis=1),
all_heading_distances.mean(axis=1) + all_heading_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_heading_distances.mean(axis=1) - 2 * all_heading_distances.std(axis=1),
all_heading_distances.mean(axis=1) + 2 * all_heading_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_heading_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_heading_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [rad]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(
f"Mean, best and worst distances over {all_heading_distances.shape[1]} episodes"
)
plt.grid()
plt.savefig(save_dir + "mean_best_worst_heading_distances")
return fig_count
def plot_all_distances_GoToPose(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
**kwargs,
) -> int:
"""
Plot all distances over all episodes."""
all_position_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
shape = state_history.shape[:-1]
all_heading_distances = np.arctan2(
state_history[:, :, 9].flatten(), state_history[:, :, 8].flatten()
)
all_heading_distances = all_heading_distances.reshape(shape)
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_position_distances.shape[1]):
ax.plot(
tgrid,
all_position_distances[:, j],
alpha=1.0,
color=cmap(j % cmap.N),
linewidth=1.0,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.title(f"All distances over {all_position_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_position_distances")
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_heading_distances.shape[1]):
ax.plot(
tgrid,
all_heading_distances[:, j],
alpha=1.0,
color=cmap(j % cmap.N),
linewidth=1.0,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [rad]")
plt.title(f"All distances over {all_heading_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_heading_distances")
return fig_count
def plot_distance_TrackXYVelocity(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst distance over all episodes."""
all_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_distances.mean(axis=1) - all_distances.std(axis=1),
all_distances.mean(axis=1) + all_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_distances.mean(axis=1) - 2 * all_distances.std(axis=1),
all_distances.mean(axis=1) + 2 * all_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(f"Mean, best and worst distances over {all_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "mean_best_worst_velocity_distances")
return fig_count
def plot_all_distances_TrackXYVelocity(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
**kwargs,
) -> int:
"""
Plot all distances over all episodes."""
all_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_distances.shape[1]):
ax.plot(
tgrid, all_distances[:, j], alpha=1.0, color=cmap(j % cmap.N), linewidth=1.0
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.title(f"All distances over {all_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_velocity_distances")
return fig_count
def plot_distance_TrackXYOVelocity(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst distance over all episodes."""
all_xy_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
all_omega_distances = np.linalg.norm(state_history[:, :, 8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_xy_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_xy_distances.mean(axis=1) - all_xy_distances.std(axis=1),
all_xy_distances.mean(axis=1) + all_xy_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_xy_distances.mean(axis=1) - 2 * all_xy_distances.std(axis=1),
all_xy_distances.mean(axis=1) + 2 * all_xy_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_xy_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_xy_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(
f"Mean, best and worst distances over {all_xy_distances.shape[1]} episodes"
)
plt.grid()
plt.savefig(save_dir + "mean_best_worst_velocity_distances")
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
all_omega_distances.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
all_omega_distances.mean(axis=1) - all_omega_distances.std(axis=1),
all_omega_distances.mean(axis=1) + all_omega_distances.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
all_omega_distances.mean(axis=1) - 2 * all_omega_distances.std(axis=1),
all_omega_distances.mean(axis=1) + 2 * all_omega_distances.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
all_omega_distances[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
all_omega_distances[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(
f"Mean, best and worst distances over {all_omega_distances.shape[1]} episodes"
)
plt.grid()
plt.savefig(save_dir + "mean_best_worst_velocity_distances")
return fig_count
def plot_all_distances_TrackXYOVelocity(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
**kwargs,
) -> int:
"""
Plot all distances over all episodes."""
all_xy_distances = np.linalg.norm(state_history[:, :, 6:8], axis=2)
all_omega_distances = np.linalg.norm(state_history[:, :, 8], axis=2)
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_xy_distances.shape[1]):
ax.plot(
tgrid,
all_xy_distances[:, j],
alpha=1.0,
color=cmap(j % cmap.N),
linewidth=1.0,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.title(f"All distances over {all_xy_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_velocity_distances")
fig_count += 1
fig, ax = plt.subplots()
cmap = cm.get_cmap("tab20")
for j in range(all_omega_distances.shape[1]):
ax.plot(
tgrid,
all_omega_distances[:, j],
alpha=1.0,
color=cmap(j % cmap.N),
linewidth=1.0,
)
plt.xlabel("Time steps")
plt.ylabel("Distance [rad/s]")
plt.title(f"All distances over {all_omega_distances.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "all_velocity_distances")
return fig_count
def plot_reward(
reward_history: np.ndarray,
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst reward over all episodes."""
fig_count += 1
fig, ax = plt.subplots()
ax.plot(
tgrid,
reward_history.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
reward_history.mean(axis=1) - reward_history.std(axis=1),
reward_history.mean(axis=1) + reward_history.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
reward_history.mean(axis=1) - 2 * reward_history.std(axis=1),
reward_history.mean(axis=1) + 2 * reward_history.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
reward_history[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
reward_history[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Reward")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(f"Mean, best and worst reward over {state_history.shape[1]} episodes")
plt.grid()
plt.savefig(save_dir + "mean_best_worst_rewards")
return fig_count
def plot_velocities(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
best_agent: int,
worst_agent: int,
fig_count: int,
**kwargs,
) -> int:
"""
Plot mean, std_dev, best and worst velocities over all episodes."""
fig_count += 1
fig, ax = plt.subplots()
ang_vel_z = state_history[:, :, 4:5][:, :, 0] # getting rid of the extra dimension
ax.plot(
tgrid,
ang_vel_z.mean(axis=1),
alpha=0.5,
color="blue",
label="mean_dist",
linewidth=1.5,
)
ax.fill_between(
tgrid,
ang_vel_z.mean(axis=1) - ang_vel_z.std(axis=1),
ang_vel_z.mean(axis=1) + ang_vel_z.std(axis=1),
color="blue",
alpha=0.4,
)
ax.fill_between(
tgrid,
ang_vel_z.mean(axis=1) - 2 * ang_vel_z.std(axis=1),
ang_vel_z.mean(axis=1) + 2 * ang_vel_z.std(axis=1),
color="blue",
alpha=0.2,
)
ax.plot(
tgrid,
ang_vel_z[:, best_agent],
alpha=0.5,
color="green",
label="best",
linewidth=1.5,
)
ax.plot(
tgrid,
ang_vel_z[:, worst_agent],
alpha=0.5,
color="red",
label="worst",
linewidth=1.5,
)
plt.xlabel("Time steps")
plt.ylabel("Angular speed [rad/s]")
plt.legend(["mean", "best", "worst", "1-std", "2-std"], loc="best")
plt.title(
f"Angular speed of mean, best and worst agents {ang_vel_z.shape[1]} episodes"
)
plt.grid()
plt.savefig(save_dir + "mean_best_worst_ang_velocities")
return fig_count
def plot_actions_histogram(
control_history: np.ndarray, save_dir: str, fig_count: int, **kwargs
) -> int:
"""
Plot mean number of thrusts over all episodes."""
fig_count += 1
plt.figure(fig_count)
plt.clf()
control_history = control_history.reshape(
(control_history.shape[1], control_history.shape[0], control_history.shape[2])
)
control_history = np.array([c for c in control_history])
freq = pd.DataFrame(
data=np.array(
[control_history[i].sum(axis=0) for i in range(control_history.shape[0])]
),
columns=[f"T{i+1}" for i in range(control_history.shape[2])],
)
mean_freq = freq.mean()
plt.bar(mean_freq.index, mean_freq.values)
plt.title(f"Mean number of thrusts in {control_history.shape[0]} episodes")
plt.savefig(save_dir + "mean_actions_histogram")
return fig_count
def plot_actions_box_plot(
control_history: np.ndarray, save_dir: str, fig_count: int, **kwargs
) -> int:
"""
Plot box plot of actions over all episodes."""
fig_count += 1
plt.figure(fig_count)
plt.clf()
control_history = control_history.reshape(
(control_history.shape[1], control_history.shape[0], control_history.shape[2])
)
control_history = np.array([c for c in control_history])
freq = pd.DataFrame(
data=np.array(
[control_history[i].sum(axis=0) for i in range(control_history.shape[0])]
),
columns=[f"T{i+1}" for i in range(control_history.shape[2])],
)
sns.boxplot(data=freq, orient="h")
plt.title(f"Mean number of thrusts in {control_history.shape[0]} episodes")
plt.savefig(save_dir + "actions_boxplot")
return fig_count
def plot_trajectories_GoToXY(
state_history: np.ndarray, save_dir: str, fig_count: int, **kwargs
) -> int:
"""
Plot trajectories of all agents in 2D space."""
fig_count += 1
plt.figure(fig_count)
plt.clf()
positions = state_history[:, :, 6:8]
cmap = cm.get_cmap("tab20")
for j in range(positions.shape[1]):
col = cmap(
j % cmap.N
) # Select a color from the colormap based on the current index
plt.plot(
positions[:, j, 0], positions[:, j, 1], color=col, alpha=1.0, linewidth=0.75
)
plt.xlabel("X [m]")
plt.ylabel("Y [m]")
plt.grid(alpha=0.3)
plt.title(f"Trajectories in 2D space [{positions.shape[1]} episodes]")
plt.gcf().dpi = 200
plt.savefig(save_dir + "multi_trajectories")
return fig_count
def plot_one_episode(
ep_data: dict,
save_dir: str = None,
show: bool = False,
debug: bool = False,
fig_count: int = 0,
) -> None:
"""
Plot episode metrics for a single agent.
ep_data: dictionary containing episode data
save_dir: directory where to save the plots
all_agents: if True, plot average results over all agents, if False only the first agent is plotted.
"""
os.makedirs(save_dir, exist_ok=True)
control_history = ep_data["act"]
reward_history = ep_data["rews"]
state_history = ep_data["obs"]
# save data to csv file
pd.DataFrame.to_csv(pd.DataFrame(control_history), save_dir + "actions.csv")
shared_metrics = [
plot_single_linear_vel,
plot_single_angular_vel,
plot_single_absolute_heading,
plot_single_rewards,
plot_single_action_histogram,
plot_single_actions,
]
if debug:
debug_metrics = [plot_single_heading_cos_sin]
else:
debug_metrics = []
# setting the right task_data labels based on the task fla.
task_flag = state_history[0, 5].astype(int)
task_metrics = []
if task_flag == 0: # GoToXY
task_data_label = ["error_x", "error_y"]
task_metrics = [
plot_single_xy_position,
plot_single_xy_position_error,
plot_single_GoToXY_distance_to_target,
plot_single_GoToXY_log_distance_to_target,
]
elif task_flag == 1: # GoToPose
task_data_label = [
"error_x",
"error_y",
"cos_error_heading",
"sin_error_heading",
]
task_metrics = [
plot_single_xy_position,
plot_single_xy_pose,
plot_single_xy_position_error,
plot_single_heading_error,
plot_single_xy_position_heading,
plot_single_GoToPose_distance_to_target,
plot_single_GoToPose_log_distance_to_target,
]
elif task_flag == 2: # TrackXYVelocity
task_data_label = ["error_vx", "error_vy"]
task_metrics = [
plot_single_TrackXYVelocity_distance_to_target,
plot_single_TrackXYVelocity_log_distance_to_target,
]
elif task_flag == 3: # TrackXYOVelocity
task_data_label = ["error_vx", "error_vy", "error_omega"]
task_metrics = [
plot_single_TrackXYOVelocity_distance_to_target,
plot_single_TrackXYOVelocity_log_distance_to_target,
]
else:
task_data_label = []
task_metrics = []
# Generate plots
metrics = shared_metrics + task_metrics + debug_metrics
tgrid = np.linspace(0, len(control_history), len(control_history))
args = {
"state_history": state_history,
"control_history": control_history,
"reward_history": reward_history,
"save_dir": save_dir,
"fig_count": fig_count,
"show": show,
"tgrid": tgrid,
}
for metric in metrics:
fig_count = metric(**args)
args["fig_count"] = fig_count
df_cols = [
"cos_theta",
"sin_theta",
"lin_vel_x",
"lin_vel_y",
"ang_vel_z",
"task_flag",
] + task_data_label
pd.DataFrame.to_csv(
pd.DataFrame(state_history[:, : len(df_cols)], columns=df_cols),
save_dir + "states_episode.csv",
)
fig_count = 0
def plot_single_linear_vel(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot linear velocity of a single agent."""
lin_vels = state_history[:, 2:4]
# plot linear velocity
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, lin_vels[:, 0], color=cm.get_cmap("tab20")(0))
plt.plot(tgrid, lin_vels[:, 1], color=cm.get_cmap("tab20")(2))
plt.xlabel("Time steps")
plt.ylabel("Velocity [m/s]")
plt.legend(["x", "y"], loc="best")
plt.title("Velocity state history")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_linear_velocity")
if show:
plt.show()
return fig_count
def plot_single_angular_vel(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot angular velocity of a single agent."""
ang_vel_z = state_history[:, 4:5]
# plot angular speed (z coordinate)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, ang_vel_z, color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Angular speed [rad/s]")
plt.legend(["z"], loc="best")
plt.title("Angular speed state history")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_angular_velocity")
if show:
plt.show()
return fig_count
def plot_single_heading_cos_sin(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot heading of a single agent with cos and sin representation."""
headings = state_history[:, :2]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, headings[:, 0], color=cm.get_cmap("tab20")(0)) # cos
plt.plot(tgrid, headings[:, 1], color=cm.get_cmap("tab20")(2)) # sin
plt.xlabel("Time steps")
plt.ylabel("Heading")
plt.legend(["cos(${\\theta}$)", "sin(${\\theta}$)"], loc="best")
plt.title("Heading state history")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_heading_cos_sin")
if show:
plt.show()
return fig_count
def plot_single_absolute_heading(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot heading of a single agent."""
headings = state_history[:, :2]
angles = np.arctan2(headings[:, 1], headings[:, 0])
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, angles, color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Angle [rad]")
plt.legend(["${\\theta}$"], loc="best")
plt.title("Angle state history")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_heading")
if show:
plt.show()
return fig_count
def plot_single_actions(
control_history: np.ndarray, save_dir: str, fig_count: int, show: bool, **kwargs
) -> int:
"""
Plot actions of a single agent."""
fig_count += 1
plt.figure(fig_count)
plt.clf()
control_history_df = pd.DataFrame(data=control_history)
fig, axes = plt.subplots(
len(control_history_df.columns), 1, sharex=True, figsize=(8, 6)
)
# Select subset of colors from a colormap
colormap = cm.get_cmap("tab20")
num_colors = len(control_history_df.columns)
colors = [colormap(i) for i in range(0, num_colors * 2, 2)]
for i, column in enumerate(control_history_df.columns):
control_history_df[column].plot(ax=axes[i], color=colors[i])
axes[i].set_ylabel(f"T{column}")
plt.xlabel("Time steps")
if save_dir:
fig.savefig(save_dir + "single_actions")
if show:
plt.show()
return fig_count
def plot_single_action_histogram(
control_history: np.ndarray, save_dir: str, fig_count: int, show: bool, **kwargs
) -> int:
"""
Plot histogram of actions of a single agent."""
fig_count += 1
plt.figure(fig_count)
plt.clf()
control_history = np.array(control_history)
actions_df = pd.DataFrame(
control_history, columns=[f"T{i+1}" for i in range(control_history.shape[1])]
)
freq = actions_df.sum()
plt.bar(freq.index, freq.values, color=cm.get_cmap("tab20")(0))
plt.title("Number of thrusts in episode")
plt.tight_layout()
if save_dir:
plt.savefig(save_dir + "single_actions_hist")
if show:
plt.show()
return fig_count
def plot_single_rewards(
reward_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot rewards of a single agent."""
if any(reward_history):
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, reward_history, color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Reward")
plt.legend(["reward"], loc="best")
plt.title("Reward history")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_reward")
if show:
plt.show()
return fig_count
def plot_single_xy_position_error(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot position error of a single agent."""
pos_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, pos_error[:, 0], color=cm.get_cmap("tab20")(0))
plt.plot(tgrid, pos_error[:, 1], color=cm.get_cmap("tab20")(2))
plt.xlabel("Time steps")
plt.ylabel("Position [m]")
plt.legend(["x position", "y position"], loc="best")
plt.title("Position Error")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_xy_position_error")
if show:
plt.show()
return fig_count
def plot_single_heading_error(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot heading error of a single agent."""
heading_error = state_history[:, 8:]
heading_error = np.arctan2(heading_error[:, 1], heading_error[:, 0])
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, heading_error, color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Heading [rad]")
plt.title("Heading error")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_heading_heading_error")
if show:
plt.show()
return fig_count
def plot_single_xy_position(
state_history: np.ndarray, save_dir: str, fig_count: int, show: bool, **kwargs
) -> int:
"""
Plot position of a single agent."""
pos_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
# Set aspect ratio to be equal
plt.gca().set_aspect("equal", adjustable="box")
x, y = pos_error[:, 0], pos_error[:, 1]
fig, ax = plt.subplots(figsize=(6, 6))
# Setting the limit of x and y direction to define which portion to zoom
x1, x2, y1, y2 = -0.07, 0.07, -0.08, 0.08
if y[0] > 0 and x[0] > 0:
location = 4
else:
location = 2 if (y[0] < 0 and x[0] < 0) else 1
axins = inset_axes(ax, width=1.5, height=1.25, loc=location)
ax.plot(x, y, color=cm.get_cmap("tab20")(0))
ax.set_xlabel("X [m]")
ax.set_ylabel("Y [m]")
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
axins.plot(x, y)
if save_dir:
fig.savefig(save_dir + "single_xy_trajectory")
if show:
plt.show()
return fig_count
def plot_single_xy_pose(
state_history: np.ndarray, save_dir: str, fig_count: int, show: bool, **kwargs
) -> int:
"""
Plot position of a single agent."""
pos_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
# Set aspect ratio to be equal
plt.gca().set_aspect("equal", adjustable="box")
# Get the heading error values
heading_error = state_history[:, 8:]
heading_error = np.abs(np.arctan2(heading_error[:, 1], heading_error[:, 0]))
x, y = pos_error[:, 0], pos_error[:, 1]
segments = [
np.column_stack([x[i : i + 2], y[i : i + 2]]) for i in range(len(x) - 1)
]
fig, ax = plt.subplots(figsize=(7, 6))
# make sure that the plot won't be limited between 0 and 1, ensuring the limits derive from the x, y coordinates plus a margin
margin = 0.08
ax.set_xlim(min(x) - margin, max(x) + margin)
ax.set_ylim(min(y) - margin, max(y) + margin)
lc = LineCollection(segments, cmap="jet", array=heading_error)
line = ax.add_collection(lc)
plt.colorbar(line, label="heading error [rad]")
# ax.plot(x, y, color=cm.get_cmap('tab20')(0))
plt.grid(alpha=0.3)
ax.set_xlabel("X [m]")
ax.set_ylabel("Y [m]")
plt.grid(alpha=0.3)
if save_dir:
fig.savefig(save_dir + "single_pose_trajectory")
if show:
plt.show()
return fig_count
def plot_single_xy_position_heading(
state_history: np.ndarray, save_dir: str, fig_count: int, show: bool, **kwargs
) -> int:
"""
Plot position of a single agent."""
pos_error = state_history[:, 6:8]
heading = state_history[:, :2]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
# Set aspect ratio to be equal
plt.gca().set_aspect("equal", adjustable="box")
x, y = pos_error[:, 0], pos_error[:, 1]
c, s = heading[:, 0], heading[:, 1]
fig, ax = plt.subplots(figsize=(6, 6))
# Setting the limit of x and y direction to define which portion to zoom
x1, x2, y1, y2 = -0.07, 0.07, -0.08, 0.08
if y[0] > 0 and x[0] > 0:
location = 4
else:
location = 2 if (y[0] < 0 and x[0] < 0) else 1
axins = inset_axes(ax, width=1.5, height=1.25, loc=location)
ax.plot(x, y, color=cm.get_cmap("tab20")(0))
ax.quiver(x[::10], y[::10], s[::10], c[::10], color=cm.get_cmap("tab20")(0))
ax.set_xlabel("X [m]")
ax.set_ylabel("Y [m]")
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
axins.plot(x, y)
if save_dir:
fig.savefig(save_dir + "single_xy_trajectory_with_heading")
if show:
plt.show()
return fig_count
def plot_single_GoToXY_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot distance to target of a single agent."""
pos_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(
tgrid,
np.linalg.norm(np.array([pos_error[:, 0], pos_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_position_target")
if show:
plt.show()
return fig_count
def plot_single_GoToXY_log_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot log distance to target of a single agent."""
pos_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(
tgrid,
np.linalg.norm(np.array([pos_error[:, 0], pos_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Log distance [m]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_position_target")
if show:
plt.show()
return fig_count
def plot_single_GoToPose_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot distance to target of a single agent."""
pos_error = state_history[:, 6:8]
heading_error = state_history[:, 8:]
heading_error = np.arctan2(heading_error[:, 1], heading_error[:, 0])
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(
tgrid,
np.linalg.norm(np.array([pos_error[:, 0], pos_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_position_target")
if show:
plt.show()
# plot heading
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, np.abs(heading_error), color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Heading [rad]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_heading_target")
if show:
plt.show()
return fig_count
def plot_single_GoToPose_log_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot log distance to target of a single agent."""
pos_error = state_history[:, 6:8]
heading_error = state_history[:, 8:]
heading_error = np.arctan2(heading_error[:, 1], heading_error[:, 0])
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(
tgrid,
np.linalg.norm(np.array([pos_error[:, 0], pos_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Log distance [m]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_position_target")
if show:
plt.show()
# plot heading
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(tgrid, np.abs(heading_error), color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Log distance [rad]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_heading_target")
if show:
plt.show()
return fig_count
def plot_single_TrackXYVelocity_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot distance to target of a single agent."""
vel_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(
tgrid,
np.linalg.norm(np.array([vel_error[:, 0], vel_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_velocity_target")
if show:
plt.show()
return fig_count
def plot_single_TrackXYVelocity_log_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot log distance to target of a single agent."""
vel_error = state_history[:, 6:8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(
tgrid,
np.linalg.norm(np.array([vel_error[:, 0], vel_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Log distance [m/s]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_velocity_target")
if show:
plt.show()
return fig_count
def plot_single_TrackXYOVelocity_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot distance to target of a single agent."""
vel_error = state_history[:, 6:8]
omega_error = state_history[:, 8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(
tgrid,
np.linalg.norm(np.array([vel_error[:, 0], vel_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Distance [m/s]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_linear_velocity_target")
if show:
plt.show()
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.plot(tgrid, np.abs(omega_error), color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Distance [rad/s]")
plt.legend(["abs dist"], loc="best")
plt.title("Distance to target")
plt.grid()
if save_dir:
plt.savefig(save_dir + "single_distance_to_angular_velocity_target")
if show:
plt.show()
return fig_count
def plot_single_TrackXYOVelocity_log_distance_to_target(
state_history: np.ndarray,
tgrid: np.ndarray,
save_dir: str,
fig_count: int,
show: bool,
**kwargs,
) -> int:
"""
Plot log distance to target of a single agent."""
vel_error = state_history[:, 6:8]
omega_error = state_history[:, 8]
# plot position (x, y coordinates)
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(
tgrid,
np.linalg.norm(np.array([vel_error[:, 0], vel_error[:, 1]]), axis=0),
color=cm.get_cmap("tab20")(0),
)
plt.xlabel("Time steps")
plt.ylabel("Log distance [m/s]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_linear_velocity_target")
if show:
plt.show()
fig_count += 1
plt.figure(fig_count)
plt.clf()
plt.yscale("log")
plt.plot(tgrid, np.abs(omega_error), color=cm.get_cmap("tab20")(0))
plt.xlabel("Time steps")
plt.ylabel("Log distance [rad/s]")
plt.legend(["x-y dist"], loc="best")
plt.title("Log distance to target")
plt.grid(True)
if save_dir:
plt.savefig(save_dir + "single_log_distance_to_angular_velocity_target")
if show:
plt.show()
return fig_count
| 47,201 | Python | 26.946714 | 130 | 0.571513 |
elharirymatteo/RANS/omniisaacgymenvs/utils/task_util.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def initialize_task(config, env, init_sim=True):
from .config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
def import_tasks():
from omniisaacgymenvs.tasks.allegro_hand import AllegroHandTask
from omniisaacgymenvs.tasks.ant import AntLocomotionTask
from omniisaacgymenvs.tasks.anymal import AnymalTask
from omniisaacgymenvs.tasks.anymal_terrain import AnymalTerrainTask
from omniisaacgymenvs.tasks.ball_balance import BallBalanceTask
from omniisaacgymenvs.tasks.cartpole import CartpoleTask
from omniisaacgymenvs.tasks.cartpole_camera import CartpoleCameraTask
from omniisaacgymenvs.tasks.crazyflie import CrazyflieTask
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_pick import (
FactoryTaskNutBoltPick,
)
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_place import (
FactoryTaskNutBoltPlace,
)
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_screw import (
FactoryTaskNutBoltScrew,
)
from omniisaacgymenvs.tasks.franka_cabinet import FrankaCabinetTask
from omniisaacgymenvs.tasks.franka_deformable import FrankaDeformableTask
from omniisaacgymenvs.tasks.humanoid import HumanoidLocomotionTask
from omniisaacgymenvs.tasks.ingenuity import IngenuityTask
from omniisaacgymenvs.tasks.quadcopter import QuadcopterTask
from omniisaacgymenvs.tasks.shadow_hand import ShadowHandTask
from omniisaacgymenvs.tasks.crazyflie import CrazyflieTask
from omniisaacgymenvs.tasks.MFP2D_Virtual import MFP2DVirtual
from omniisaacgymenvs.tasks.MFP2D_Virtual_Dock import MFP2DVirtual_Dock
from omniisaacgymenvs.tasks.MFP2D_Virtual_Dock_RGBD import MFP2DVirtual_Dock_RGBD
from omniisaacgymenvs.tasks.MFP3D_Virtual import MFP3DVirtual
from omniisaacgymenvs.tasks.warp.ant import (
AntLocomotionTask as AntLocomotionTaskWarp,
)
from omniisaacgymenvs.tasks.warp.cartpole import CartpoleTask as CartpoleTaskWarp
from omniisaacgymenvs.tasks.warp.humanoid import (
HumanoidLocomotionTask as HumanoidLocomotionTaskWarp,
)
# Mappings from strings to environments
task_map = {
"AllegroHand": AllegroHandTask,
"Ant": AntLocomotionTask,
"Anymal": AnymalTask,
"AnymalTerrain": AnymalTerrainTask,
"BallBalance": BallBalanceTask,
"Cartpole": CartpoleTask,
"CartpoleCamera": CartpoleCameraTask,
"FactoryTaskNutBoltPick": FactoryTaskNutBoltPick,
"FactoryTaskNutBoltPlace": FactoryTaskNutBoltPlace,
"FactoryTaskNutBoltScrew": FactoryTaskNutBoltScrew,
"FrankaCabinet": FrankaCabinetTask,
"FrankaDeformable": FrankaDeformableTask,
"Humanoid": HumanoidLocomotionTask,
"Ingenuity": IngenuityTask,
"Quadcopter": QuadcopterTask,
"Crazyflie": CrazyflieTask,
"ShadowHand": ShadowHandTask,
"ShadowHandOpenAI_FF": ShadowHandTask,
"ShadowHandOpenAI_LSTM": ShadowHandTask,
"MFP2DVirtual": MFP2DVirtual,
"MFP2DVirtual_Dock": MFP2DVirtual_Dock,
"MFP2DVirtual_Dock_RGBD": MFP2DVirtual_Dock_RGBD,
"MFP3DVirtual": MFP3DVirtual,
}
task_map_warp = {
"Cartpole": CartpoleTaskWarp,
"Ant": AntLocomotionTaskWarp,
"Humanoid": HumanoidLocomotionTaskWarp,
}
return task_map, task_map_warp
def initialize_task(config, env, init_sim=True):
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
task_map, task_map_warp = import_tasks()
cfg = sim_config.config
if cfg["warp"]:
task_map = task_map_warp
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
backend = "warp" if cfg["warp"] else "torch"
rendering_dt = sim_config.get_physics_params()["rendering_dt"]
env.set_task(
task=task,
sim_params=sim_config.get_physics_params(),
backend=backend,
init_sim=init_sim,
rendering_dt=rendering_dt,
)
return task
| 5,657 | Python | 40.602941 | 85 | 0.742443 |
elharirymatteo/RANS/omniisaacgymenvs/utils/domain_randomization/randomize.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import copy
import numpy as np
import torch
import omni
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.extensions import enable_extension
class Randomizer:
def __init__(self, main_config, task_config):
self._cfg = task_config
self._config = main_config
self.randomize = False
dr_config = self._cfg.get("domain_randomization", None)
self.distributions = dict()
self.active_domain_randomizations = dict()
self._observations_dr_params = None
self._actions_dr_params = None
if dr_config is not None:
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize and randomization_params is not None:
self.randomize = True
self.min_frequency = dr_config.get("min_frequency", 1)
# import DR extensions
enable_extension("omni.replicator.isaac")
import omni.replicator.core as rep
import omni.replicator.isaac as dr
self.rep = rep
self.dr = dr
def apply_on_startup_domain_randomization(self, task):
if self.randomize:
torch.manual_seed(self._config["seed"])
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
for opt in randomization_params.keys():
if opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
for attribute, params in randomization_params["rigid_prim_views"][view_name].items():
params = randomization_params["rigid_prim_views"][view_name][attribute]
if attribute in ["scale", "mass", "density"] and params is not None:
if "on_startup" in params.keys():
if not set(
("operation", "distribution", "distribution_parameters")
).issubset(params["on_startup"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} "
+ "on_startup are provided: operation, distribution, distribution_parameters."
)
view = task.world.scene._scene_registry.rigid_prim_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
sync_dim_noise=True,
)
elif attribute == "mass":
self.randomize_mass_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
)
elif attribute == "density":
self.randomize_density_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
)
if opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
for attribute, params in randomization_params["articulation_views"][view_name].items():
params = randomization_params["articulation_views"][view_name][attribute]
if attribute in ["scale"] and params is not None:
if "on_startup" in params.keys():
if not set(
("operation", "distribution", "distribution_parameters")
).issubset(params["on_startup"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} "
+ "on_startup are provided: operation, distribution, distribution_parameters."
)
view = task.world.scene._scene_registry.articulated_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
sync_dim_noise=True,
)
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("On Startup Domain randomization will not be applied.")
def set_up_domain_randomization(self, task):
if self.randomize:
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
self.rep.set_global_seed(self._config["seed"])
with self.dr.trigger.on_rl_frame(num_envs=self._cfg["env"]["numEnvs"]):
for opt in randomization_params.keys():
if opt == "observations":
self._set_up_observations_randomization(task)
elif opt == "actions":
self._set_up_actions_randomization(task)
elif opt == "simulation":
if randomization_params["simulation"] is not None:
self.distributions["simulation"] = dict()
self.dr.physics_view.register_simulation_context(task.world)
for attribute, params in randomization_params["simulation"].items():
self._set_up_simulation_randomization(attribute, params)
elif opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
self.distributions["rigid_prim_views"] = dict()
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
self.distributions["rigid_prim_views"][view_name] = dict()
self.dr.physics_view.register_rigid_prim_view(
rigid_prim_view=task.world.scene._scene_registry.rigid_prim_views[
view_name
],
)
for attribute, params in randomization_params["rigid_prim_views"][
view_name
].items():
if attribute not in ["scale", "density"]:
self._set_up_rigid_prim_view_randomization(view_name, attribute, params)
elif opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
self.distributions["articulation_views"] = dict()
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
self.distributions["articulation_views"][view_name] = dict()
self.dr.physics_view.register_articulation_view(
articulation_view=task.world.scene._scene_registry.articulated_views[
view_name
],
)
for attribute, params in randomization_params["articulation_views"][
view_name
].items():
if attribute not in ["scale"]:
self._set_up_articulation_view_randomization(view_name, attribute, params)
self.rep.orchestrator.run()
if self._config.get("enable_recording", False):
# we need to deal with initializing render product here because it has to be initialized after orchestrator.run.
# otherwise, replicator will stop the simulation
task._env.create_viewport_render_product(resolution=(task.viewport_camera_width, task.viewport_camera_height))
if not task.is_extension:
task.world.render()
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("Domain randomization will not be applied.")
def _set_up_observations_randomization(self, task):
task.randomize_observations = True
self._observations_dr_params = self._cfg["domain_randomization"]["randomization_params"]["observations"]
if self._observations_dr_params is None:
raise ValueError(f"Observations randomization parameters are not provided.")
if "on_reset" in self._observations_dr_params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(
self._observations_dr_params["on_reset"].keys()
):
raise ValueError(
f"Please ensure the following observations on_reset randomization parameters are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("observations", "on_reset")] = np.array(
self._observations_dr_params["on_reset"]["distribution_parameters"]
)
if "on_interval" in self._observations_dr_params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
self._observations_dr_params["on_interval"].keys()
):
raise ValueError(
f"Please ensure the following observations on_interval randomization parameters are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("observations", "on_interval")] = np.array(
self._observations_dr_params["on_interval"]["distribution_parameters"]
)
self._observations_counter_buffer = torch.zeros(
(self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]
)
self._observations_correlated_noise = torch.zeros(
(self._cfg["env"]["numEnvs"], task.num_observations), device=self._config["rl_device"]
)
def _set_up_actions_randomization(self, task):
task.randomize_actions = True
self._actions_dr_params = self._cfg["domain_randomization"]["randomization_params"]["actions"]
if self._actions_dr_params is None:
raise ValueError(f"Actions randomization parameters are not provided.")
if "on_reset" in self._actions_dr_params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(
self._actions_dr_params["on_reset"].keys()
):
raise ValueError(
f"Please ensure the following actions on_reset randomization parameters are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("actions", "on_reset")] = np.array(
self._actions_dr_params["on_reset"]["distribution_parameters"]
)
if "on_interval" in self._actions_dr_params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
self._actions_dr_params["on_interval"].keys()
):
raise ValueError(
f"Please ensure the following actions on_interval randomization parameters are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("actions", "on_interval")] = np.array(
self._actions_dr_params["on_interval"]["distribution_parameters"]
)
self._actions_counter_buffer = torch.zeros(
(self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]
)
self._actions_correlated_noise = torch.zeros(
(self._cfg["env"]["numEnvs"], task.num_actions), device=self._config["rl_device"]
)
def apply_observations_randomization(self, observations, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._observations_counter_buffer[env_ids] = 0
self._observations_counter_buffer += 1
if "on_reset" in self._observations_dr_params.keys():
observations[:] = self._apply_correlated_noise(
buffer_type="observations",
buffer=observations,
reset_ids=env_ids,
operation=self._observations_dr_params["on_reset"]["operation"],
distribution=self._observations_dr_params["on_reset"]["distribution"],
distribution_parameters=self._observations_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._observations_dr_params.keys():
randomize_ids = (
(self._observations_counter_buffer >= self._observations_dr_params["on_interval"]["frequency_interval"])
.nonzero(as_tuple=False)
.squeeze(-1)
)
self._observations_counter_buffer[randomize_ids] = 0
observations[:] = self._apply_uncorrelated_noise(
buffer=observations,
randomize_ids=randomize_ids,
operation=self._observations_dr_params["on_interval"]["operation"],
distribution=self._observations_dr_params["on_interval"]["distribution"],
distribution_parameters=self._observations_dr_params["on_interval"]["distribution_parameters"],
)
return observations
def apply_actions_randomization(self, actions, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._actions_counter_buffer[env_ids] = 0
self._actions_counter_buffer += 1
if "on_reset" in self._actions_dr_params.keys():
actions[:] = self._apply_correlated_noise(
buffer_type="actions",
buffer=actions,
reset_ids=env_ids,
operation=self._actions_dr_params["on_reset"]["operation"],
distribution=self._actions_dr_params["on_reset"]["distribution"],
distribution_parameters=self._actions_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._actions_dr_params.keys():
randomize_ids = (
(self._actions_counter_buffer >= self._actions_dr_params["on_interval"]["frequency_interval"])
.nonzero(as_tuple=False)
.squeeze(-1)
)
self._actions_counter_buffer[randomize_ids] = 0
actions[:] = self._apply_uncorrelated_noise(
buffer=actions,
randomize_ids=randomize_ids,
operation=self._actions_dr_params["on_interval"]["operation"],
distribution=self._actions_dr_params["on_interval"]["distribution"],
distribution_parameters=self._actions_dr_params["on_interval"]["distribution_parameters"],
)
return actions
def _apply_uncorrelated_noise(self, buffer, randomize_ids, operation, distribution, distribution_parameters):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(
mean=distribution_parameters[0],
std=distribution_parameters[1],
size=(len(randomize_ids), buffer.shape[1]),
device=self._config["rl_device"],
)
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(
(len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]
) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"])
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer[randomize_ids] += noise
elif operation == "scaling":
buffer[randomize_ids] *= noise
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _apply_correlated_noise(self, buffer_type, buffer, reset_ids, operation, distribution, distribution_parameters):
if buffer_type == "observations":
correlated_noise_buffer = self._observations_correlated_noise
elif buffer_type == "actions":
correlated_noise_buffer = self._actions_correlated_noise
if len(reset_ids) > 0:
if distribution == "gaussian" or distribution == "normal":
correlated_noise_buffer[reset_ids] = torch.normal(
mean=distribution_parameters[0],
std=distribution_parameters[1],
size=(len(reset_ids), buffer.shape[1]),
device=self._config["rl_device"],
)
elif distribution == "uniform":
correlated_noise_buffer[reset_ids] = (
distribution_parameters[1] - distribution_parameters[0]
) * torch.rand(
(len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]
) + distribution_parameters[
0
]
elif distribution == "loguniform" or distribution == "log_uniform":
correlated_noise_buffer[reset_ids] = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"])
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer += correlated_noise_buffer
elif operation == "scaling":
buffer *= correlated_noise_buffer
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _set_up_simulation_randomization(self, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for simulation {attribute} is not provided.")
if attribute in self.dr.SIMULATION_CONTEXT_ATTRIBUTES:
self.distributions["simulation"][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for simulation {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("simulation", attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"operation": params["on_reset"]["operation"]}
self.distributions["simulation"][attribute]["on_reset"] = self._generate_distribution(
dimension=self.dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_simulation_context(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for simulation {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("simulation", attribute, "on_interval")] = np.array(
params["on_interval"]["distribution_parameters"]
)
kwargs = {"operation": params["on_interval"]["operation"]}
self.distributions["simulation"][attribute]["on_interval"] = self._generate_distribution(
dimension=self.dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_simulation_context(**kwargs)
def _set_up_rigid_prim_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for rigid prim view {view_name} {attribute} is not provided.")
if attribute in self.dr.RIGID_PRIM_ATTRIBUTES:
self.distributions["rigid_prim_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] = self._generate_distribution(
dimension=self.dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_rigid_prim_view(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_interval")] = np.array(
params["on_interval"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute][
"on_interval"
] = self._generate_distribution(
dimension=self.dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_rigid_prim_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _set_up_articulation_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for articulation view {view_name} {attribute} is not provided.")
if attribute in self.dr.ARTICULATION_ATTRIBUTES:
self.distributions["articulation_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute][
"on_reset"
] = self._generate_distribution(
dimension=self.dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_articulation_view(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[
("articulation_views", view_name, attribute, "on_interval")
] = np.array(params["on_interval"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute][
"on_interval"
] = self._generate_distribution(
dimension=self.dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_articulation_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _generate_distribution(self, view_name, attribute, dimension, params):
dist_params = self._sanitize_distribution_parameters(attribute, dimension, params["distribution_parameters"])
if params["distribution"] == "uniform":
return self.rep.distribution.uniform(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "gaussian" or params["distribution"] == "normal":
return self.rep.distribution.normal(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "loguniform" or params["distribution"] == "log_uniform":
return self.rep.distribution.log_uniform(tuple(dist_params[0]), tuple(dist_params[1]))
else:
raise ValueError(
f"The provided distribution for {view_name} {attribute} is not supported. "
+ "Options: uniform, gaussian/normal, loguniform/log_uniform"
)
def _sanitize_distribution_parameters(self, attribute, dimension, params):
distribution_parameters = np.array(params)
if distribution_parameters.shape == (2,):
# if the user does not provide a set of parameters for each dimension
dist_params = [[distribution_parameters[0]] * dimension, [distribution_parameters[1]] * dimension]
elif distribution_parameters.shape == (2, dimension):
# if the user provides a set of parameters for each dimension in the format [[...], [...]]
dist_params = distribution_parameters.tolist()
elif attribute in ["material_properties", "body_inertias"] and distribution_parameters.shape == (2, 3):
# if the user only provides the parameters for one body in the articulation, assume the same parameters for all other links
dist_params = [
[distribution_parameters[0]] * (dimension // 3),
[distribution_parameters[1]] * (dimension // 3),
]
else:
raise ValueError(
f"The provided distribution_parameters for {view_name} {attribute} is invalid due to incorrect dimensions."
)
return dist_params
def set_dr_distribution_parameters(self, distribution_parameters, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
if distribution_path[0] == "observations":
if len(distribution_parameters) == 2:
self._observations_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(
f"Please provide distribution_parameters for observations {distribution_path[1]} "
+ "in the form of [dist_param_1, dist_param_2]"
)
elif distribution_path[0] == "actions":
if len(distribution_parameters) == 2:
self._actions_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(
f"Please provide distribution_parameters for actions {distribution_path[1]} "
+ "in the form of [dist_param_1, dist_param_2]"
)
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][
distribution_path[2]
]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if (
replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform"
or replicator_distribution.node.get_node_type().get_node_type()
== "omni.replicator.core.OgnSampleLogUniform"
):
dimension = len(self.dr.utils.get_distribution_params(replicator_distribution, ["lower"])[0])
dist_params = self._sanitize_distribution_parameters(
distribution_path[-2], dimension, distribution_parameters
)
self.dr.utils.set_distribution_params(
replicator_distribution, {"lower": dist_params[0], "upper": dist_params[1]}
)
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
dimension = len(self.dr.utils.get_distribution_params(replicator_distribution, ["mean"])[0])
dist_params = self._sanitize_distribution_parameters(
distribution_path[-2], dimension, distribution_parameters
)
self.dr.utils.set_distribution_params(
replicator_distribution, {"mean": dist_params[0], "std": dist_params[1]}
)
def get_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
if distribution_path[0] == "observations":
return self._observations_dr_params[distribution_path[1]]["distribution_parameters"]
elif distribution_path[0] == "actions":
return self._actions_dr_params[distribution_path[1]]["distribution_parameters"]
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][
distribution_path[2]
]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if (
replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform"
or replicator_distribution.node.get_node_type().get_node_type()
== "omni.replicator.core.OgnSampleLogUniform"
):
return self.dr.utils.get_distribution_params(replicator_distribution, ["lower", "upper"])
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
return self.dr.utils.get_distribution_params(replicator_distribution, ["mean", "std"])
def get_initial_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
return self.active_domain_randomizations[distribution_path].copy()
def _generate_noise(self, distribution, distribution_parameters, size, device):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(
mean=distribution_parameters[0], std=distribution_parameters[1], size=size, device=device
)
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(
size, device=device
) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand(size, device=device)
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
return noise
def randomize_scale_on_startup(self, view, distribution, distribution_parameters, operation, sync_dim_noise=True):
scales = view.get_local_scales()
if sync_dim_noise:
dist_params = np.asarray(
self._sanitize_distribution_parameters(attribute="scale", dimension=1, params=distribution_parameters)
)
noise = (
self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device).repeat(3, 1).T
)
else:
dist_params = np.asarray(
self._sanitize_distribution_parameters(attribute="scale", dimension=3, params=distribution_parameters)
)
noise = torch.zeros((view.count, 3), device=view._device)
for i in range(3):
noise[:, i] = self._generate_noise(distribution, dist_params[:, i], (view.count,), view._device)
if operation == "additive":
scales += noise
elif operation == "scaling":
scales *= noise
elif operation == "direct":
scales = noise
else:
print(f"The specified {operation} operation type is not supported.")
view.set_local_scales(scales=scales)
def randomize_mass_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
masses = view.get_masses()
dist_params = np.asarray(
self._sanitize_distribution_parameters(
attribute=f"{view.name} mass", dimension=1, params=distribution_parameters
)
)
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_masses = view.set_masses
if operation == "additive":
masses += noise
elif operation == "scaling":
masses *= noise
elif operation == "direct":
masses = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_masses(masses)
def randomize_density_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
densities = view.get_densities()
dist_params = np.asarray(
self._sanitize_distribution_parameters(
attribute=f"{view.name} density", dimension=1, params=distribution_parameters
)
)
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_densities = view.set_densities
if operation == "additive":
densities += noise
elif operation == "scaling":
densities *= noise
elif operation == "direct":
densities = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_densities(densities)
| 46,049 | Python | 58.650259 | 136 | 0.55593 |
elharirymatteo/RANS/omniisaacgymenvs/utils/rlgames/rlgames_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Callable
import numpy as np
import torch
from rl_games.algos_torch import torch_ext
from rl_games.common import env_configurations, vecenv
from rl_games.common.algo_observer import AlgoObserver
class RLGPUAlgoObserver(AlgoObserver):
"""Allows us to log stats from the env along with the algorithm running stats."""
def __init__(self):
pass
def after_init(self, algo):
self.algo = algo
self.mean_scores = torch_ext.AverageMeter(1, self.algo.games_to_track).to(
self.algo.ppo_device
)
self.ep_infos = []
self.direct_info = {}
self.writer = self.algo.writer
def process_infos(self, infos, done_indices):
assert isinstance(infos, dict), "RLGPUAlgoObserver expects dict info"
if isinstance(infos, dict):
if "episode" in infos:
self.ep_infos.append(infos["episode"])
if len(infos) > 0 and isinstance(
infos, dict
): # allow direct logging from env
self.direct_info = {}
for k, v in infos.items():
# only log scalars
if (
isinstance(v, float)
or isinstance(v, int)
or (isinstance(v, torch.Tensor) and len(v.shape) == 0)
):
self.direct_info[k] = v
def after_clear_stats(self):
self.mean_scores.clear()
def after_print_stats(self, frame, epoch_num, total_time):
if self.ep_infos:
for key in self.ep_infos[0]:
infotensor = torch.tensor([], device=self.algo.device)
for ep_info in self.ep_infos:
# handle scalar and zero dimensional tensor infos
if not isinstance(ep_info[key], torch.Tensor):
ep_info[key] = torch.Tensor([ep_info[key]])
if len(ep_info[key].shape) == 0:
ep_info[key] = ep_info[key].unsqueeze(0)
infotensor = torch.cat(
(infotensor, ep_info[key].to(self.algo.device))
)
value = torch.mean(infotensor)
self.writer.add_scalar("Episode/" + key, value, epoch_num)
self.ep_infos.clear()
for k, v in self.direct_info.items():
self.writer.add_scalar(f"{k}/frame", v, frame)
self.writer.add_scalar(f"{k}/iter", v, epoch_num)
self.writer.add_scalar(f"{k}/time", v, total_time)
if self.mean_scores.current_size > 0:
mean_scores = self.mean_scores.get_mean()
self.writer.add_scalar("scores/mean", mean_scores, frame)
self.writer.add_scalar("scores/iter", mean_scores, epoch_num)
self.writer.add_scalar("scores/time", mean_scores, total_time)
class RLGPUEnv(vecenv.IVecEnv):
def __init__(self, config_name, num_actors, **kwargs):
self.env = env_configurations.configurations[config_name]["env_creator"](
**kwargs
)
def step(self, action):
return self.env.step(action)
def reset(self):
return self.env.reset()
def get_number_of_agents(self):
return self.env.get_number_of_agents()
def get_env_info(self):
info = {}
info["action_space"] = self.env.action_space
info["observation_space"] = self.env.observation_space
if self.env.num_states > 0:
info["state_space"] = self.env.state_space
print(info["action_space"], info["observation_space"], info["state_space"])
else:
print(info["action_space"], info["observation_space"])
return info
| 5,321 | Python | 39.318182 | 87 | 0.622439 |
elharirymatteo/RANS/omniisaacgymenvs/utils/rlgames/rlgames_train_mt.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import copy
import datetime
import os
import queue
import threading
import traceback
import hydra
from omegaconf import DictConfig
from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT
import omniisaacgymenvs
from omniisaacgymenvs.envs.vec_env_rlgames_mt import VecEnvRLGamesMT
from omniisaacgymenvs.utils.config_utils.path_utils import retrieve_checkpoint_path
from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import *
from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from omniisaacgymenvs.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv
from omniisaacgymenvs.utils.task_util import initialize_task
from rl_games.common import env_configurations, vecenv
from rl_games.torch_runner import Runner
class RLGTrainer:
def __init__(self, cfg, cfg_dict):
self.cfg = cfg
self.cfg_dict = cfg_dict
# ensure checkpoints can be specified as relative paths
self._bad_checkpoint = False
if self.cfg.checkpoint:
self.cfg.checkpoint = retrieve_checkpoint_path(self.cfg.checkpoint)
if not self.cfg.checkpoint:
self._bad_checkpoint = True
def launch_rlg_hydra(self, env):
# `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally.
# We use the helper function here to specify the environment config.
self.cfg_dict["task"]["test"] = self.cfg.test
# register the rl-games adapter to use inside the runner
vecenv.register("RLGPU", lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register("rlgpu", {"vecenv_type": "RLGPU", "env_creator": lambda **kwargs: env})
self.rlg_config_dict = omegaconf_to_dict(self.cfg.train)
def run(self):
# create runner and set the settings
runner = Runner(RLGPUAlgoObserver())
# add evaluation parameters
if self.cfg.evaluation:
player_config = self.rlg_config_dict["params"]["config"].get("player", {})
player_config["evaluation"] = True
player_config["update_checkpoint_freq"] = 100
player_config["dir_to_monitor"] = os.path.dirname(self.cfg.checkpoint)
self.rlg_config_dict["params"]["config"]["player"] = player_config
module_path = os.path.abspath(os.path.join(os.path.dirname(omniisaacgymenvs.__file__)))
self.rlg_config_dict["params"]["config"]["train_dir"] = os.path.join(module_path, "runs")
# load config
runner.load(copy.deepcopy(self.rlg_config_dict))
runner.reset()
# dump config dict
experiment_dir = os.path.join(module_path, "runs", self.cfg.train.params.config.name)
os.makedirs(experiment_dir, exist_ok=True)
with open(os.path.join(experiment_dir, "config.yaml"), "w") as f:
f.write(OmegaConf.to_yaml(self.cfg))
time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if self.cfg.wandb_activate:
# Make sure to install WandB if you actually use this.
import wandb
run_name = f"{self.cfg.wandb_name}_{time_str}"
wandb.init(
project=self.cfg.wandb_project,
group=self.cfg.wandb_group,
entity=self.cfg.wandb_entity,
config=self.cfg_dict,
sync_tensorboard=True,
id=run_name,
resume="allow",
monitor_gym=True,
)
runner.run(
{"train": not self.cfg.test, "play": self.cfg.test, "checkpoint": self.cfg.checkpoint, "sigma": None}
)
if self.cfg.wandb_activate:
wandb.finish()
class Trainer(TrainerMT):
def __init__(self, trainer, env):
self.ppo_thread = None
self.action_queue = None
self.data_queue = None
self.trainer = trainer
self.is_running = False
self.env = env
self.create_task()
self.run()
def create_task(self):
self.trainer.launch_rlg_hydra(self.env)
# task = initialize_task(self.trainer.cfg_dict, self.env, init_sim=False)
self.task = self.env.task
def run(self):
self.is_running = True
self.action_queue = queue.Queue(1)
self.data_queue = queue.Queue(1)
if "mt_timeout" in self.trainer.cfg_dict:
self.env.initialize(self.action_queue, self.data_queue, self.trainer.cfg_dict["mt_timeout"])
else:
self.env.initialize(self.action_queue, self.data_queue)
self.ppo_thread = PPOTrainer(self.env, self.task, self.trainer)
self.ppo_thread.daemon = True
self.ppo_thread.start()
def stop(self):
self.env.stop = True
self.env.clear_queues()
if self.action_queue:
self.action_queue.join()
if self.data_queue:
self.data_queue.join()
if self.ppo_thread:
self.ppo_thread.join()
self.action_queue = None
self.data_queue = None
self.ppo_thread = None
self.is_running = False
class PPOTrainer(threading.Thread):
def __init__(self, env, task, trainer):
super().__init__()
self.env = env
self.task = task
self.trainer = trainer
def run(self):
from omni.isaac.gym.vec_env import TaskStopException
print("starting ppo...")
try:
self.trainer.run()
# trainer finished - send stop signal to main thread
self.env.should_run = False
self.env.send_actions(None, block=False)
except TaskStopException:
print("Task Stopped!")
self.env.should_run = False
self.env.send_actions(None, block=False)
except Exception as e:
# an error occurred on the RL side - signal stop to main thread
print(traceback.format_exc())
self.env.should_run = False
self.env.send_actions(None, block=False)
| 7,633 | Python | 37.17 | 119 | 0.654395 |
elharirymatteo/RANS/omniisaacgymenvs/utils/config_utils/sim_config.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import copy
import carb
import numpy as np
import omni.usd
import torch
from omni.isaac.core.utils.extensions import enable_extension
from omniisaacgymenvs.utils.config_utils.default_scene_params import *
class SimConfig:
def __init__(self, config: dict = None):
if config is None:
config = dict()
self._config = config
self._cfg = config.get("task", dict())
self._parse_config()
if self._config["test"] == True:
self._sim_params["enable_scene_query_support"] = True
if (
self._config["headless"] == True
and not self._sim_params["enable_cameras"]
and not self._config["enable_livestream"]
and not self._config.get("enable_recording", False)
):
self._sim_params["use_fabric"] = False
self._sim_params["enable_viewport"] = False
else:
self._sim_params["enable_viewport"] = True
enable_extension("omni.kit.viewport.bundle")
if self._sim_params["enable_cameras"] or self._config.get("enable_recording", False):
enable_extension("omni.replicator.isaac")
self._sim_params["warp"] = self._config["warp"]
self._sim_params["sim_device"] = self._config["sim_device"]
self._adjust_dt()
if self._sim_params["disable_contact_processing"]:
carb.settings.get_settings().set_bool("/physics/disableContactProcessing", True)
carb.settings.get_settings().set_bool("/physics/physxDispatcher", True)
# Force the background grid off all the time for RL tasks, to avoid the grid showing up in any RL camera task
carb.settings.get_settings().set("/app/viewport/grid/enabled", False)
# Disable framerate limiting which might cause rendering slowdowns
carb.settings.get_settings().set("/app/runLoops/main/rateLimitEnabled", False)
import omni.ui
# Dock floating UIs this might not be needed anymore as extensions dock themselves
# Method for docking a particular window to a location
def dock_window(space, name, location, ratio=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, ratio=ratio)
return window
# Acquire the main docking station
main_dockspace = omni.ui.Workspace.get_window("DockSpace")
dock_window(main_dockspace, "Content", omni.ui.DockPosition.BOTTOM, 0.3)
window = omni.ui.Workspace.get_window("Content")
if window:
window.visible = False
window = omni.ui.Workspace.get_window("Simulation Settings")
if window:
window.visible = False
# workaround for asset root search hang
carb.settings.get_settings().set_string(
"/persistent/isaac/asset_root/default",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.1",
)
carb.settings.get_settings().set_string(
"/persistent/isaac/asset_root/nvidia",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.1",
)
# make sure the correct USD update flags are set
if self._sim_params["use_fabric"]:
carb.settings.get_settings().set_bool("/physics/updateToUsd", False)
carb.settings.get_settings().set_bool("/physics/updateParticlesToUsd", False)
carb.settings.get_settings().set_bool("/physics/updateVelocitiesToUsd", False)
carb.settings.get_settings().set_bool("/physics/updateForceSensorsToUsd", False)
carb.settings.get_settings().set_bool("/physics/outputVelocitiesLocalSpace", False)
carb.settings.get_settings().set_bool("/physics/fabricUpdateTransformations", True)
carb.settings.get_settings().set_bool("/physics/fabricUpdateVelocities", False)
carb.settings.get_settings().set_bool("/physics/fabricUpdateForceSensors", False)
carb.settings.get_settings().set_bool("/physics/fabricUpdateJointStates", False)
def _parse_config(self):
# general sim parameter
self._sim_params = copy.deepcopy(default_sim_params)
self._default_physics_material = copy.deepcopy(default_physics_material)
sim_cfg = self._cfg.get("sim", None)
if sim_cfg is not None:
for opt in sim_cfg.keys():
if opt in self._sim_params:
if opt == "default_physics_material":
for material_opt in sim_cfg[opt]:
self._default_physics_material[material_opt] = sim_cfg[opt][material_opt]
else:
self._sim_params[opt] = sim_cfg[opt]
else:
print("Sim params does not have attribute: ", opt)
self._sim_params["default_physics_material"] = self._default_physics_material
# physx parameters
self._physx_params = copy.deepcopy(default_physx_params)
if sim_cfg is not None and "physx" in sim_cfg:
for opt in sim_cfg["physx"].keys():
if opt in self._physx_params:
self._physx_params[opt] = sim_cfg["physx"][opt]
else:
print("Physx sim params does not have attribute: ", opt)
self._sanitize_device()
def _sanitize_device(self):
if self._sim_params["use_gpu_pipeline"]:
self._physx_params["use_gpu"] = True
# device should be in sync with pipeline
if self._sim_params["use_gpu_pipeline"]:
self._config["sim_device"] = f"cuda:{self._config['device_id']}"
else:
self._config["sim_device"] = "cpu"
# also write to physics params for setting sim device
self._physx_params["sim_device"] = self._config["sim_device"]
print("Pipeline: ", "GPU" if self._sim_params["use_gpu_pipeline"] else "CPU")
print("Pipeline Device: ", self._config["sim_device"])
print("Sim Device: ", "GPU" if self._physx_params["use_gpu"] else "CPU")
def parse_actor_config(self, actor_name):
actor_params = copy.deepcopy(default_actor_options)
if "sim" in self._cfg and actor_name in self._cfg["sim"]:
actor_cfg = self._cfg["sim"][actor_name]
for opt in actor_cfg.keys():
if actor_cfg[opt] != -1 and opt in actor_params:
actor_params[opt] = actor_cfg[opt]
elif opt not in actor_params:
print("Actor params does not have attribute: ", opt)
return actor_params
def _get_actor_config_value(self, actor_name, attribute_name, attribute=None):
actor_params = self.parse_actor_config(actor_name)
if attribute is not None:
if attribute_name not in actor_params:
return attribute.Get()
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
elif actor_params["override_usd_defaults"] and not attribute.IsAuthored():
return self._physx_params[attribute_name]
else:
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
def _adjust_dt(self):
# re-evaluate rendering dt to simulate physics substeps
physics_dt = self.sim_params["dt"]
rendering_dt = self.sim_params["rendering_dt"]
# by default, rendering dt = physics dt
if rendering_dt <= 0:
rendering_dt = physics_dt
self.task_config["renderingInterval"] = max(round((1/physics_dt) / (1/rendering_dt)), 1)
# we always set rendering dt to be the same as physics dt, stepping is taken care of in VecEnvRLGames
self.sim_params["rendering_dt"] = physics_dt
@property
def sim_params(self):
return self._sim_params
@property
def config(self):
return self._config
@property
def task_config(self):
return self._cfg
@property
def physx_params(self):
return self._physx_params
def get_physics_params(self):
return {**self.sim_params, **self.physx_params}
def _get_physx_collision_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
return physx_collision_api
def _get_physx_rigid_body_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI(prim)
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
return physx_rb_api
def _get_physx_articulation_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
arti_api = PhysxSchema.PhysxArticulationAPI(prim)
if not arti_api:
arti_api = PhysxSchema.PhysxArticulationAPI.Apply(prim)
return arti_api
def set_contact_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
contact_offset = physx_collision_api.GetContactOffsetAttr()
# if not contact_offset:
# contact_offset = physx_collision_api.CreateContactOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "contact_offset", contact_offset)
if value != -1:
contact_offset.Set(value)
def set_rest_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
rest_offset = physx_collision_api.GetRestOffsetAttr()
# if not rest_offset:
# rest_offset = physx_collision_api.CreateRestOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "rest_offset", rest_offset)
if value != -1:
rest_offset.Set(value)
def set_position_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_position_iteration_count = physx_rb_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_position_iteration_count", solver_position_iteration_count
)
if value != -1:
solver_position_iteration_count.Set(value)
def set_velocity_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_velocity_iteration_count = physx_rb_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_velocity_iteration_count", solver_velocity_iteration_count
)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_max_depenetration_velocity(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
max_depenetration_velocity = physx_rb_api.GetMaxDepenetrationVelocityAttr()
if value is None:
value = self._get_actor_config_value(name, "max_depenetration_velocity", max_depenetration_velocity)
if value != -1:
max_depenetration_velocity.Set(value)
def set_sleep_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
sleep_threshold = physx_rb_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_stabilization_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
stabilization_threshold = physx_rb_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def set_gyroscopic_forces(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
enable_gyroscopic_forces = physx_rb_api.GetEnableGyroscopicForcesAttr()
if value is None:
value = self._get_actor_config_value(name, "enable_gyroscopic_forces", enable_gyroscopic_forces)
if value != -1:
enable_gyroscopic_forces.Set(value)
def set_density(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
density = physx_rb_api.GetDensityAttr()
if value is None:
value = self._get_actor_config_value(name, "density", density)
if value != -1:
density.Set(value)
# auto-compute mass
self.set_mass(prim, 0.0)
def set_mass(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
mass = physx_rb_api.GetMassAttr()
if value is None:
value = self._get_actor_config_value(name, "mass", mass)
if value != -1:
mass.Set(value)
def retain_acceleration(self, prim):
# retain accelerations if running with more than one substep
physx_rb_api = self._get_physx_rigid_body_api(prim)
if self._sim_params["substeps"] > 1:
physx_rb_api.GetRetainAccelerationsAttr().Set(True)
def make_kinematic(self, name, prim, cfg, value=None):
# make rigid body kinematic (fixed base and no collision)
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
if value is None:
value = self._get_actor_config_value(name, "make_kinematic")
if value == True:
# parse through all children prims
prims = [prim]
while len(prims) > 0:
cur_prim = prims.pop(0)
rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath())
if rb:
rb.CreateKinematicEnabledAttr().Set(True)
children_prims = cur_prim.GetPrim().GetChildren()
prims = prims + children_prims
def set_articulation_position_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_position_iteration_count = arti_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_position_iteration_count", solver_position_iteration_count
)
if value != -1:
solver_position_iteration_count.Set(value)
def set_articulation_velocity_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_velocity_iteration_count = arti_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_velocity_iteration_count", solver_velocity_iteration_count
)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_articulation_sleep_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
sleep_threshold = arti_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_articulation_stabilization_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
stabilization_threshold = arti_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def apply_rigid_body_settings(self, name, prim, cfg, is_articulation):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
rb_api = UsdPhysics.RigidBodyAPI.Get(stage, prim.GetPath())
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPath())
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
# if it's a body in an articulation, it's handled at articulation root
if not is_articulation:
self.make_kinematic(name, prim, cfg, cfg["make_kinematic"])
self.set_position_iteration(name, prim, cfg["solver_position_iteration_count"])
self.set_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"])
self.set_max_depenetration_velocity(name, prim, cfg["max_depenetration_velocity"])
self.set_sleep_threshold(name, prim, cfg["sleep_threshold"])
self.set_stabilization_threshold(name, prim, cfg["stabilization_threshold"])
self.set_gyroscopic_forces(name, prim, cfg["enable_gyroscopic_forces"])
# density and mass
mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath())
if mass_api is None:
mass_api = UsdPhysics.MassAPI.Apply(prim)
mass_attr = mass_api.GetMassAttr()
density_attr = mass_api.GetDensityAttr()
if not mass_attr:
mass_attr = mass_api.CreateMassAttr()
if not density_attr:
density_attr = mass_api.CreateDensityAttr()
if cfg["density"] != -1:
density_attr.Set(cfg["density"])
mass_attr.Set(0.0) # mass is to be computed
elif cfg["override_usd_defaults"] and not density_attr.IsAuthored() and not mass_attr.IsAuthored():
density_attr.Set(self._physx_params["density"])
self.retain_acceleration(prim)
def apply_rigid_shape_settings(self, name, prim, cfg):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
# collision APIs
collision_api = UsdPhysics.CollisionAPI(prim)
if not collision_api:
collision_api = UsdPhysics.CollisionAPI.Apply(prim)
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
self.set_contact_offset(name, prim, cfg["contact_offset"])
self.set_rest_offset(name, prim, cfg["rest_offset"])
def apply_articulation_settings(self, name, prim, cfg):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
is_articulation = False
# check if is articulation
prims = [prim]
while len(prims) > 0:
prim_tmp = prims.pop(0)
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim_tmp.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim_tmp.GetPath())
if articulation_api or physx_articulation_api:
is_articulation = True
children_prims = prim_tmp.GetPrim().GetChildren()
prims = prims + children_prims
# parse through all children prims
prims = [prim]
while len(prims) > 0:
cur_prim = prims.pop(0)
rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath())
collision_body = UsdPhysics.CollisionAPI.Get(stage, cur_prim.GetPath())
articulation = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
if rb:
self.apply_rigid_body_settings(name, cur_prim, cfg, is_articulation)
if collision_body:
self.apply_rigid_shape_settings(name, cur_prim, cfg)
if articulation:
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, cur_prim.GetPath())
# enable self collisions
enable_self_collisions = physx_articulation_api.GetEnabledSelfCollisionsAttr()
if cfg["enable_self_collisions"] != -1:
enable_self_collisions.Set(cfg["enable_self_collisions"])
self.set_articulation_position_iteration(name, cur_prim, cfg["solver_position_iteration_count"])
self.set_articulation_velocity_iteration(name, cur_prim, cfg["solver_velocity_iteration_count"])
self.set_articulation_sleep_threshold(name, cur_prim, cfg["sleep_threshold"])
self.set_articulation_stabilization_threshold(name, cur_prim, cfg["stabilization_threshold"])
children_prims = cur_prim.GetPrim().GetChildren()
prims = prims + children_prims
| 22,563 | Python | 43.769841 | 117 | 0.634446 |
elharirymatteo/RANS/omniisaacgymenvs/utils/config_utils/default_scene_params.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
default_physx_params = {
### Per-scene settings
"use_gpu": False,
"worker_thread_count": 4,
"solver_type": 1, # 0: PGS, 1:TGS
"bounce_threshold_velocity": 0.2,
"friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact
# point will experience friction forces.
"friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the
# distance between the contacts is smaller than correlation distance.
# disabling these can be useful for debugging
"enable_sleeping": True,
"enable_stabilization": True,
# GPU buffers
"gpu_max_rigid_contact_count": 512 * 1024,
"gpu_max_rigid_patch_count": 80 * 1024,
"gpu_found_lost_pairs_capacity": 1024,
"gpu_found_lost_aggregate_pairs_capacity": 1024,
"gpu_total_aggregate_pairs_capacity": 1024,
"gpu_max_soft_body_contacts": 1024 * 1024,
"gpu_max_particle_contacts": 1024 * 1024,
"gpu_heap_capacity": 64 * 1024 * 1024,
"gpu_temp_buffer_capacity": 16 * 1024 * 1024,
"gpu_max_num_partitions": 8,
"gpu_collision_stack_size": 64 * 1024 * 1024,
### Per-actor settings ( can override in actor_options )
"solver_position_iteration_count": 4,
"solver_velocity_iteration_count": 1,
"sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep.
# Allowed range [0, max_float).
"stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may
# participate in stabilization. Allowed range [0, max_float).
### Per-body settings ( can override in actor_options )
"enable_gyroscopic_forces": False,
"density": 1000.0, # density to be used for bodies that do not specify mass or density
"max_depenetration_velocity": 100.0,
### Per-shape settings ( can override in actor_options )
"contact_offset": 0.02,
"rest_offset": 0.001,
}
default_physics_material = {"static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0}
default_sim_params = {
"gravity": [0.0, 0.0, -9.81],
"dt": 1.0 / 60.0,
"rendering_dt": -1.0, # we don't want to override this if it's set from cfg
"substeps": 1,
"use_gpu_pipeline": True,
"add_ground_plane": True,
"add_distant_light": True,
"use_fabric": True,
"enable_scene_query_support": False,
"enable_cameras": False,
"disable_contact_processing": False,
"default_physics_material": default_physics_material,
}
default_actor_options = {
# -1 means use authored value from USD or default values from default_sim_params if not explicitly authored in USD.
# If an attribute value is not explicitly authored in USD, add one with the value given here,
# which overrides the USD default.
"override_usd_defaults": False,
"make_kinematic": -1,
"enable_self_collisions": -1,
"enable_gyroscopic_forces": -1,
"solver_position_iteration_count": -1,
"solver_velocity_iteration_count": -1,
"sleep_threshold": -1,
"stabilization_threshold": -1,
"max_depenetration_velocity": -1,
"density": -1,
"mass": -1,
"contact_offset": -1,
"rest_offset": -1,
}
| 4,783 | Python | 44.132075 | 119 | 0.703951 |
elharirymatteo/RANS/omniisaacgymenvs/utils/config_utils/path_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import carb
from hydra.utils import to_absolute_path
def is_valid_local_file(path):
return os.path.isfile(path)
def is_valid_ov_file(path):
import omni.client
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
def download_ov_file(source_path, target_path):
import omni.client
result = omni.client.copy(source_path, target_path)
if result == omni.client.Result.OK:
return True
return False
def break_ov_path(path):
import omni.client
return omni.client.break_url(path)
def retrieve_checkpoint_path(path):
# check if it's a local path
if is_valid_local_file(path):
return to_absolute_path(path)
# check if it's an OV path
elif is_valid_ov_file(path):
ov_path = break_ov_path(path)
file_name = os.path.basename(ov_path.path)
target_path = f"checkpoints/{file_name}"
copy_to_local = download_ov_file(path, target_path)
return to_absolute_path(target_path)
else:
carb.log_error(f"Invalid checkpoint path: {path}. Does the file exist?")
return None
def get_experience(headless, enable_livestream, enable_viewport, enable_recording, kit_app):
if kit_app == '':
if enable_viewport:
import omniisaacgymenvs
experience = os.path.abspath(os.path.join(os.path.dirname(omniisaacgymenvs.__file__), '../apps/omni.isaac.sim.python.gym.camera.kit'))
else:
experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.kit'
if headless and not enable_livestream and not enable_recording:
experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.headless.kit'
else:
experience = kit_app
return experience
| 3,346 | Python | 35.780219 | 146 | 0.715481 |
elharirymatteo/RANS/omniisaacgymenvs/utils/hydra_cfg/hydra_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import hydra
from omegaconf import DictConfig, OmegaConf
## OmegaConf & Hydra Config
# Resolvers used in hydra configs (see https://omegaconf.readthedocs.io/en/2.1_branch/usage.html#resolvers)
if not OmegaConf.has_resolver("eq"):
OmegaConf.register_new_resolver("eq", lambda x, y: x.lower() == y.lower())
if not OmegaConf.has_resolver("contains"):
OmegaConf.register_new_resolver("contains", lambda x, y: x.lower() in y.lower())
if not OmegaConf.has_resolver("if"):
OmegaConf.register_new_resolver("if", lambda pred, a, b: a if pred else b)
# allows us to resolve default arguments which are copied in multiple places in the config. used primarily for
# num_ensv
if not OmegaConf.has_resolver("resolve_default"):
OmegaConf.register_new_resolver("resolve_default", lambda default, arg: default if arg == "" else arg)
| 2,394 | Python | 51.065216 | 110 | 0.767753 |
elharirymatteo/RANS/omniisaacgymenvs/utils/hydra_cfg/reformat.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Dict
from omegaconf import DictConfig, OmegaConf
def omegaconf_to_dict(d: DictConfig) -> Dict:
"""Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation."""
ret = {}
for k, v in d.items():
if isinstance(v, DictConfig):
ret[k] = omegaconf_to_dict(v)
else:
ret[k] = v
return ret
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionory."""
if type(val) == dict:
if not start:
print("")
nesting += 4
for k in val:
print(nesting * " ", end="")
print(k, end=": ")
print_dict(val[k], nesting, start=False)
else:
print(val)
| 2,313 | Python | 38.896551 | 95 | 0.707739 |
elharirymatteo/RANS/omniisaacgymenvs/utils/terrain_utils/terrain_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from math import sqrt
import numpy as np
from numpy.random import choice
from omni.isaac.core.prims import XFormPrim
from pxr import Gf, PhysxSchema, Sdf, UsdPhysics
from scipy import interpolate
def random_uniform_terrain(
terrain,
min_height,
max_height,
step=1,
downsampled_scale=None,
):
"""
Generate a uniform noise terrain
Parameters
terrain (SubTerrain): the terrain
min_height (float): the minimum height of the terrain [meters]
max_height (float): the maximum height of the terrain [meters]
step (float): minimum height change between two points [meters]
downsampled_scale (float): distance between two randomly sampled points ( musty be larger or equal to terrain.horizontal_scale)
"""
if downsampled_scale is None:
downsampled_scale = terrain.horizontal_scale
# switch parameters to discrete units
min_height = int(min_height / terrain.vertical_scale)
max_height = int(max_height / terrain.vertical_scale)
step = int(step / terrain.vertical_scale)
heights_range = np.arange(min_height, max_height + step, step)
height_field_downsampled = np.random.choice(
heights_range,
(
int(terrain.width * terrain.horizontal_scale / downsampled_scale),
int(terrain.length * terrain.horizontal_scale / downsampled_scale),
),
)
x = np.linspace(0, terrain.width * terrain.horizontal_scale, height_field_downsampled.shape[0])
y = np.linspace(0, terrain.length * terrain.horizontal_scale, height_field_downsampled.shape[1])
f = interpolate.RectBivariateSpline(y, x, height_field_downsampled)
x_upsampled = np.linspace(0, terrain.width * terrain.horizontal_scale, terrain.width)
y_upsampled = np.linspace(0, terrain.length * terrain.horizontal_scale, terrain.length)
z_upsampled = np.rint(f(y_upsampled, x_upsampled))
terrain.height_field_raw += z_upsampled.astype(np.int16)
return terrain
def sloped_terrain(terrain, slope=1):
"""
Generate a sloped terrain
Parameters:
terrain (SubTerrain): the terrain
slope (int): positive or negative slope
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * terrain.width)
terrain.height_field_raw[:, np.arange(terrain.length)] += (max_height * xx / terrain.width).astype(
terrain.height_field_raw.dtype
)
return terrain
def pyramid_sloped_terrain(terrain, slope=1, platform_size=1.0):
"""
Generate a sloped terrain
Parameters:
terrain (terrain): the terrain
slope (int): positive or negative slope
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
center_x = int(terrain.width / 2)
center_y = int(terrain.length / 2)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = (center_x - np.abs(center_x - xx)) / center_x
yy = (center_y - np.abs(center_y - yy)) / center_y
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * (terrain.width / 2))
terrain.height_field_raw += (max_height * xx * yy).astype(terrain.height_field_raw.dtype)
platform_size = int(platform_size / terrain.horizontal_scale / 2)
x1 = terrain.width // 2 - platform_size
x2 = terrain.width // 2 + platform_size
y1 = terrain.length // 2 - platform_size
y2 = terrain.length // 2 + platform_size
min_h = min(terrain.height_field_raw[x1, y1], 0)
max_h = max(terrain.height_field_raw[x1, y1], 0)
terrain.height_field_raw = np.clip(terrain.height_field_raw, min_h, max_h)
return terrain
def discrete_obstacles_terrain(terrain, max_height, min_size, max_size, num_rects, platform_size=1.0):
"""
Generate a terrain with gaps
Parameters:
terrain (terrain): the terrain
max_height (float): maximum height of the obstacles (range=[-max, -max/2, max/2, max]) [meters]
min_size (float): minimum size of a rectangle obstacle [meters]
max_size (float): maximum size of a rectangle obstacle [meters]
num_rects (int): number of randomly generated obstacles
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
max_height = int(max_height / terrain.vertical_scale)
min_size = int(min_size / terrain.horizontal_scale)
max_size = int(max_size / terrain.horizontal_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
(i, j) = terrain.height_field_raw.shape
height_range = [-max_height, -max_height // 2, max_height // 2, max_height]
width_range = range(min_size, max_size, 4)
length_range = range(min_size, max_size, 4)
for _ in range(num_rects):
width = np.random.choice(width_range)
length = np.random.choice(length_range)
start_i = np.random.choice(range(0, i - width, 4))
start_j = np.random.choice(range(0, j - length, 4))
terrain.height_field_raw[start_i : start_i + width, start_j : start_j + length] = np.random.choice(height_range)
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def wave_terrain(terrain, num_waves=1, amplitude=1.0):
"""
Generate a wavy terrain
Parameters:
terrain (terrain): the terrain
num_waves (int): number of sine waves across the terrain length
Returns:
terrain (SubTerrain): update terrain
"""
amplitude = int(0.5 * amplitude / terrain.vertical_scale)
if num_waves > 0:
div = terrain.length / (num_waves * np.pi * 2)
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
terrain.height_field_raw += (amplitude * np.cos(yy / div) + amplitude * np.sin(xx / div)).astype(
terrain.height_field_raw.dtype
)
return terrain
def stairs_terrain(terrain, step_width, step_height):
"""
Generate a stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the height of the step [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
num_steps = terrain.width // step_width
height = step_height
for i in range(num_steps):
terrain.height_field_raw[i * step_width : (i + 1) * step_width, :] += height
height += step_height
return terrain
def pyramid_stairs_terrain(terrain, step_width, step_height, platform_size=1.0):
"""
Generate stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the step_height [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height = 0
start_x = 0
stop_x = terrain.width
start_y = 0
stop_y = terrain.length
while (stop_x - start_x) > platform_size and (stop_y - start_y) > platform_size:
start_x += step_width
stop_x -= step_width
start_y += step_width
stop_y -= step_width
height += step_height
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = height
return terrain
def stepping_stones_terrain(terrain, stone_size, stone_distance, max_height, platform_size=1.0, depth=-10):
"""
Generate a stepping stones terrain
Parameters:
terrain (terrain): the terrain
stone_size (float): horizontal size of the stepping stones [meters]
stone_distance (float): distance between stones (i.e size of the holes) [meters]
max_height (float): maximum height of the stones (positive and negative) [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
depth (float): depth of the holes (default=-10.) [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
stone_size = int(stone_size / terrain.horizontal_scale)
stone_distance = int(stone_distance / terrain.horizontal_scale)
max_height = int(max_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height_range = np.arange(-max_height - 1, max_height, step=1)
start_x = 0
start_y = 0
terrain.height_field_raw[:, :] = int(depth / terrain.vertical_scale)
if terrain.length >= terrain.width:
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
start_x = np.random.randint(0, stone_size)
# fill first hole
stop_x = max(0, start_x - stone_distance)
terrain.height_field_raw[0:stop_x, start_y:stop_y] = np.random.choice(height_range)
# fill row
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(height_range)
start_x += stone_size + stone_distance
start_y += stone_size + stone_distance
elif terrain.width > terrain.length:
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
start_y = np.random.randint(0, stone_size)
# fill first hole
stop_y = max(0, start_y - stone_distance)
terrain.height_field_raw[start_x:stop_x, 0:stop_y] = np.random.choice(height_range)
# fill column
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(height_range)
start_y += stone_size + stone_distance
start_x += stone_size + stone_distance
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def convert_heightfield_to_trimesh(height_field_raw, horizontal_scale, vertical_scale, slope_threshold=None):
"""
Convert a heightfield array to a triangle mesh represented by vertices and triangles.
Optionally, corrects vertical surfaces above the provide slope threshold:
If (y2-y1)/(x2-x1) > slope_threshold -> Move A to A' (set x1 = x2). Do this for all directions.
B(x2,y2)
/|
/ |
/ |
(x1,y1)A---A'(x2',y1)
Parameters:
height_field_raw (np.array): input heightfield
horizontal_scale (float): horizontal scale of the heightfield [meters]
vertical_scale (float): vertical scale of the heightfield [meters]
slope_threshold (float): the slope threshold above which surfaces are made vertical. If None no correction is applied (default: None)
Returns:
vertices (np.array(float)): array of shape (num_vertices, 3). Each row represents the location of each vertex [meters]
triangles (np.array(int)): array of shape (num_triangles, 3). Each row represents the indices of the 3 vertices connected by this triangle.
"""
hf = height_field_raw
num_rows = hf.shape[0]
num_cols = hf.shape[1]
y = np.linspace(0, (num_cols - 1) * horizontal_scale, num_cols)
x = np.linspace(0, (num_rows - 1) * horizontal_scale, num_rows)
yy, xx = np.meshgrid(y, x)
if slope_threshold is not None:
slope_threshold *= horizontal_scale / vertical_scale
move_x = np.zeros((num_rows, num_cols))
move_y = np.zeros((num_rows, num_cols))
move_corners = np.zeros((num_rows, num_cols))
move_x[: num_rows - 1, :] += hf[1:num_rows, :] - hf[: num_rows - 1, :] > slope_threshold
move_x[1:num_rows, :] -= hf[: num_rows - 1, :] - hf[1:num_rows, :] > slope_threshold
move_y[:, : num_cols - 1] += hf[:, 1:num_cols] - hf[:, : num_cols - 1] > slope_threshold
move_y[:, 1:num_cols] -= hf[:, : num_cols - 1] - hf[:, 1:num_cols] > slope_threshold
move_corners[: num_rows - 1, : num_cols - 1] += (
hf[1:num_rows, 1:num_cols] - hf[: num_rows - 1, : num_cols - 1] > slope_threshold
)
move_corners[1:num_rows, 1:num_cols] -= (
hf[: num_rows - 1, : num_cols - 1] - hf[1:num_rows, 1:num_cols] > slope_threshold
)
xx += (move_x + move_corners * (move_x == 0)) * horizontal_scale
yy += (move_y + move_corners * (move_y == 0)) * horizontal_scale
# create triangle mesh vertices and triangles from the heightfield grid
vertices = np.zeros((num_rows * num_cols, 3), dtype=np.float32)
vertices[:, 0] = xx.flatten()
vertices[:, 1] = yy.flatten()
vertices[:, 2] = hf.flatten() * vertical_scale
triangles = -np.ones((2 * (num_rows - 1) * (num_cols - 1), 3), dtype=np.uint32)
for i in range(num_rows - 1):
ind0 = np.arange(0, num_cols - 1) + i * num_cols
ind1 = ind0 + 1
ind2 = ind0 + num_cols
ind3 = ind2 + 1
start = 2 * i * (num_cols - 1)
stop = start + 2 * (num_cols - 1)
triangles[start:stop:2, 0] = ind0
triangles[start:stop:2, 1] = ind3
triangles[start:stop:2, 2] = ind1
triangles[start + 1 : stop : 2, 0] = ind0
triangles[start + 1 : stop : 2, 1] = ind2
triangles[start + 1 : stop : 2, 2] = ind3
return vertices, triangles
def add_terrain_to_stage(stage, vertices, triangles, position=None, orientation=None):
num_faces = triangles.shape[0]
terrain_mesh = stage.DefinePrim("/World/terrain", "Mesh")
terrain_mesh.GetAttribute("points").Set(vertices)
terrain_mesh.GetAttribute("faceVertexIndices").Set(triangles.flatten())
terrain_mesh.GetAttribute("faceVertexCounts").Set(np.asarray([3] * num_faces))
terrain = XFormPrim(prim_path="/World/terrain", name="terrain", position=position, orientation=orientation)
UsdPhysics.CollisionAPI.Apply(terrain.prim)
# collision_api = UsdPhysics.MeshCollisionAPI.Apply(terrain.prim)
# collision_api.CreateApproximationAttr().Set("meshSimplification")
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(terrain.prim)
physx_collision_api.GetContactOffsetAttr().Set(0.02)
physx_collision_api.GetRestOffsetAttr().Set(0.00)
class SubTerrain:
def __init__(self, terrain_name="terrain", width=256, length=256, vertical_scale=1.0, horizontal_scale=1.0):
self.terrain_name = terrain_name
self.vertical_scale = vertical_scale
self.horizontal_scale = horizontal_scale
self.width = width
self.length = length
self.height_field_raw = np.zeros((self.width, self.length), dtype=np.int16)
| 17,645 | Python | 41.215311 | 147 | 0.649306 |
elharirymatteo/RANS/omniisaacgymenvs/utils/terrain_utils/create_terrain_demo.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os, sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SCRIPT_DIR)
import omni
from omni.isaac.kit import SimulationApp
import numpy as np
import torch
simulation_app = SimulationApp({"headless": False})
from abc import abstractmethod
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.prims import RigidPrimView, RigidPrim, XFormPrim
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import define_prim, get_prim_at_path
from omni.isaac.core.utils.nucleus import find_nucleus_server
from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.cloner import GridCloner
from pxr import UsdPhysics, UsdLux, UsdShade, Sdf, Gf, UsdGeom, PhysxSchema
from terrain_utils import *
class TerrainCreation(BaseTask):
def __init__(self, name, num_envs, num_per_row, env_spacing, config=None, offset=None,) -> None:
BaseTask.__init__(self, name=name, offset=offset)
self._num_envs = num_envs
self._num_per_row = num_per_row
self._env_spacing = env_spacing
self._device = "cpu"
self._cloner = GridCloner(self._env_spacing, self._num_per_row)
self._cloner.define_base_env(self.default_base_env_path)
define_prim(self.default_zero_env_path)
@property
def default_base_env_path(self):
return "/World/envs"
@property
def default_zero_env_path(self):
return f"{self.default_base_env_path}/env_0"
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight"))
distantLight.CreateIntensityAttr(2000)
self.get_terrain()
self.get_ball()
super().set_up_scene(scene)
prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs)
print(f"cloning {self._num_envs} environments...")
self._env_pos = self._cloner.clone(
source_prim_path="/World/envs/env_0",
prim_paths=prim_paths
)
return
def get_terrain(self):
# create all available terrain types
num_terains = 8
terrain_width = 12.
terrain_length = 12.
horizontal_scale = 0.25 # [m]
vertical_scale = 0.005 # [m]
num_rows = int(terrain_width/horizontal_scale)
num_cols = int(terrain_length/horizontal_scale)
heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16)
def new_sub_terrain():
return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale)
heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=-0.2, max_height=0.2, step=0.2, downsampled_scale=0.5).height_field_raw
heightfield[num_rows:2*num_rows, :] = sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[2*num_rows:3*num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[3*num_rows:4*num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=0.5, min_size=1., max_size=5., num_rects=20).height_field_raw
heightfield[4*num_rows:5*num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=2., amplitude=1.).height_field_raw
heightfield[5*num_rows:6*num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[6*num_rows:7*num_rows, :] = pyramid_stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[7*num_rows:8*num_rows, :] = stepping_stones_terrain(new_sub_terrain(), stone_size=1.,
stone_distance=1., max_height=0.5, platform_size=0.).height_field_raw
vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5)
position = np.array([-6.0, 48.0, 0])
orientation = np.array([0.70711, 0.0, 0.0, -0.70711])
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation)
def get_ball(self):
ball = DynamicSphere(prim_path=self.default_zero_env_path + "/ball",
name="ball",
translation=np.array([0.0, 0.0, 1.0]),
mass=0.5,
radius=0.2,)
def post_reset(self):
for i in range(self._num_envs):
ball_prim = self._stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}/ball")
color = 0.5 + 0.5 * np.random.random(3)
visual_material = PreviewSurface(prim_path=f"{self.default_base_env_path}/env_{i}/ball/Looks/visual_material", color=color)
binding_api = UsdShade.MaterialBindingAPI(ball_prim)
binding_api.Bind(visual_material.material, bindingStrength=UsdShade.Tokens.strongerThanDescendants)
def get_observations(self):
pass
def calculate_metrics(self) -> None:
pass
def is_done(self) -> None:
pass
if __name__ == "__main__":
world = World(
stage_units_in_meters=1.0,
rendering_dt=1.0/60.0,
backend="torch",
device="cpu",
)
num_envs = 800
num_per_row = 80
env_spacing = 0.56*2
terrain_creation_task = TerrainCreation(name="TerrainCreation",
num_envs=num_envs,
num_per_row=num_per_row,
env_spacing=env_spacing,
)
world.add_task(terrain_creation_task)
world.reset()
while simulation_app.is_running():
if world.is_playing():
if world.current_time_step_index == 0:
world.reset(soft=True)
world.step(render=True)
else:
world.step(render=True)
simulation_app.close() | 7,869 | Python | 43.213483 | 166 | 0.650654 |
elharirymatteo/RANS/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import omni.client
import omni.usd
from pxr import Sdf, UsdGeom
def update_reference(source_prim_path, source_reference_path, target_reference_path):
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
prim_spec = stage.GetRootLayer().GetPrimAtPath(prim.GetPath())
reference_list = prim_spec.referenceList
refs = reference_list.GetAddedOrExplicitItems()
if len(refs) > 0:
for ref in refs:
if ref.assetPath == source_reference_path:
prim.GetReferences().RemoveReference(ref)
prim.GetReferences().AddReference(assetPath=target_reference_path, primPath=prim.GetPath())
prims = prims + prim.GetChildren()
def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None):
"""Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path.
Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
"""
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
edits = Sdf.BatchNamespaceEdit()
while len(prims) > 0:
prim = prims.pop(0)
print(prim)
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform")
print(prim, new_xform)
edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0))
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
stage.GetRootLayer().Apply(edits)
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
def convert_asset_instanceable(asset_usd_path, source_prim_path, save_as_path=None, create_xforms=True):
"""Makes all mesh/geometry prims instanceable.
Can optionally add UsdGeom.Xform prim as parent for all mesh/geometry prims.
Makes a copy of the asset USD file, which will be used for referencing.
Updates asset file to convert all parent prims of mesh/geometry prims to reference cloned USD file.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
create_xforms (bool): Whether to add new UsdGeom.Xform prims to mesh/geometry prims.
"""
if create_xforms:
create_parent_xforms(asset_usd_path, source_prim_path, save_as_path)
asset_usd_path = save_as_path
instance_usd_path = ".".join(asset_usd_path.split(".")[:-1]) + "_meshes.usd"
omni.client.copy(asset_usd_path, instance_usd_path)
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
if prim:
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
parent_prim = prim.GetParent()
if parent_prim and not parent_prim.IsInstance():
parent_prim.GetReferences().AddReference(
assetPath=instance_usd_path, primPath=str(parent_prim.GetPath())
)
parent_prim.SetInstanceable(True)
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
| 5,627 | Python | 42.627907 | 111 | 0.67727 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/proprioceptive/base_sensor.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import numpy as np
from dataclasses import asdict
from omniisaacgymenvs.robots.sensors.proprioceptive.Type import *
class BaseSensorInterface:
"""
Base sensor class
"""
def __init__(self, sensor_cfg: Sensor_T):
"""
dt: float
inertial_to_sensor_frame: List[float]
sensor_frame_to_optical_frame: List[float]
"""
self.sensor_cfg = asdict(sensor_cfg)
self.dt = self.sensor_cfg["dt"]
self.body_to_sensor_frame = self.sensor_cfg["body_to_sensor_frame"]
self.sensor_frame_to_optical_frame = self.sensor_cfg[
"sensor_frame_to_optical_frame"
]
self._sensor_state = None
def update(self, state: State):
"""
state is the state of the rigid body to be simulated
Args:
state (State): state of the rigid body to be simulated
"""
raise NotImplementedError
def reset_idx(self, env_ids:torch.Tensor) -> None:
"""
reset sensor state of specified env.
Args:
env_ids (torch.Tensor): list of env ids to reset
"""
raise NotImplementedError
@property
def state(self):
"""
return sensor state
"""
raise NotImplementedError | 1,589 | Python | 27.90909 | 82 | 0.601007 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/proprioceptive/Type.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import numpy as np
import torch
import dataclasses
from typing import List
EPS = 1e-5
@dataclasses.dataclass
class Gyroscope_T:
"""
Gyroscope typing class.
Args:
noise_density (float): noise density of the gyroscope.
random_walk (float): random walk of the gyroscope.
bias_correlation_time (float): bias correlation time of the gyroscope.
turn_on_bias_sigma (float): turn on bias sigma of the gyroscope.
"""
noise_density: float = 0.0003393695767766752
random_walk: float = 3.878509448876288e-05
bias_correlation_time: float = 1.0e3
turn_on_bias_sigma: float = 0.008726646259971648
@dataclasses.dataclass
class Accelometer_T:
"""
Accelometer typing class.
Args:
noise_density (float): noise density of the accelometer.
random_walk (float): random walk of the accelometer.
bias_correlation_time (float): bias correlation time of the accelometer.
turn_on_bias_sigma (float): turn on bias sigma of the accelometer.
"""
noise_density: float = 0.004
random_walk: float = 0.006
bias_correlation_time: float = 300.0
turn_on_bias_sigma: float = 0.196
@dataclasses.dataclass
class Sensor_T:
"""
Sensor typing class.
Args:
dt (float): physics time resolution
inertial_to_sensor_frame (List[float]): transform from inertial frame (ENU) to sensor frame (FLU)
sensor_frame_to_optical_frame (List[float]): transform from sensor frame (FLU) to sensor optical optical frame (OPENCV)
"""
dt: float = 0.01
body_to_sensor_frame: List[float] = dataclasses.field(default_factory=list)
sensor_frame_to_optical_frame: List[float] = dataclasses.field(default_factory=list)
def __post_init__(self):
assert len(self.body_to_sensor_frame) == 4
assert len(self.sensor_frame_to_optical_frame) == 4
self.body_to_sensor_frame = torch.tensor(self.body_to_sensor_frame).to(torch.float32)
self.sensor_frame_to_optical_frame = torch.tensor(self.sensor_frame_to_optical_frame).to(torch.float32)
@dataclasses.dataclass
class IMU_T(Sensor_T):
"""
IMU typing class.
Args:
dt (float): physics time resolution
inertial_to_sensor_frame (List[float]): transform from inertial frame (ENU) to sensor frame (FLU)
sensor_frame_to_optical_frame (List[float]): transform from sensor frame (FLU) to sensor optical optical frame (OPENCV)
gravity_vector (List[float]): gravity vector in inertial frame
accel_param (Accelometer_T): accelometer parameter
gyro_param (Gyroscope_T): gyroscope parameter
"""
gyro_param: Gyroscope_T = Gyroscope_T()
accel_param: Accelometer_T = Accelometer_T()
gravity_vector: List[float] = dataclasses.field(default_factory=list)
def __post_init__(self):
super().__post_init__()
assert len(self.gravity_vector) == 3
self.gravity_vector = torch.tensor(self.gravity_vector).to(torch.float32)
@dataclasses.dataclass
class GPS_T(Sensor_T):
"""
GPS typing class.
Not implemented yet.
Args:
dt (float): physics time resolution
inertial_to_sensor_frame (List[float]): transform from inertial frame (ENU) to sensor frame (FLU)
sensor_frame_to_optical_frame (List[float]): transform from sensor frame (FLU) to sensor optical optical frame (OPENCV)
"""
def __post_init__(self):
super().__post_init__()
@dataclasses.dataclass
class State:
"""
State typing class of any rigid body (to be simulated) respective to inertial frame.
Args:
position (torch.float32): position of the body in inertial frame.
orientation (torch.float32): orientation of the body in inertial frame.
linear_velocity (torch.float32): linear velocity of the body in inertial frame.
angular_velocity (torch.float32): angular velocity of the body in inertial frame.
"""
position: torch.float32
orientation: torch.float32
linear_velocity: torch.float32
angular_velocity: torch.float32
def __post_init__(self):
assert len(self.position.shape) == 2, f"need to be batched tensor."
assert len(self.orientation.shape) == 2, f"need to be batched tensor."
assert len(self.linear_velocity.shape) == 2, f"need to be batched tensor."
assert len(self.angular_velocity.shape) == 2, f"need to be batched tensor."
@staticmethod
def quat_to_mat(quat: torch.Tensor) -> torch.Tensor:
"""
Convert batched quaternion to batched rotation matrix.
Args:
quat (torch.Tensor): batched quaternion.(..., 4)
"""
w, x, y, z = torch.unbind(quat, -1)
two_s = 2.0 / ((quat * quat).sum(-1) + EPS)
R = torch.stack(
(
1 - two_s * (y * y + z * z),
two_s * (x * y - z * w),
two_s * (x * z + y * w),
two_s * (x * y + z * w),
1 - two_s * (x * x + z * z),
two_s * (y * z - x * w),
two_s * (x * z - y * w),
two_s * (y * z + x * w),
1 - two_s * (x * x + y * y),
),
-1,
)
return R.reshape(quat.shape[:-1] + (3, 3))
@property
def body_transform(self) -> torch.float32:
"""
Return transform from inertial frame to body frame(= inverse of body pose).
T[:, :3, :3] = orientation.T
T[:, :3, 3] = - orientation.T @ position
Returns:
transform (torch.float32): transform matrix from inertial frame to body frame.
"""
transform = torch.zeros(self.position.shape[0], 4, 4).to(self.orientation.device)
orientation = self.quat_to_mat(self.orientation)
transform[:, :3, :3] = orientation.transpose(1, 2)
transform[:, :3, 3] = - 1 * torch.bmm(orientation.transpose(1, 2), self.position[:, :, None]).squeeze()
return transform
@dataclasses.dataclass
class ImuState:
"""
IMU state typing class.
Args:
angular_velocity (torch.float32): angular velocity of the body in body frame.
linear_acceleration (torch.float32): linear acceleration of the body in body frame.
"""
angular_velocity: torch.float32 = torch.zeros(1, 3)
linear_acceleration: torch.float32 = torch.zeros(1, 3)
def update(self, angular_velocity:torch.float32, linear_acceleration:torch.float32) -> None:
"""
Update internal attribute from arguments.
Args:
angular_velocity (torch.float32): angular velocity of the body in body frame.
linear_acceleration (torch.float32): linear acceleration of the body in body frame.
"""
self.angular_velocity = angular_velocity
self.linear_acceleration = linear_acceleration
def reset_idx(self, env_ids:torch.Tensor) -> None:
"""
Reset internal attribute of specified env to zero.
"""
self.angular_velocity[env_ids] = 0
self.linear_acceleration[env_ids] = 0
@property
def unite_imu(self) -> torch.float32:
"""
Return IMU state as a single tensor.
Returns:
imu (torch.float32): IMU state as a single tensor.
"""
return torch.cat([self.angular_velocity, self.linear_acceleration], dim=1) | 7,593 | Python | 37.548223 | 127 | 0.632951 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/proprioceptive/gps.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import numpy as numpy
from omniisaacgymenvs.robots.sensors.proprioceptive.base_sensor import BaseSensorInterface
from omniisaacgymenvs.robots.sensors.proprioceptive.Type import *
class GPSInterface(BaseSensorInterface):
"""
GPS sensor class to simulate GPS based on pegasus simulator
(https://github.com/PegasusSimulator/PegasusSimulator)
"""
def __init__(self, sensor_cfg: GPS_T):
"""
Args:
sensor_cfg (GPS_T): GPS sensor configuration.
"""
super().__init__(sensor_cfg) | 850 | Python | 33.039999 | 90 | 0.678824 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/proprioceptive/imu.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import numpy as numpy
import torch
from omniisaacgymenvs.robots.sensors.proprioceptive.base_sensor import BaseSensorInterface
from omniisaacgymenvs.robots.sensors.proprioceptive.Type import IMU_T, Accelometer_T, Gyroscope_T, State, ImuState
class IMUInterface(BaseSensorInterface):
"""
IMU sensor class to simulate accelometer and gyroscope based on pegasus simulator.
(https://github.com/PegasusSimulator/PegasusSimulator)
The way it works is that it takes the state information, directly published from physics engine,
and then add imu noise (white noise and time diffusing random walk) to state info.
Since it is "inteface", you do not need to call initialize method as seen in omn.isaac.sensor.IMUSensor.
"""
def __init__(self, sensor_cfg: IMU_T, num_envs: int = 1):
"""
Args:
sensor_cfg (IMU_T): imu sensor configuration.
num_envs (int): number of environments.
"""
super().__init__(sensor_cfg)
self.gravity_vector = self.sensor_cfg["gravity_vector"]
self._gyroscope_bias = torch.zeros(3, 1)
self._gyroscope_noise_density = self.sensor_cfg["gyro_param"]["noise_density"]
self._gyroscope_random_walk = self.sensor_cfg["gyro_param"]["random_walk"]
self._gyroscope_bias_correlation_time = self.sensor_cfg["gyro_param"][
"bias_correlation_time"
]
self._gyroscope_turn_on_bias_sigma = self.sensor_cfg["gyro_param"][
"turn_on_bias_sigma"
]
self._accelerometer_bias = torch.zeros(3, 1)
self._accelerometer_noise_density = self.sensor_cfg["accel_param"][
"noise_density"
]
self._accelerometer_random_walk = self.sensor_cfg["accel_param"]["random_walk"]
self._accelerometer_bias_correlation_time = self.sensor_cfg["accel_param"][
"bias_correlation_time"
]
self._accelerometer_turn_on_bias_sigma = self.sensor_cfg["accel_param"][
"turn_on_bias_sigma"
]
self._prev_linear_velocity = torch.zeros(num_envs, 3).to(torch.float32)
self._sensor_state = ImuState(angular_velocity=torch.zeros(num_envs, 3).to(torch.float32),
linear_acceleration=torch.zeros(num_envs, 3).to(torch.float32))
def update(self, state: State):
"""
gyroscope and accelerometer simulation (https://ieeexplore.ieee.org/document/7487628)
gyroscope = angular_velocity + white noise + random walk.
accelerometer = -1 * (acceleration + white noise + random walk).
NOTE that accelerometer measures inertial acceleration. Thus, the reading is the negative of body acceleration.
"""
device = state.angular_velocity.device
# gyroscope term
tau_g = self._gyroscope_bias_correlation_time
sigma_g_d = 1 / torch.sqrt(torch.tensor(self.dt)) * self._gyroscope_noise_density
sigma_b_g = self._gyroscope_random_walk
sigma_b_g_d = torch.sqrt(-sigma_b_g * sigma_b_g * tau_g / 2.0 * (torch.exp(torch.tensor(-2.0 * self.dt / tau_g)) - 1.0))
phi_g_d = torch.exp(torch.tensor(-1.0/tau_g * self.dt))
angular_velocity = torch.bmm(state.body_transform[:, :3, :3], state.angular_velocity[:, :, None]).squeeze()
for i in range(3):
self._gyroscope_bias[i] = phi_g_d * self._gyroscope_bias[i] + sigma_b_g_d * torch.randn(1)
angular_velocity[:, i] = angular_velocity[:, i] + sigma_g_d * torch.randn(1).to(device) + self._gyroscope_bias[i].to(device)
# accelerometer term
self._prev_linear_velocity = self._prev_linear_velocity.to(device)
tau_a = self._accelerometer_bias_correlation_time
sigma_a_d = 1.0 / torch.sqrt(torch.tensor(self.dt)) * self._accelerometer_noise_density
sigma_b_a = self._accelerometer_random_walk
sigma_b_a_d = torch.sqrt(-sigma_b_a * sigma_b_a * tau_a / 2.0 * (torch.exp(torch.tensor(-2.0 * self.dt / tau_a)) - 1.0))
phi_a_d = torch.exp(torch.tensor(-1.0 / tau_a * self.dt))
linear_acceleration_inertial = (state.linear_velocity - self._prev_linear_velocity) / self.dt + self.gravity_vector.to(device)
self._prev_linear_velocity = state.linear_velocity
linear_acceleration = torch.bmm(state.body_transform[:, :3, :3], linear_acceleration_inertial[:, :, None]).squeeze()
for i in range(3):
self._accelerometer_bias[i] = phi_a_d * self._accelerometer_bias[i] + sigma_b_a_d * torch.randn(1)
linear_acceleration[:, i] = (
linear_acceleration[:, i] + sigma_a_d * torch.randn(1).to(device)
) #+ self._accelerometer_bias[i]
# transform accel/gyro from body frame to sensor optical frame
angular_velocity = torch.bmm(self.sensor_frame_to_optical_frame[None, :3, :3].expand(angular_velocity.shape[0], 3, 3).to(device),
torch.bmm(
self.body_to_sensor_frame[None, :3, :3].expand(angular_velocity.shape[0], 3, 3).to(device), angular_velocity[:, :, None]
)).squeeze()
linear_acceleration = torch.bmm(self.sensor_frame_to_optical_frame[None, :3, :3].expand(linear_acceleration.shape[0], 3, 3).to(device),
torch.bmm(
self.body_to_sensor_frame[None, :3, :3].expand(linear_acceleration.shape[0], 3, 3).to(device), linear_acceleration[:, :, None]
)).squeeze()
self._sensor_state.update(angular_velocity, -1*linear_acceleration)
def reset_idx(self, env_ids: torch.Tensor):
"""
reset sensor state of specified env.
Args:
env_ids (torch.Tensor): environment indices to reset.
"""
env_long = env_ids.long()
self._sensor_state.reset_idx(env_ids=env_long)
self._prev_linear_velocity[env_long] = 0
@property
def state(self):
"""
return sensor state.
"""
return self._sensor_state
if __name__ == "__main__":
## comes from yaml parsed by hydra ##########
BODY_TO_SENSOR_FRAME = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]
SENSOR_FRAME_TO_OPTICAL_FRAME = [[-0, -1, 0, 0],
[0, 0, -1, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]]
GRAVITY_VECTOR = [0, 0, -9.81]
dt = 0.01
ACCEL_PARAM = {"noise_density": 0.004,
"random_walk": 0.006,
"bias_correlation_time": 300.0,
"turn_on_bias_sigma": 0.196
}
GYRO_PARAM = {"noise_density": 0.0003393695767766752,
"random_walk": 3.878509448876288e-05,
"bias_correlation_time": 1.0e3,
"turn_on_bias_sigma": 0.008726646259971648
}
#############################################
imu_t = IMU_T(
body_to_sensor_frame=BODY_TO_SENSOR_FRAME,
sensor_frame_to_optical_frame=SENSOR_FRAME_TO_OPTICAL_FRAME,
gravity_vector=GRAVITY_VECTOR,
dt=dt,
accel_param=Accelometer_T(**ACCEL_PARAM),
gyro_param=Gyroscope_T(**GYRO_PARAM),
)
imu = IMUInterface(imu_t)
while True:
N = 16
position = torch.zeros(N, 3).to(torch.float32)
orientation = torch.zeros(N, 4).to(torch.float32)
orientation[:, 0] = 1.0
linear_velocity = torch.zeros(N, 3).to(torch.float32)
angular_velocity = torch.zeros(N, 3).to(torch.float32)
state = State(position, orientation, linear_velocity, angular_velocity)
imu.update(state)
print(imu.state) | 8,278 | Python | 49.481707 | 167 | 0.57526 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/exteroceptive/camera.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from omniisaacgymenvs.robots.sensors.exteroceptive.camera_interface import camera_interface_factory
from typing import List
from dataclasses import dataclass, field
from omni.isaac.core.utils.stage import get_current_stage
from pxr import Gf
import carb
## Replicator hack
carb_settings = carb.settings.get_settings()
carb_settings.set_bool(
"rtx/raytracing/cached/enabled",
False,
)
carb_settings.set_int(
"rtx/descriptorSets",
8192,
)
@dataclass
class CameraCalibrationParam:
"""
Camera calibration params class.
Args:
focalLength (float): focal length of the camera.
focusDistance (float): focus distance of the camera.
clippingRange (List[float]): clipping range of the camera.
horizontalAperture (float): horizontal aperture of the camera.
verticalAperture (float): vertical aperture of the camera.
"""
focalLength: float = None
focusDistance: float = None
clippingRange: List[float] = None
horizontalAperture: float = None
verticalAperture: float = None
@dataclass
class RLCameraParams:
"""
RLCamera params class.
Args:
prim_path (str): path to the prim that the sensor is attached to.
resolution (List[int]): resolution of the sensor.
is_override (bool): if True, the sensor parameters will be overriden.
params (dict): parameters for the sensor.
"""
prim_path: str
resolution: List[int]
is_override: bool
params: CameraCalibrationParam = field(default_factory=dict)
def __post_init__(self):
assert len(self.resolution) == 2, f"resolution should be a list of 2 ints, got {self.resolution}"
self.params = CameraCalibrationParam(**self.params)
class RLCamera:
"""
RLCamera is a sensor that can be used in RL tasks.
It uses replicator to record synthetic (mostly images) data.
"""
def __init__(self, sensor_cfg:dict, rep:object)->None:
"""
Args:
sensor_cfg (dict): configuration for the sensor with the following key, value
prim_path (str): path to the prim that the sensor is attached to
sensor_param (dict): parameters for the sensor
override_param (bool): if True, the sensor parameters will be overriden
rep (object): omni.replicator.core object
"""
self.sensor_cfg = RLCameraParams(**sensor_cfg)
self.prim_path = self.sensor_cfg.prim_path
self.is_override = self.sensor_cfg.is_override
self.rep = rep
if self.is_override:
assert "params" in sensor_cfg.keys(), "params must be provided if override is True."
self.override_params(get_current_stage(), self.prim_path, self.sensor_cfg.params)
self.render_product = self.rep.create.render_product(
self.prim_path,
resolution=[*self.sensor_cfg.resolution])
self.annotators = {}
self.camera_interfaces = {}
self.enable_rgb()
self.enable_depth()
def override_params(self, stage, prim_path:str, sensor_param:CameraCalibrationParam)->None:
"""
Override the sensor parameters if override=True
Args:
stage (Stage): stage object
prim_path (str): path to the prim that the sensor is attached to
sensor_param (CameraCalibrationParam): parameters for the sensor
"""
camera = stage.DefinePrim(prim_path, 'Camera')
camera.GetAttribute('focalLength').Set(sensor_param.focalLength)
camera.GetAttribute('focusDistance').Set(sensor_param.focusDistance)
camera.GetAttribute("clippingRange").Set(Gf.Vec2f(*sensor_param.clippingRange))
camera.GetAttribute("horizontalAperture").Set(sensor_param.horizontalAperture)
camera.GetAttribute("verticalAperture").Set(sensor_param.verticalAperture)
def enable_rgb(self) -> None:
"""
Enable RGB as a RL observation
"""
rgb_annot = self.rep.AnnotatorRegistry.get_annotator("rgb")
rgb_annot.attach([self.render_product])
self.annotators.update({"rgb":rgb_annot})
self.camera_interfaces.update({"rgb":camera_interface_factory.get("RGBInterface")()})
def enable_depth(self) -> None:
"""
Enable depth as a RL observation
"""
depth_annot = self.rep.AnnotatorRegistry.get_annotator("distance_to_image_plane")
depth_annot.attach([self.render_product])
self.annotators.update({"depth":depth_annot})
self.camera_interfaces.update({"depth":camera_interface_factory.get("DepthInterface")()})
def get_observation(self) -> dict:
"""
Returns a dict of observations
"""
obs_buf = {}
for modality, annotator in self.annotators.items():
camera_interface = self.camera_interfaces[modality]
data_pt = camera_interface(annotator.get_data())
obs_buf.update({modality:data_pt})
return obs_buf
class CameraFactory:
"""
Factory class to create sensors.
"""
def __init__(self):
self.creators = {}
def register(self, name: str, sensor):
"""
Registers a new sensor.
Args:
name (str): name of the sensor.
sensor (object): sensor object.
"""
self.creators[name] = sensor
def get(
self, name: str
) -> object:
"""
Returns a sensor.
Args:
name (str): name of the sensor.
"""
assert name in self.creators.keys(), f"{name} not in {self.creators.keys()}"
return self.creators[name]
camera_factory = CameraFactory()
camera_factory.register("RLCamera", RLCamera) | 6,082 | Python | 34.782353 | 105 | 0.637455 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/exteroceptive/camera_module_generator.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import os
from dataclasses import dataclass, field
from omni.isaac.core.utils.stage import get_current_stage, add_reference_to_stage
from omni.isaac.core.utils.prims import get_prim_at_path
from pxr import Gf
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
@dataclass
class RootPrimParams:
"""
Root prim params class.
Args:
prim_path (str): path to the prim.
translation (List[float]): translation of the prim.
rotation (List[float]): rotation of the prim.
"""
prim_path: str
translation: List[float]
rotation: List[float]
def __post_init__(self):
assert len(self.translation) == 3, f"translation should be a list of 3 floats, got {self.translation}"
assert len(self.rotation) == 3, f"rotation should be a list of 3 floats, got {self.rotation}"
@dataclass
class SensorBaseParams:
"""
Sensor base params class.
Args:
prim_name (str): name of the prim.
usd_path (str): path to the usd file. none if you do not link a usd file.
"""
prim_name: str = None
usd_path: str = None
@dataclass
class CameraCalibrationParam:
"""
Camera calibration params class.
Args:
focalLength (float): focal length of the camera.
focusDistance (float): focus distance of the camera.
clippingRange (List[float]): clipping range of the camera.
horizontalAperture (float): horizontal aperture of the camera.
verticalAperture (float): vertical aperture of the camera.
"""
focalLength: float
focusDistance: float
clippingRange: List[float]
horizontalAperture: float
verticalAperture: float
@dataclass
class CameraParams:
"""
Camera params class.
Args:
prim_path (str): path to the prim.
rotation (List[float]): rotation of the prim.
params (CameraCalibrationParam): camera calibration params.
"""
prim_path: str
rotation: List[float]
params: CameraCalibrationParam = field(default_factory=dict)
def __post_init__(self):
assert len(self.rotation) == 3, f"rotation should be a list of 3 floats, got {self.rotation}"
self.params = CameraCalibrationParam(**self.params)
@dataclass
class CameraModuleParams:
"""
Camera module params class.
Args:
module_name (str): name of the module.
root_prim (RootPrimParams): root prim params.
sensor_base (SensorBaseParams): sensor base params.
links (list): list of links and their transforms.
camera_sensor (CameraParams): camera params.
"""
module_name: str
root_prim: RootPrimParams = field(default_factory=dict)
sensor_base: SensorBaseParams = field(default_factory=dict)
links: list = field(default_factory=list)
camera_sensor: CameraParams = field(default_factory=dict)
def __post_init__(self):
self.root_prim = RootPrimParams(**self.root_prim)
self.sensor_base = SensorBaseParams(**self.sensor_base)
self.camera_sensor = CameraParams(**self.camera_sensor)
class D435_Sensor:
"""
D435 sensor module class.
It handles the creation of sensor links(body) and joints between them.
"""
def __init__(self, cfg:dict):
"""
Args:
cfg (dict): configuration for the sensor
"""
self.cfg = CameraModuleParams(**cfg)
self.root_prim_path = self.cfg.root_prim.prim_path
self.sensor_base = self.cfg.sensor_base
self.links = self.cfg.links
self.stage = get_current_stage()
def _add_root_prim(self) -> None:
"""
Add root prim.
"""
_, prim = createXform(self.stage, self.root_prim_path)
setTranslate(prim, Gf.Vec3d(*self.cfg.root_prim.translation))
setRotateXYZ(prim, Gf.Vec3d(*self.cfg.root_prim.rotation))
def _add_sensor_link(self) -> None:
"""
Add sensor link(body).
If usd file is given, it will be linked to the sensor link.
"""
_, prim = createXform(self.stage, os.path.join(self.root_prim_path, self.sensor_base.prim_name))
setTranslate(prim, Gf.Vec3d((0, 0, 0)))
setRotateXYZ(prim, Gf.Vec3d((0, 0, 0)))
if self.sensor_base.usd_path is not None:
sensor_body_usd = os.path.join(os.getcwd(), self.sensor_base.usd_path)
camera_body_prim = add_reference_to_stage(sensor_body_usd,
os.path.join(self.root_prim_path,
self.sensor_base.prim_name,
"base_body"))
setTranslate(camera_body_prim, Gf.Vec3d((0, 0, 0)))
setRotateXYZ(camera_body_prim, Gf.Vec3d((0, 0, 0)))
def _add_link(self, link_name:str) -> None:
"""
Add link(body).
Args:
link_name (str): name of the link.
"""
createXform(self.stage, os.path.join(self.root_prim_path, link_name))
def _add_transform(self, link_name:str, transform:list) -> None:
"""
Add transform to the link(body) relative to its parent prim.
Args:
link_name (str): name of the link.
transform (list): transform of the link.
"""
prim = get_prim_at_path(os.path.join(self.root_prim_path, link_name))
setTranslate(prim, Gf.Vec3f(*transform[:3]))
setRotateXYZ(prim, Gf.Vec3f(*transform[3:]))
def _add_camera(self) -> None:
"""
Add usd camera to camera optical link.
"""
camera = self.stage.DefinePrim(self.cfg.camera_sensor.prim_path, 'Camera')
setTranslate(camera, Gf.Vec3d((0, 0, 0)))
setRotateXYZ(camera, Gf.Vec3f(*self.cfg.camera_sensor.rotation))
camera.GetAttribute('focalLength').Set(self.cfg.camera_sensor.params.focalLength)
camera.GetAttribute('focusDistance').Set(self.cfg.camera_sensor.params.focusDistance)
camera.GetAttribute("clippingRange").Set(Gf.Vec2f(*self.cfg.camera_sensor.params.clippingRange))
camera.GetAttribute("horizontalAperture").Set(self.cfg.camera_sensor.params.horizontalAperture)
camera.GetAttribute("verticalAperture").Set(self.cfg.camera_sensor.params.verticalAperture)
def _build_prim_structure(self) -> None:
"""
Build the sensor prim structure.
"""
self._add_root_prim()
self._add_sensor_link()
for link in self.links:
self._add_link(link[0])
self._add_transform(link[0], link[1])
def build(self) -> None:
"""
Initialize the sensor prim structure.
"""
self._build_prim_structure()
self._add_camera()
class D455_Sensor(D435_Sensor):
"""
D455 sensor module class.
It is identical to D435 exept its extrinsics.
"""
def __init__(self, cfg:dict):
"""
Args:
cfg (dict): configuration for the sensor
"""
super().__init__(cfg)
class SensorModuleFactory:
"""
Factory class to create tasks.
"""
def __init__(self):
self.creators = {}
def register(self, name: str, sensor):
"""
Registers a new task.
Args:
name (str): name of the task.
sensor (object): task object.
"""
self.creators[name] = sensor
def get(
self, name: str
) -> object:
"""
Returns a task.
Args:
name (str): name of the task.
"""
assert name in self.creators.keys(), f"{name} not in {self.creators.keys()}"
return self.creators[name]
sensor_module_factory = SensorModuleFactory()
sensor_module_factory.register("D435", D435_Sensor)
sensor_module_factory.register("D455", D455_Sensor) | 8,204 | Python | 32.627049 | 110 | 0.607021 |
elharirymatteo/RANS/omniisaacgymenvs/robots/sensors/exteroceptive/camera_interface.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import numpy as np
import torch
class BaseCameraInterface:
"""
Base camera interface class.
"""
def __call__(self, data):
"""
Get data from the sensor in torch tensor.
Args:
data (Any): data from rep.annotator.get_data()
"""
raise NotImplementedError
class RGBInterface(BaseCameraInterface):
"""
RGB camera interface class."""
def __call__(self, data):
"""
Get rgb data from the sensor in torch tensor.
Args:
data (Any): rgb data from rep.annotator.get_data()
"""
rgb_image = np.frombuffer(data, dtype=np.uint8).reshape(*data.shape, -1)
rgb_image = np.squeeze(rgb_image)[:, :, :3].transpose((2, 0, 1))
rgb_image = (rgb_image/255.0).astype(np.float32)
return torch.from_numpy(rgb_image)
class DepthInterface(BaseCameraInterface):
"""
Depth camera interface class.
"""
def __call__(self, data):
"""
Get depth data from the sensor in torch tensor.
Args:
data (Any): depth data from rep.annotator.get_data()
"""
depth_image = np.frombuffer(data, dtype=np.float32).reshape(*data.shape, -1).transpose((2, 0, 1))
return torch.from_numpy(depth_image)
class SemanticSegmentationInterface(BaseCameraInterface):
"""
Semantic segmentation camera interface class.
"""
def __call__(self, data):
"""
Get semantic segmentation data from the sensor in torch tensor.
Args:
data (Any): semantic segmentation data from rep.annotator.get_data()
"""
raise NotImplementedError
class InstanceSegmentationInterface(BaseCameraInterface):
"""
Instance segmentation camera interface class.
"""
def __call__(self, data):
"""
Get instance segmentation data from the sensor in torch tensor.
Args:
data (Any): instance segmentation data from rep.annotator.get_data()
"""
raise NotImplementedError
class ObjectDetectionInterface(BaseCameraInterface):
"""
Object detection camera interface class."""
def __call__(self, data):
"""
Get object detection data from the sensor in torch tensor.
Args:
data (Any): object detection data from rep.annotator.get_data()"""
raise NotImplementedError
class CameraInterfaceFactory:
"""
Factory class to create tasks.
"""
def __init__(self):
"""
Initialize factor attributes.
"""
self.creators = {}
def register(self, name: str, sensor):
"""
Registers a new task.
Args:
name (str): name of the task.
sensor (object): task object.
"""
self.creators[name] = sensor
def get(
self, name: str
) -> object:
"""
Returns a task.
Args:
name (str): name of the task.
"""
assert name in self.creators.keys(), f"{name} not in {self.creators.keys()}"
return self.creators[name]
camera_interface_factory = CameraInterfaceFactory()
camera_interface_factory.register("RGBInterface", RGBInterface)
camera_interface_factory.register("DepthInterface", DepthInterface)
camera_interface_factory.register("SemanticSegmentationInterface", SemanticSegmentationInterface)
camera_interface_factory.register("InstanceSegmentationInterface", InstanceSegmentationInterface)
camera_interface_factory.register("ObjectDetectionInterface", ObjectDetectionInterface) | 3,892 | Python | 30.144 | 105 | 0.622302 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/balance_bot.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
class BalanceBot(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "BalanceBot",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/BalanceBot/balance_bot.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
for j in range(3):
# set leg joint properties
joint_path = f"joints/lower_leg{j}"
set_drive(f"{self.prim_path}/{joint_path}", "angular", "position", 0, 400, 40, 1000)
| 2,996 | Python | 40.054794 | 96 | 0.697597 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/allegro_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics
class AllegroHand(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "allegro_hand",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/AllegroHand/allegro_hand_instanceable.usd"
self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation
self._orientation = (
torch.tensor([0.257551, 0.283045, 0.683330, -0.621782]) if orientation is None else orientation
)
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
def set_allegro_hand_properties(self, stage, allegro_hand_prim):
for link_prim in allegro_hand_prim.GetChildren():
if not (
link_prim == stage.GetPrimAtPath("/allegro/Looks")
or link_prim == stage.GetPrimAtPath("/allegro/root_joint")
):
rb = PhysxSchema.PhysxRigidBodyAPI.Apply(link_prim)
rb.GetDisableGravityAttr().Set(True)
rb.GetRetainAccelerationsAttr().Set(False)
rb.GetEnableGyroscopicForcesAttr().Set(False)
rb.GetAngularDampingAttr().Set(0.01)
rb.GetMaxLinearVelocityAttr().Set(1000)
rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180)
rb.GetMaxDepenetrationVelocityAttr().Set(1000)
rb.GetMaxContactImpulseAttr().Set(1e32)
def set_motor_control_mode(self, stage, allegro_hand_path):
prim = stage.GetPrimAtPath(allegro_hand_path)
self._set_joint_properties(stage, prim)
def _set_joint_properties(self, stage, prim):
if prim.HasAPI(UsdPhysics.DriveAPI):
drive = UsdPhysics.DriveAPI.Apply(prim, "angular")
drive.GetStiffnessAttr().Set(3 * np.pi / 180)
drive.GetDampingAttr().Set(0.1 * np.pi / 180)
drive.GetMaxForceAttr().Set(0.5)
revolute_joint = PhysxSchema.PhysxJointAPI.Get(stage, prim.GetPath())
revolute_joint.GetJointFrictionAttr().Set(0.01)
for child_prim in prim.GetChildren():
self._set_joint_properties(stage, child_prim)
| 4,627 | Python | 43.5 | 107 | 0.673655 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/shadow_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics
class ShadowHand(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "shadow_hand",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/ShadowHand/shadow_hand_instanceable.usd"
self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation
self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
def set_shadow_hand_properties(self, stage, shadow_hand_prim):
for link_prim in shadow_hand_prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(True)
rb.GetRetainAccelerationsAttr().Set(True)
def set_motor_control_mode(self, stage, shadow_hand_path):
joints_config = {
"robot0_WRJ1": {"stiffness": 5, "damping": 0.5, "max_force": 4.785},
"robot0_WRJ0": {"stiffness": 5, "damping": 0.5, "max_force": 2.175},
"robot0_FFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_FFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_FFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_MFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_MFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_MFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_RFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_RFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_RFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_LFJ4": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_THJ4": {"stiffness": 1, "damping": 0.1, "max_force": 2.3722},
"robot0_THJ3": {"stiffness": 1, "damping": 0.1, "max_force": 1.45},
"robot0_THJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.99},
"robot0_THJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.99},
"robot0_THJ0": {"stiffness": 1, "damping": 0.1, "max_force": 0.81},
}
for joint_name, config in joints_config.items():
set_drive(
f"{self.prim_path}/joints/{joint_name}",
"angular",
"position",
0.0,
config["stiffness"] * np.pi / 180,
config["damping"] * np.pi / 180,
config["max_force"],
)
| 5,517 | Python | 46.982608 | 103 | 0.623527 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/AMR_4WheelsSkidSteer.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from omni.isaac.core.robots.robot import Robot
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
from pxr import Gf
import torch
import omni
import carb
import math
import os
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
compute_actions,
)
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
ConfigurationParameters,
)
from omniisaacgymenvs.robots.sensors.exteroceptive.camera_module_generator import (
sensor_module_factory,
)
from omniisaacgymenvs.robots.articulations.utils.Types import (
Sphere,
DirectDriveWheel,
GeometricPrimitive,
PhysicsMaterial,
GeometricPrimitiveFactory,
PassiveWheelFactory,
)
@dataclass
class SkidSteerParameters:
shape: GeometricPrimitive = field(default_factory=dict)
front_left_wheel: DirectDriveWheel = field(default_factory=dict)
front_right_wheel: DirectDriveWheel = field(default_factory=dict)
rear_left_wheel: DirectDriveWheel = field(default_factory=dict)
rear_right_wheel: DirectDriveWheel = field(default_factory=dict)
passive_wheels: list = field(default_factory=list)
mass: float = 5.0
CoM: tuple = (0, 0, 0)
def __post_init__(self):
self.shape = GeometricPrimitiveFactory.get_item(self.shape)
self.front_left_wheel = DirectDriveWheel(**self.front_left_wheel)
self.front_right_wheel = DirectDriveWheel(**self.front_right_wheel)
self.rear_left_wheel = DirectDriveWheel(**self.rear_left_wheel)
self.rear_right_wheel = DirectDriveWheel(**self.rear_right_wheel)
class CreateAMR4WheelsSkidSteer:
"""
Creates a 2 wheeled SkidSteer robot."""
def __init__(self, path: str, cfg: dict) -> None:
self.platform_path = path
self.joints_path = "joints"
self.materials_path = "materials"
self.core_path = None
self.stage = omni.usd.get_context().get_stage()
# Reads the thruster configuration and computes the number of virtual thrusters.
self.settings = SkidSteerParameters(**cfg["system"])
self.camera_cfg = cfg.get("camera", None)
def build(self) -> None:
"""
Builds the platform."""
# Creates articulation root and the Xforms to store materials/joints.
self.platform_path, self.platform_prim = createArticulation(
self.stage, self.platform_path
)
self.joints_path, self.joints_prim = createXform(
self.stage, self.platform_path + "/" + self.joints_path
)
self.materials_path, self.materials_prim = createXform(
self.stage, self.platform_path + "/" + self.materials_path
)
# Creates a set of basic materials
self.createBasicColors()
# Creates the main body element and adds the position & heading markers.
self.createCore()
self.createDrivingWheels()
self.createPassiveWheels()
def createCore(self) -> None:
"""
Creates the core of the AMR.
"""
self.core_path, self.core_prim = self.settings.shape.build(
self.stage, self.platform_path + "/core"
)
applyMass(self.core_prim, self.settings.mass, Gf.Vec3d(0, 0, 0))
if self.camera_cfg is not None:
self.createCamera()
else:
self.settings.shape.add_orientation_marker(
self.stage, self.core_path + "/arrow", self.colors["red"]
)
self.settings.shape.add_positional_marker(
self.stage, self.core_path + "/marker", self.colors["green"]
)
def createDrivingWheels(self) -> None:
"""
Creates the wheels of the AMR.
"""
# Creates the front left wheel
front_left_wheel_path, front_left_wheel_prim = (
self.settings.front_left_wheel.build(
self.stage,
joint_path=self.joints_path + "/front_left_wheel",
wheel_path=self.platform_path + "/front_left_wheel",
body_path=self.core_path,
)
)
# Creates the front right wheel
front_right_wheel_path, front_right_wheel_prim = (
self.settings.front_right_wheel.build(
self.stage,
joint_path=self.joints_path + "/front_right_wheel",
wheel_path=self.platform_path + "/front_right_wheel",
body_path=self.core_path,
)
)
# Creates the rear left wheel
rear_left_wheel_path, rear_left_wheel_prim = (
self.settings.rear_left_wheel.build(
self.stage,
joint_path=self.joints_path + "/rear_left_wheel",
wheel_path=self.platform_path + "/rear_left_wheel",
body_path=self.core_path,
)
)
# Creates the rear right wheel
rear_right_wheel_path, rear_right_wheel_prim = (
self.settings.rear_right_wheel.build(
self.stage,
joint_path=self.joints_path + "/rear_right_wheel",
wheel_path=self.platform_path + "/rear_right_wheel",
body_path=self.core_path,
)
)
def createPassiveWheels(self) -> None:
"""
Creates the wheels of the AMR.
"""
for i, wheel in enumerate(self.settings.passive_wheels):
wheel_path, wheel_prim = wheel.build(
self.stage,
joint_path=self.joints_path + f"/passive_wheel_{i}",
material_path=self.materials_path + "/zero_friction",
path=self.platform_path + f"/passive_wheel_{i}",
body_path=self.core_path,
)
def createBasicColors(self) -> None:
"""
Creates a set of basic colors."""
self.colors = {}
self.colors["red"] = createColor(
self.stage, self.materials_path + "/red", [1, 0, 0]
)
self.colors["green"] = createColor(
self.stage, self.materials_path + "/green", [0, 1, 0]
)
self.colors["blue"] = createColor(
self.stage, self.materials_path + "/blue", [0, 0, 1]
)
self.colors["white"] = createColor(
self.stage, self.materials_path + "/white", [1, 1, 1]
)
self.colors["grey"] = createColor(
self.stage, self.materials_path + "/grey", [0.5, 0.5, 0.5]
)
self.colors["dark_grey"] = createColor(
self.stage, self.materials_path + "/dark_grey", [0.25, 0.25, 0.25]
)
self.colors["black"] = createColor(
self.stage, self.materials_path + "/black", [0, 0, 0]
)
def createCamera(self) -> None:
"""
Creates a camera module prim.
"""
self.camera = sensor_module_factory.get(self.camera_cfg["module_name"])(
self.camera_cfg
)
self.camera.build()
class AMR_4W_SS(Robot):
def __init__(
self,
prim_path: str,
cfg: dict,
name: Optional[str] = "AMR_2W_SS",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
AMR = CreateAMR4WheelsSkidSteer(prim_path, cfg)
AMR.build()
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
scale=scale,
)
| 8,046 | Python | 32.115226 | 88 | 0.589113 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/MFP3D_thrusters.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from omni.isaac.core.robots.robot import Robot
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
from pxr import Gf
import torch
import omni
import carb
import math
import os
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
from omniisaacgymenvs.tasks.MFP.MFP3D_thruster_generator import (
compute_actions,
)
from omniisaacgymenvs.tasks.MFP.MFP3D_thruster_generator import (
ConfigurationParameters,
)
from omniisaacgymenvs.robots.sensors.exteroceptive.camera_module_generator import (
sensor_module_factory,
)
@dataclass
class PlatformParameters:
shape: str = "sphere"
radius: float = 0.31
height: float = 0.5
mass: float = 5.32
CoM: tuple = (0, 0, 0)
refinement: int = 2
usd_asset_path: str = "/None"
enable_collision: bool = False
def __post_init__(self):
assert self.shape in [
"cylinder",
"sphere",
"asset",
], "The shape must be 'cylinder', 'sphere' or 'asset'."
assert self.radius > 0, "The radius must be larger than 0."
assert self.height > 0, "The height must be larger than 0."
assert self.mass > 0, "The mass must be larger than 0."
assert len(self.CoM) == 3, "The length of the CoM coordinates must be 3."
assert self.refinement > 0, "The refinement level must be larger than 0."
assert type(self.enable_collision) == bool, "The enable_collision must be a bool."
self.refinement = int(self.refinement)
class CreatePlatform:
"""
Creates a floating platform with a core body and a set of thrusters."""
def __init__(self, path: str, cfg: dict) -> None:
self.platform_path = path
self.joints_path = "joints"
self.materials_path = "materials"
self.core_path = None
self.stage = omni.usd.get_context().get_stage()
# Reads the thruster configuration and computes the number of virtual thrusters.
self.settings = PlatformParameters(**cfg["core"])
thruster_cfg = ConfigurationParameters(**cfg["configuration"])
self.num_virtual_thrusters = compute_actions(thruster_cfg)
self.camera_cfg = cfg.get("camera", None)
def build(self) -> None:
"""
Builds the platform."""
# Creates articulation root and the Xforms to store materials/joints.
self.platform_path, self.platform_prim = createArticulation(
self.stage, self.platform_path
)
self.joints_path, self.joints_prim = createXform(
self.stage, self.platform_path + "/" + self.joints_path
)
self.materials_path, self.materials_prim = createXform(
self.stage, self.platform_path + "/" + self.materials_path
)
# Creates a set of basic materials
self.createBasicColors()
# Creates the main body element and adds the position & heading markers.
if self.settings.shape == "sphere":
self.core_path = self.createRigidSphere(
self.platform_path + "/core",
"body",
self.settings.radius,
Gf.Vec3d([0, 0, 0]),
0.0001,
)
elif self.settings.shape == "cylinder":
self.core_path = self.createRigidCylinder(
self.platform_path + "/core",
"body",
self.settings.radius,
self.settings.height,
Gf.Vec3d([0, 0, 0]),
0.0001,
)
# Creates the movable CoM and the joints to control it.
self.createMovableCoM(
self.platform_path + "/movable_CoM",
"CoM",
self.settings.radius / 2,
self.settings.CoM,
self.settings.mass,
)
if self.camera_cfg is not None:
self.createCamera()
else:
self.createArrowXform(self.core_path + "/arrow")
self.createPositionMarkerXform(self.core_path + "/marker")
# Adds virtual anchors for the thrusters
for i in range(self.num_virtual_thrusters):
self.createVirtualThruster(
self.platform_path + "/v_thruster_" + str(i),
self.joints_path + "/v_thruster_joint_" + str(i),
self.core_path,
0.0001,
Gf.Vec3d([0, 0, 0]),
)
def createMovableCoM(
self, path: str, name: str, radius: float, CoM: Gf.Vec3d, mass: float
) -> None:
"""
Creates a movable Center of Mass (CoM).
Args:
path (str): The path to the movable CoM.
name (str): The name of the sphere used as CoM.
radius (float): The radius of the sphere used as CoM.
CoM (Gf.Vec3d): The resting position of the center of mass.
mass (float): The mass of the Floating Platform.
Returns:
str: The path to the movable CoM.
"""
# Create Xform
CoM_path, CoM_prim = createXform(self.stage, path)
# Add shapes
cylinder_path = CoM_path + "/" + name
cylinder_path, cylinder_geom = createCylinder(
self.stage, CoM_path + "/" + name, radius, radius, self.settings.refinement
)
cylinder_prim = self.stage.GetPrimAtPath(cylinder_geom.GetPath())
applyRigidBody(cylinder_prim)
# Sets the collider
applyCollider(cylinder_prim)
# Sets the mass and CoM
applyMass(cylinder_prim, mass, Gf.Vec3d(0, 0, 0))
# Add dual prismatic joint
CoM_path, CoM_prim = createXform(
self.stage, os.path.join(self.joints_path, "/CoM_joints")
)
createP3Joint(
self.stage,
os.path.join(self.joints_path, "CoM_joints"),
self.core_path,
cylinder_path,
damping=1e6,
stiffness=1e12,
prefix="com_",
enable_drive=True,
)
return cylinder_path
def createBasicColors(self) -> None:
"""
Creates a set of basic colors."""
self.colors = {}
self.colors["red"] = createColor(
self.stage, self.materials_path + "/red", [1, 0, 0]
)
self.colors["green"] = createColor(
self.stage, self.materials_path + "/green", [0, 1, 0]
)
self.colors["blue"] = createColor(
self.stage, self.materials_path + "/blue", [0, 0, 1]
)
self.colors["white"] = createColor(
self.stage, self.materials_path + "/white", [1, 1, 1]
)
self.colors["grey"] = createColor(
self.stage, self.materials_path + "/grey", [0.5, 0.5, 0.5]
)
self.colors["dark_grey"] = createColor(
self.stage, self.materials_path + "/dark_grey", [0.25, 0.25, 0.25]
)
self.colors["black"] = createColor(
self.stage, self.materials_path + "/black", [0, 0, 0]
)
def createArrowXform(self, path: str) -> None:
"""
Creates an Xform to store the arrow indicating the platform heading."""
self.arrow_path, self.arrow_prim = createXform(self.stage, path)
createArrow(
self.stage,
self.arrow_path,
0.1,
0.5,
[self.settings.radius, 0, 0],
self.settings.refinement,
)
applyMaterial(self.arrow_prim, self.colors["red"])
def createPositionMarkerXform(self, path: str) -> None:
"""
Creates an Xform to store the position marker."""
self.marker_path, self.marker_prim = createXform(self.stage, path)
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_z_plus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([0, 0, self.settings.radius]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["blue"])
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_z_minus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([0, 0, -self.settings.radius]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["blue"])
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_y_plus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([0, self.settings.radius, 0]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["green"])
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_y_minus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([0, -self.settings.radius, 0]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["green"])
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_x_plus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([self.settings.radius, 0, 0]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["red"])
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere_x_minus",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([-self.settings.radius, 0, 0]))
applyMaterial(self.stage.GetPrimAtPath(sphere_path), self.colors["red"])
def createRigidSphere(
self, path: str, name: str, radius: float, CoM: list, mass: float
) -> str:
"""
Creates a rigid sphere. The sphere is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the main body of the platform."""
# Creates an Xform to store the core body
path, prim = createXform(self.stage, path)
# Creates a sphere
sphere_path = path + "/" + name
sphere_path, sphere_geom = createSphere(
self.stage, path + "/" + name, radius, self.settings.refinement
)
sphere_prim = self.stage.GetPrimAtPath(sphere_geom.GetPath())
applyRigidBody(sphere_prim)
# Sets the collider
applyCollider(sphere_prim, self.settings.enable_collision)
# Sets the mass and CoM
applyMass(sphere_prim, mass, CoM)
return sphere_path
def createRigidCylinder(
self, path: str, name: str, radius: float, height: float, CoM: list, mass: float
) -> str:
"""
Creates a rigid cylinder. The cylinder is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the main body of the platform."""
# Creates an Xform to store the core body
path, prim = createXform(self.stage, path)
# Creates a sphere
sphere_path = path + "/" + name
sphere_path, sphere_geom = createCylinder(
self.stage, path + "/" + name, radius, height, self.settings.refinement
)
sphere_prim = self.stage.GetPrimAtPath(sphere_geom.GetPath())
applyRigidBody(sphere_prim)
# Sets the collider
applyCollider(sphere_prim, self.settings.enable_collision)
# Sets the mass and CoM
applyMass(sphere_prim, mass, CoM)
return sphere_path
def createVirtualThruster(
self, path: str, joint_path: str, parent_path: str, thruster_mass, thruster_CoM
) -> str:
"""
Creates a virtual thruster. The thruster is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the thrusters of the platform."""
# Create Xform
thruster_path, thruster_prim = createXform(self.stage, path)
# Add shapes
setTranslate(thruster_prim, Gf.Vec3d([0, 0, 0]))
setOrient(thruster_prim, Gf.Quatd(1, Gf.Vec3d([0, 0, 0])))
# Make rigid
applyRigidBody(thruster_prim)
# Add mass
applyMass(thruster_prim, thruster_mass, thruster_CoM)
# Create joint
createFixedJoint(self.stage, joint_path, parent_path, thruster_path)
return thruster_path
def createCamera(self) -> None:
"""
Creates a camera module prim.
"""
self.camera = sensor_module_factory.get(
self.camera_cfg["module_name"]
)(self.camera_cfg)
self.camera.build()
class ModularFloatingPlatform(Robot):
def __init__(
self,
prim_path: str,
cfg: dict,
name: Optional[str] = "modular_floating_platform",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
fp = CreatePlatform(prim_path, cfg)
fp.build()
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
scale=scale,
)
| 13,720 | Python | 34.918848 | 100 | 0.581268 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/crazyflie.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Crazyflie(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "crazyflie",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Crazyflie/cf2x.usd"
add_reference_to_stage(self._usd_path, prim_path)
scale = torch.tensor([5, 5, 5])
super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
| 2,720 | Python | 40.861538 | 119 | 0.718015 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/cabinet.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Cabinet(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "cabinet",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
self._position = torch.tensor([0.0, 0.0, 0.4]) if translation is None else translation
self._orientation = torch.tensor([0.1, 0.0, 0.0, 0.0]) if orientation is None else orientation
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
| 1,819 | Python | 35.399999 | 111 | 0.660803 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/humanoid.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Humanoid(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Humanoid",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Humanoid/humanoid_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,716 | Python | 38.955882 | 98 | 0.71134 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/MFP2D_thrusters.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from omni.isaac.core.robots.robot import Robot
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
from pxr import Gf
import torch
import omni
import carb
import math
import os
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
compute_actions,
)
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
ConfigurationParameters,
)
from omniisaacgymenvs.robots.sensors.exteroceptive.camera_module_generator import (
sensor_module_factory,
)
@dataclass
class PlatformParameters:
shape: str = "sphere"
radius: float = 0.31
height: float = 0.5
mass: float = 5.32
CoM: tuple = (0, 0, 0)
refinement: int = 2
usd_asset_path: str = "/None"
enable_collision: bool = False
def __post_init__(self):
assert self.shape in [
"cylinder",
"sphere",
"asset",
], "The shape must be 'cylinder', 'sphere' or 'asset'."
assert self.radius > 0, "The radius must be larger than 0."
assert self.height > 0, "The height must be larger than 0."
assert self.mass > 0, "The mass must be larger than 0."
assert len(self.CoM) == 3, "The length of the CoM coordinates must be 3."
assert self.refinement > 0, "The refinement level must be larger than 0."
assert type(self.enable_collision) == bool, "The enable_collision must be a bool."
self.refinement = int(self.refinement)
class CreatePlatform:
"""
Creates a floating platform with a core body and a set of thrusters."""
def __init__(self, path: str, cfg: dict) -> None:
self.platform_path = path
self.joints_path = "joints"
self.materials_path = "materials"
self.core_path = None
self.stage = omni.usd.get_context().get_stage()
# Reads the thruster configuration and computes the number of virtual thrusters.
self.settings = PlatformParameters(**cfg["core"])
thruster_cfg = ConfigurationParameters(**cfg["configuration"])
self.num_virtual_thrusters = compute_actions(thruster_cfg)
self.camera_cfg = cfg.get("camera", None)
def build(self) -> None:
"""
Builds the platform."""
# Creates articulation root and the Xforms to store materials/joints.
self.platform_path, self.platform_prim = createArticulation(
self.stage, self.platform_path
)
self.joints_path, self.joints_prim = createXform(
self.stage, self.platform_path + "/" + self.joints_path
)
self.materials_path, self.materials_prim = createXform(
self.stage, self.platform_path + "/" + self.materials_path
)
# Creates a set of basic materials
self.createBasicColors()
# Creates the main body element and adds the position & heading markers.
if self.settings.shape == "sphere":
self.core_path = self.createRigidSphere(
self.platform_path + "/core",
"body",
self.settings.radius,
Gf.Vec3d(0, 0, 0),
0.0001,
)
elif self.settings.shape == "cylinder":
self.core_path = self.createRigidCylinder(
self.platform_path + "/core",
"body",
self.settings.radius,
self.settings.height,
Gf.Vec3d(0, 0, 0),
0.0001,
)
# Creates a set of joints to constrain the platform on the XY plane (3DoF).
self.createXYPlaneLock()
# Creates the movable CoM and the joints to control it.
self.createMovableCoM(
self.platform_path + "/movable_CoM",
"CoM",
self.settings.radius / 2,
self.settings.CoM,
self.settings.mass,
)
if self.camera_cfg is not None:
self.createCamera()
else:
self.createArrowXform(self.core_path + "/arrow")
self.createPositionMarkerXform(self.core_path + "/marker")
# Adds virtual anchors for the thrusters
for i in range(self.num_virtual_thrusters):
self.createVirtualThruster(
self.platform_path + "/v_thruster_" + str(i),
self.joints_path + "/v_thruster_joint_" + str(i),
self.core_path,
0.0001,
Gf.Vec3d([0, 0, 0]),
)
def createXYPlaneLock(self) -> None:
"""
Creates a set of joints to constrain the platform to the XY plane.
3DoF: translation on X and Y, rotation on Z."""
# Create anchor to world. It's fixed.
anchor_path, anchor_prim = createXform(
self.stage, self.platform_path + "/world_anchor"
)
setTranslate(anchor_prim, Gf.Vec3d(0, 0, 0))
setOrient(anchor_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(anchor_prim)
applyMass(anchor_prim, 0.0000001)
fixed_joint = createFixedJoint(
self.stage, self.joints_path, body_path2=anchor_path
)
# Create the bodies & joints allowing translation
x_tr_path, x_tr_prim = createXform(
self.stage, self.platform_path + "/x_translation_body"
)
y_tr_path, y_tr_prim = createXform(
self.stage, self.platform_path + "/y_translation_body"
)
setTranslate(x_tr_prim, Gf.Vec3d(0, 0, 0))
setOrient(x_tr_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(x_tr_prim)
applyMass(x_tr_prim, 0.0000001)
setTranslate(y_tr_prim, Gf.Vec3d(0, 0, 0))
setOrient(y_tr_prim, Gf.Quatd(1, Gf.Vec3d(0, 0, 0)))
applyRigidBody(y_tr_prim)
applyMass(y_tr_prim, 0.0000001)
tr_joint_x = createPrismaticJoint(
self.stage,
self.joints_path + "/fp_world_joint_x",
body_path1=anchor_path,
body_path2=x_tr_path,
axis="X",
enable_drive=False,
)
tr_joint_y = createPrismaticJoint(
self.stage,
self.joints_path + "/fp_world_joint_y",
body_path1=x_tr_path,
body_path2=y_tr_path,
axis="Y",
enable_drive=False,
)
# Adds the joint allowing for rotation
rv_joint_z = createRevoluteJoint(
self.stage,
self.joints_path + "/fp_world_joint_z",
body_path1=y_tr_path,
body_path2=self.core_path,
axis="Z",
enable_drive=False,
)
def createMovableCoM(
self, path: str, name: str, radius: float, CoM: Gf.Vec3d, mass: float
) -> None:
"""
Creates a movable Center of Mass (CoM).
Args:
path (str): The path to the movable CoM.
name (str): The name of the sphere used as CoM.
radius (float): The radius of the sphere used as CoM.
CoM (Gf.Vec3d): The resting position of the center of mass.
mass (float): The mass of the Floating Platform.
Returns:
str: The path to the movable CoM.
"""
# Create Xform
CoM_path, CoM_prim = createXform(self.stage, path)
# Add shapes
cylinder_path = CoM_path + "/" + name
cylinder_path, cylinder_geom = createCylinder(
self.stage, CoM_path + "/" + name, radius, radius, self.settings.refinement
)
cylinder_prim = self.stage.GetPrimAtPath(cylinder_geom.GetPath())
applyRigidBody(cylinder_prim)
# Sets the collider
applyCollider(cylinder_prim)
# Sets the mass and CoM
applyMass(cylinder_prim, mass, Gf.Vec3d(0, 0, 0))
# Add dual prismatic joint
CoM_path, CoM_prim = createXform(
self.stage, os.path.join(self.joints_path, "/CoM_joints")
)
createP2Joint(
self.stage,
os.path.join(self.joints_path, "CoM_joints"),
self.core_path,
cylinder_path,
damping=1e6,
stiffness=1e12,
prefix="com_",
enable_drive=True,
)
return cylinder_path
def createBasicColors(self) -> None:
"""
Creates a set of basic colors."""
self.colors = {}
self.colors["red"] = createColor(
self.stage, self.materials_path + "/red", [1, 0, 0]
)
self.colors["green"] = createColor(
self.stage, self.materials_path + "/green", [0, 1, 0]
)
self.colors["blue"] = createColor(
self.stage, self.materials_path + "/blue", [0, 0, 1]
)
self.colors["white"] = createColor(
self.stage, self.materials_path + "/white", [1, 1, 1]
)
self.colors["grey"] = createColor(
self.stage, self.materials_path + "/grey", [0.5, 0.5, 0.5]
)
self.colors["dark_grey"] = createColor(
self.stage, self.materials_path + "/dark_grey", [0.25, 0.25, 0.25]
)
self.colors["black"] = createColor(
self.stage, self.materials_path + "/black", [0, 0, 0]
)
def createArrowXform(self, path: str) -> None:
"""
Creates an Xform to store the arrow indicating the platform heading."""
self.arrow_path, self.arrow_prim = createXform(self.stage, path)
createArrow(
self.stage,
self.arrow_path,
0.1,
0.5,
[self.settings.radius, 0, 0],
self.settings.refinement,
)
applyMaterial(self.arrow_prim, self.colors["blue"])
def createPositionMarkerXform(self, path: str) -> None:
"""
Creates an Xform to store the position marker."""
self.marker_path, self.marker_prim = createXform(self.stage, path)
sphere_path, sphere_geom = createSphere(
self.stage,
self.marker_path + "/marker_sphere",
0.05,
self.settings.refinement,
)
setTranslate(sphere_geom, Gf.Vec3d([0, 0, self.settings.radius]))
applyMaterial(self.marker_prim, self.colors["green"])
def createRigidSphere(
self, path: str, name: str, radius: float, CoM: list, mass: float
) -> str:
"""
Creates a rigid sphere. The sphere is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the main body of the platform."""
# Creates an Xform to store the core body
path, prim = createXform(self.stage, path)
# Creates a sphere
sphere_path = path + "/" + name
sphere_path, sphere_geom = createSphere(
self.stage, path + "/" + name, radius, self.settings.refinement
)
sphere_prim = self.stage.GetPrimAtPath(sphere_geom.GetPath())
applyRigidBody(sphere_prim)
# Sets the collider
applyCollider(sphere_prim, self.settings.enable_collision)
# Sets the mass and CoM
applyMass(sphere_prim, mass, CoM)
return sphere_path
def createRigidCylinder(
self, path: str, name: str, radius: float, height: float, CoM: list, mass: float
) -> str:
"""
Creates a rigid cylinder. The cylinder is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the main body of the platform."""
# Creates an Xform to store the core body
path, prim = createXform(self.stage, path)
# Creates a sphere
sphere_path = path + "/" + name
sphere_path, sphere_geom = createCylinder(
self.stage, path + "/" + name, radius, height, self.settings.refinement
)
sphere_prim = self.stage.GetPrimAtPath(sphere_geom.GetPath())
applyRigidBody(sphere_prim)
# Sets the collider
applyCollider(sphere_prim, self.settings.enable_collision)
# Sets the mass and CoM
applyMass(sphere_prim, mass, CoM)
return sphere_path
def createVirtualThruster(
self, path: str, joint_path: str, parent_path: str, thruster_mass, thruster_CoM
) -> str:
"""
Creates a virtual thruster. The thruster is a RigidBody, a Collider, and has a mass and CoM.
It is used to create the thrusters of the platform."""
# Create Xform
thruster_path, thruster_prim = createXform(self.stage, path)
# Add shapes
setTranslate(thruster_prim, Gf.Vec3d([0, 0, 0]))
setOrient(thruster_prim, Gf.Quatd(1, Gf.Vec3d([0, 0, 0])))
# Make rigid
applyRigidBody(thruster_prim)
# Add mass
applyMass(thruster_prim, thruster_mass, thruster_CoM)
# Create joint
createFixedJoint(self.stage, joint_path, parent_path, thruster_path)
return thruster_path
def createCamera(self) -> None:
"""
Creates a camera module prim.
"""
self.camera = sensor_module_factory.get(
self.camera_cfg["module_name"]
)(self.camera_cfg)
self.camera.build()
class ModularFloatingPlatform(Robot):
def __init__(
self,
prim_path: str,
cfg: dict,
name: Optional[str] = "modular_floating_platform",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
fp = CreatePlatform(prim_path, cfg)
fp.build()
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
scale=scale,
)
| 14,184 | Python | 34.374065 | 100 | 0.576495 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/franka.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import math
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import PhysxSchema
class Franka(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "franka",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation
self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Franka/franka_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
dof_paths = [
"panda_link0/panda_joint1",
"panda_link1/panda_joint2",
"panda_link2/panda_joint3",
"panda_link3/panda_joint4",
"panda_link4/panda_joint5",
"panda_link5/panda_joint6",
"panda_link6/panda_joint7",
"panda_hand/panda_finger_joint1",
"panda_hand/panda_finger_joint2",
]
drive_type = ["angular"] * 7 + ["linear"] * 2
default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02]
stiffness = [400 * np.pi / 180] * 7 + [10000] * 2
damping = [80 * np.pi / 180] * 7 + [100] * 2
max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200]
max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2]
for i, dof in enumerate(dof_paths):
set_drive(
prim_path=f"{self.prim_path}/{dof}",
drive_type=drive_type[i],
target_type="position",
target_value=default_dof_pos[i],
stiffness=stiffness[i],
damping=damping[i],
max_force=max_force[i],
)
PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set(
max_velocity[i]
)
def set_franka_properties(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(True)
| 3,653 | Python | 37.0625 | 116 | 0.599781 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/ant.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Ant(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Ant",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Ant/ant_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,696 | Python | 38.661764 | 88 | 0.709199 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/cartpole.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Cartpole(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Cartpole",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Cartpole/cartpole.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,703 | Python | 38.764705 | 85 | 0.710322 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/factory_franka.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import math
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import PhysxSchema
class FactoryFranka(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "franka",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation
self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/FactoryFranka/factory_franka.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
dof_paths = [
"panda_link0/panda_joint1",
"panda_link1/panda_joint2",
"panda_link2/panda_joint3",
"panda_link3/panda_joint4",
"panda_link4/panda_joint5",
"panda_link5/panda_joint6",
"panda_link6/panda_joint7",
"panda_hand/panda_finger_joint1",
"panda_hand/panda_finger_joint2",
]
drive_type = ["angular"] * 7 + ["linear"] * 2
default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02]
stiffness = [40 * np.pi / 180] * 7 + [500] * 2
damping = [80 * np.pi / 180] * 7 + [20] * 2
max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200]
max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2]
for i, dof in enumerate(dof_paths):
set_drive(
prim_path=f"{self.prim_path}/{dof}",
drive_type=drive_type[i],
target_type="position",
target_value=default_dof_pos[i],
stiffness=stiffness[i],
damping=damping[i],
max_force=max_force[i],
)
PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set(
max_velocity[i]
)
| 3,356 | Python | 36.719101 | 116 | 0.596544 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/AMR_2WheelsSkidSteer.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from omni.isaac.core.robots.robot import Robot
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
from pxr import Gf, PhysxSchema
import torch
import omni
import carb
import math
import os
from omniisaacgymenvs.robots.articulations.utils.MFP_utils import *
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
compute_actions,
)
from omniisaacgymenvs.tasks.MFP.MFP2D_thruster_generator import (
ConfigurationParameters,
)
from omniisaacgymenvs.robots.sensors.exteroceptive.camera_module_generator import (
sensor_module_factory,
)
from omniisaacgymenvs.robots.articulations.utils.Types import (
Sphere,
DirectDriveWheel,
GeometricPrimitive,
PhysicsMaterial,
GeometricPrimitiveFactory,
PassiveWheelFactory,
)
@dataclass
class SkidSteerParameters:
shape: GeometricPrimitive = field(default_factory=dict)
left_wheel: DirectDriveWheel = field(default_factory=dict)
right_wheel: DirectDriveWheel = field(default_factory=dict)
passive_wheels: list = field(default_factory=list)
mass: float = 5.0
CoM: tuple = (0, 0, 0)
def __post_init__(self):
self.shape = GeometricPrimitiveFactory.get_item(self.shape)
self.left_wheel = DirectDriveWheel(**self.left_wheel)
self.right_wheel = DirectDriveWheel(**self.right_wheel)
self.passive_wheels = [
PassiveWheelFactory.get_item(wheel) for wheel in self.passive_wheels
]
class CreateAMR2WheelsSkidSteer:
"""
Creates a 2 wheeled SkidSteer robot."""
def __init__(self, path: str, cfg: dict) -> None:
self.platform_path = path
self.joints_path = "joints"
self.materials_path = "materials"
self.core_path = None
self.stage = omni.usd.get_context().get_stage()
# Reads the thruster configuration and computes the number of virtual thrusters.
self.settings = SkidSteerParameters(**cfg["system"])
self.camera_cfg = cfg.get("camera", None)
def build(self) -> None:
"""
Builds the platform."""
# Creates articulation root and the Xforms to store materials/joints.
self.platform_path, self.platform_prim = createArticulation(
self.stage, self.platform_path
)
self.joints_path, self.joints_prim = createXform(
self.stage, self.platform_path + "/" + self.joints_path
)
self.materials_path, self.materials_prim = createXform(
self.stage, self.platform_path + "/" + self.materials_path
)
# Creates a set of basic materials
self.createBasicColors()
# Creates the main body element and adds the position & heading markers.
self.createCore()
self.createDrivingWheels()
self.createPassiveWheels()
def createCore(self) -> None:
"""
Creates the core of the AMR.
"""
self.core_path, self.core_prim = self.settings.shape.build(
self.stage, self.platform_path + "/core"
)
applyMass(self.core_prim, self.settings.mass, Gf.Vec3d(0, 0, 0))
if self.camera_cfg is not None:
self.createCamera()
else:
self.settings.shape.add_orientation_marker(
self.stage, self.core_path + "/arrow", self.colors["red"]
)
self.settings.shape.add_positional_marker(
self.stage, self.core_path + "/marker", self.colors["green"]
)
def createDrivingWheels(self) -> None:
"""
Creates the wheels of the AMR.
"""
# Creates the left wheel
left_wheel_path, left_wheel_prim = self.settings.left_wheel.build(
self.stage,
joint_path=self.joints_path + "/left_wheel",
wheel_path=self.platform_path + "/left_wheel",
body_path=self.core_path,
)
# Creates the right wheel
right_wheel_path, right_wheel_prim = self.settings.right_wheel.build(
self.stage,
joint_path=self.joints_path + "/right_wheel",
wheel_path=self.platform_path + "/right_wheel",
body_path=self.core_path,
)
def createPassiveWheels(self) -> None:
"""
Creates the wheels of the AMR.
"""
for i, wheel in enumerate(self.settings.passive_wheels):
wheel_path, wheel_prim = wheel.build(
self.stage,
joint_path=self.joints_path + f"/passive_wheel_{i}",
material_path=self.materials_path + "/zero_friction",
path=self.platform_path + f"/passive_wheel_{i}",
body_path=self.core_path,
)
def createBasicColors(self) -> None:
"""
Creates a set of basic colors."""
self.colors = {}
self.colors["red"] = createColor(
self.stage, self.materials_path + "/red", [1, 0, 0]
)
self.colors["green"] = createColor(
self.stage, self.materials_path + "/green", [0, 1, 0]
)
self.colors["blue"] = createColor(
self.stage, self.materials_path + "/blue", [0, 0, 1]
)
self.colors["white"] = createColor(
self.stage, self.materials_path + "/white", [1, 1, 1]
)
self.colors["grey"] = createColor(
self.stage, self.materials_path + "/grey", [0.5, 0.5, 0.5]
)
self.colors["dark_grey"] = createColor(
self.stage, self.materials_path + "/dark_grey", [0.25, 0.25, 0.25]
)
self.colors["black"] = createColor(
self.stage, self.materials_path + "/black", [0, 0, 0]
)
def createCamera(self) -> None:
"""
Creates a camera module prim.
"""
self.camera = sensor_module_factory.get(self.camera_cfg["module_name"])(
self.camera_cfg
)
self.camera.build()
class AMR_2W_SS(Robot):
def __init__(
self,
prim_path: str,
cfg: dict,
name: Optional[str] = "AMR_2W_SS",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
AMR = CreateAMR2WheelsSkidSteer(prim_path, cfg)
AMR.build()
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
scale=scale,
)
stage = omni.usd.get_context().get_stage()
art = PhysxSchema.PhysxArticulationAPI.Apply(stage.GetPrimAtPath(prim_path))
art.CreateEnabledSelfCollisionsAttr().Set(False)
| 7,148 | Python | 31.348416 | 88 | 0.598769 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/quadcopter.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Quadcopter(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Quadcopter",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Quadcopter/quadcopter.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
position=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,719 | Python | 39.597014 | 89 | 0.706878 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/ingenuity.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Ingenuity(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "ingenuity",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = (
assets_root_path + "/Isaac/Robots/Ingenuity/ingenuity.usd"
)
add_reference_to_stage(self._usd_path, prim_path)
scale = torch.tensor([0.01, 0.01, 0.01])
super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
| 2,802 | Python | 40.83582 | 119 | 0.711991 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/anymal.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from pxr import PhysxSchema
class Anymal(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Anymal",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find nucleus server with /Isaac folder")
self._usd_path = assets_root_path + "/Isaac/Robots/ANYbotics/anymal_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
self._dof_names = [
"LF_HAA",
"LH_HAA",
"RF_HAA",
"RH_HAA",
"LF_HFE",
"LH_HFE",
"RF_HFE",
"RH_HFE",
"LF_KFE",
"LH_KFE",
"RF_KFE",
"RH_KFE",
]
@property
def dof_names(self):
return self._dof_names
def set_anymal_properties(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(False)
rb.GetRetainAccelerationsAttr().Set(False)
rb.GetLinearDampingAttr().Set(0.0)
rb.GetMaxLinearVelocityAttr().Set(1000.0)
rb.GetAngularDampingAttr().Set(0.0)
rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180)
def prepare_contacts(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
if "_HIP" not in str(link_prim.GetPrimPath()):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.CreateSleepThresholdAttr().Set(0)
cr_api = PhysxSchema.PhysxContactReportAPI.Apply(link_prim)
cr_api.CreateThresholdAttr().Set(0)
| 4,273 | Python | 38.943925 | 97 | 0.648022 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/test/test_AMR_4W_SS.py | if __name__ == "__main__":
from omni.isaac.kit import SimulationApp
cfg = {
"headless": False,
}
simulation_app = SimulationApp(cfg)
from omni.isaac.core import World
import omni
from omniisaacgymenvs.robots.articulations.AMR_4WheelsSkidSteer import (
AMR_4W_SS,
SkidSteerParameters,
)
from pxr import UsdLux
timeline = omni.timeline.get_timeline_interface()
world = World(stage_units_in_meters=1.0)
world.scene.add_default_ground_plane()
light = UsdLux.DistantLight.Define(world.stage, "/DistantLight")
light.CreateIntensityAttr(3000.0)
physics_ctx = world.get_physics_context()
physics_ctx.set_solver_type("PGS")
# Clearpath Robotics' Husky
Husky = {
"shape": {
"name": "Cube",
"width": 0.670,
"depth": 0.990,
"height": 0.260,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 50.0,
"front_left_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [
0.544 / 2,
-0.670 / 2 - 0.125 / 2,
-0.260 / 2 + 0.330 / 2 - 0.130,
],
"orientation": [-90, 0, 0],
},
"front_right_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [
0.544 / 2,
0.670 / 2 + 0.125 / 2,
-0.260 / 2 + 0.330 / 2 - 0.130,
],
"orientation": [-90, 0, 0],
},
"rear_left_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [
-0.544 / 2,
-0.670 / 2 - 0.125 / 2,
-0.260 / 2 + 0.330 / 2 - 0.130,
],
"orientation": [-90, 0, 0],
},
"rear_right_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.330 / 2,
"height": 0.125,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [
-0.544 / 2,
0.670 / 2 + 0.125 / 2,
-0.260 / 2 + 0.330 / 2 - 0.130,
],
"orientation": [-90, 0, 0],
},
}
AMR_4W_SS("/Husky", cfg={"system": Husky}, translation=[0, 0, 0.3])
world.reset()
for i in range(100):
world.step(render=True)
timeline.play()
while simulation_app.is_running():
world.step(render=True)
timeline.stop()
simulation_app.close()
| 5,701 | Python | 29.010526 | 76 | 0.349412 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/test/test_AMR_2W_SS.py | if __name__ == "__main__":
from omni.isaac.kit import SimulationApp
cfg = {
"headless": False,
}
simulation_app = SimulationApp(cfg)
from omni.isaac.core import World
import omni
from omniisaacgymenvs.robots.articulations.AMR_2WheelsSkidSteer import (
AMR_2W_SS,
SkidSteerParameters,
)
from pxr import UsdLux
timeline = omni.timeline.get_timeline_interface()
world = World(stage_units_in_meters=1.0)
world.scene.add_default_ground_plane()
light = UsdLux.DistantLight.Define(world.stage, "/DistantLight")
light.CreateIntensityAttr(3000.0)
physics_ctx = world.get_physics_context()
physics_ctx.set_solver_type("PGS")
# Kobuki's Turtlebot 2
Turtlebot2 = {
"shape": {
"name": "Cylinder",
"radius": 0.354 / 2,
"height": 0.420,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 6.5,
"left_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [0.0, -0.24 / 2, -0.420 / 2 + 0.076 / 2 - 0.015],
"orientation": [-90, 0, 0],
},
"right_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [0.0, 0.24 / 2, -0.420 / 2 + 0.076 / 2 - 0.015],
"orientation": [-90, 0, 0],
},
"passive_wheels": [
{
"name": "ZeroFrictionSphere",
"radius": 0.076 / 2,
"offset": [-0.24 / 2, 0.0, -0.420 / 2 + 0.076 / 2 - 0.015],
},
{
"name": "ZeroFrictionSphere",
"radius": 0.076 / 2,
"offset": [0.24 / 2, 0.0, -0.420 / 2 + 0.076 / 2 - 0.015],
},
],
}
AMR_2W_SS("/Turtlebot2", cfg={"system": Turtlebot2}, translation=[0, 0, 0.3])
# Kobuki's Turtlebot 2
Turtlebot2_caster = {
"shape": {
"name": "Cylinder",
"radius": 0.354 / 2,
"height": 0.420,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 6.5,
"left_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [0.0, -0.24 / 2, -0.420 / 2 + 0.076 / 2 - 0.015],
"orientation": [-90, 0, 0],
},
"right_wheel": {
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"actuator": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": True,
"damping": 1e10,
"stiffness": 0.0,
},
"offset": [0.0, 0.24 / 2, -0.420 / 2 + 0.076 / 2 - 0.015],
"orientation": [-90, 0, 0],
},
"passive_wheels": [
{
"name": "CasterWheel",
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"wheel_joint": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": False,
},
"caster_joint": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": False,
},
"caster_offset": [-0.24 / 2, 0.0, -0.420 / 2 + 0.076 - 0.015],
"wheel_offset": [-0.24 / 2, 0.0, -0.420 / 2 + 0.076 / 2 - 0.015],
"wheel_orientation": [-90, 0, 0],
},
{
"name": "CasterWheel",
"wheel": {
"visual_shape": {
"name": "Cylinder",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": False,
"is_rigid": False,
"refinement": 2,
},
"collider_shape": {
"name": "Capsule",
"radius": 0.076 / 2,
"height": 0.04,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
},
"mass": 0.05,
},
"wheel_joint": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": False,
},
"caster_joint": {
"name": "RevoluteJoint",
"axis": "Z",
"enable_drive": False,
},
"caster_offset": [0.24 / 2, 0.0, -0.420 / 2 + 0.076 - 0.015],
"wheel_offset": [0.24 / 2, 0.0, -0.420 / 2 + 0.076 / 2 - 0.015],
"wheel_orientation": [-90, 0, 0],
},
],
}
AMR_2W_SS(
"/Turtlebot2_Caster",
cfg={"system": Turtlebot2_caster},
translation=[1.0, 0, 0.3],
)
world.reset()
for i in range(100):
world.step(render=True)
timeline.play()
while simulation_app.is_running():
world.step(render=True)
timeline.stop()
simulation_app.close()
| 8,904 | Python | 31.264493 | 81 | 0.336478 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/cabinet_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class CabinetView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "CabinetView",
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._drawers = RigidPrimView(
prim_paths_expr="/World/envs/.*/cabinet/drawer_top", name="drawers_view", reset_xform_properties=False
)
| 586 | Python | 28.349999 | 114 | 0.653584 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/shadow_hand_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class ShadowHandView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "ShadowHandView",
) -> None:
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._fingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/shadow_hand/robot0.*distal",
name="finger_view",
reset_xform_properties=False,
)
@property
def actuated_dof_indices(self):
return self._actuated_dof_indices
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self.actuated_joint_names = [
"robot0_WRJ1",
"robot0_WRJ0",
"robot0_FFJ3",
"robot0_FFJ2",
"robot0_FFJ1",
"robot0_MFJ3",
"robot0_MFJ2",
"robot0_MFJ1",
"robot0_RFJ3",
"robot0_RFJ2",
"robot0_RFJ1",
"robot0_LFJ4",
"robot0_LFJ3",
"robot0_LFJ2",
"robot0_LFJ1",
"robot0_THJ4",
"robot0_THJ3",
"robot0_THJ2",
"robot0_THJ1",
"robot0_THJ0",
]
self._actuated_dof_indices = list()
for joint_name in self.actuated_joint_names:
self._actuated_dof_indices.append(self.get_dof_index(joint_name))
self._actuated_dof_indices.sort()
limit_stiffness = torch.tensor([30.0] * self.num_fixed_tendons, device=self._device)
damping = torch.tensor([0.1] * self.num_fixed_tendons, device=self._device)
self.set_fixed_tendon_properties(dampings=damping, limit_stiffnesses=limit_stiffness)
fingertips = ["robot0_ffdistal", "robot0_mfdistal", "robot0_rfdistal", "robot0_lfdistal", "robot0_thdistal"]
self._sensor_indices = torch.tensor([self._body_indices[j] for j in fingertips], device=self._device, dtype=torch.long)
| 3,681 | Python | 38.591397 | 127 | 0.669383 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/franka_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class FrankaView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "FrankaView",
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._hands = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_link7", name="hands_view", reset_xform_properties=False
)
self._lfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_leftfinger", name="lfingers_view", reset_xform_properties=False
)
self._rfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_rightfinger",
name="rfingers_view",
reset_xform_properties=False,
)
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self._gripper_indices = [self.get_dof_index("panda_finger_joint1"), self.get_dof_index("panda_finger_joint2")]
@property
def gripper_indices(self):
return self._gripper_indices
| 1,241 | Python | 32.567567 | 120 | 0.637389 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/floating_platform_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class FloatingPlatformView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "FloatingPlatformView"
) -> None:
"""[summary]
"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.base = RigidPrimView(prim_paths_expr=f"/World/envs/.*/Floating_platform/base_link/Cylinder",
name="base_view")
self.thrusters = [RigidPrimView(prim_paths_expr=f"/World/envs/.*/Floating_platform/t{i}/thruster_{i}",
name=f"thruster_{i}_view") for i in range(1, 5)]
| 2,381 | Python | 43.943395 | 110 | 0.710206 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/factory_franka_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class FactoryFrankaView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "FactoryFrankaView",
) -> None:
"""Initialize articulation view."""
super().__init__(
prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False
)
self._hands = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_hand",
name="hands_view",
reset_xform_properties=False,
)
self._lfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_leftfinger",
name="lfingers_view",
reset_xform_properties=False,
track_contact_forces=True,
)
self._rfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_rightfinger",
name="rfingers_view",
reset_xform_properties=False,
track_contact_forces=True,
)
self._fingertip_centered = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_fingertip_centered",
name="fingertips_view",
reset_xform_properties=False,
)
def initialize(self, physics_sim_view):
"""Initialize physics simulation view."""
super().initialize(physics_sim_view)
| 1,488 | Python | 31.369565 | 84 | 0.598118 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/anymal_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class AnymalView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "AnymalView",
track_contact_forces=False,
prepare_contact_sensors=False,
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._knees = RigidPrimView(
prim_paths_expr="/World/envs/.*/anymal/.*_THIGH",
name="knees_view",
reset_xform_properties=False,
track_contact_forces=track_contact_forces,
prepare_contact_sensors=prepare_contact_sensors,
)
self._base = RigidPrimView(
prim_paths_expr="/World/envs/.*/anymal/base",
name="base_view",
reset_xform_properties=False,
track_contact_forces=track_contact_forces,
prepare_contact_sensors=prepare_contact_sensors,
)
def get_knee_transforms(self):
return self._knees.get_world_poses()
def is_knee_below_threshold(self, threshold, ground_heights=None):
knee_pos, _ = self._knees.get_world_poses()
knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2]
if ground_heights is not None:
knee_heights -= ground_heights
return (
(knee_heights[:, 0] < threshold)
| (knee_heights[:, 1] < threshold)
| (knee_heights[:, 2] < threshold)
| (knee_heights[:, 3] < threshold)
)
def is_base_below_threshold(self, threshold, ground_heights):
base_pos, _ = self.get_world_poses()
base_heights = base_pos[:, 2]
base_heights -= ground_heights
return base_heights[:] < threshold
| 3,433 | Python | 41.395061 | 98 | 0.678415 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/quadcopter_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class QuadcopterView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "QuadcopterView") -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self.rotors = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Quadcopter/rotor[0-3]", name="rotors_view", reset_xform_properties=False
)
| 2,121 | Python | 47.227272 | 117 | 0.759547 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/allegro_hand_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class AllegroHandView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "AllegroHandView",
) -> None:
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._actuated_dof_indices = list()
@property
def actuated_dof_indices(self):
return self._actuated_dof_indices
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self._actuated_dof_indices = [i for i in range(self.num_dof)]
| 2,275 | Python | 41.148147 | 98 | 0.74989 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/crazyflie_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class CrazyflieView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "CrazyflieView") -> None:
"""[summary]"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.physics_rotors = [
RigidPrimView(prim_paths_expr=f"/World/envs/.*/Crazyflie/m{i}_prop", name=f"m{i}_prop_view")
for i in range(1, 5)
]
| 2,140 | Python | 42.693877 | 104 | 0.737383 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/MFP3D_view.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class ModularFloatingPlatformView(ArticulationView):
def __init__(
self, prim_paths_expr: str, name: Optional[str] = "ModularFloatingPlatformView"
) -> None:
"""[summary]"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.base = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/core/body",
name="base_view",
)
self.CoM = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/movable_CoM/CoM",
name="CoM_view",
)
self.thrusters = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/v_thruster_*",
name="thrusters",
)
def get_CoM_indices(self):
self.CoM_shifter_indices = [
self.get_dof_index("com_x_axis_joint"),
self.get_dof_index("com_y_axis_joint"),
self.get_dof_index("com_z_axis_joint"),
]
def get_plane_lock_indices(self):
self.lock_indices = []
| 1,526 | Python | 30.163265 | 88 | 0.599607 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/ingenuity_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class IngenuityView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "IngenuityView") -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self.physics_rotors = [
RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_physics_{i}",
name=f"physics_rotor_{i}_view",
reset_xform_properties=False,
)
for i in range(2)
]
self.visual_rotors = [
RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_visual_{i}",
name=f"visual_rotor_{i}_view",
reset_xform_properties=False,
)
for i in range(2)
]
| 2,524 | Python | 42.534482 | 98 | 0.70206 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/views/MFP2D_view.py | __author__ = "Antoine Richard, Matteo El Hariry"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class ModularFloatingPlatformView(ArticulationView):
def __init__(
self, prim_paths_expr: str,
name: Optional[str] = "ModularFloatingPlatformView",
track_contact_force:bool = False,
) -> None:
"""[summary]"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.base = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/core/body",
name="base_view",
track_contact_forces=track_contact_force,
)
self.CoM = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/movable_CoM/CoM",
name="CoM_view",
)
self.thrusters = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Modular_floating_platform/v_thruster_*",
name="thrusters",
)
def get_CoM_indices(self):
self.CoM_shifter_indices = [
self.get_dof_index("com_x_axis_joint"),
self.get_dof_index("com_y_axis_joint"),
]
def get_plane_lock_indices(self):
self.lock_indices = [
self.get_dof_index("fp_world_joint_x"),
self.get_dof_index("fp_world_joint_y"),
self.get_dof_index("fp_world_joint_z"),
]
| 1,745 | Python | 31.333333 | 88 | 0.591404 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/utils/Types.py | import omniisaacgymenvs.robots.articulations.utils.MFP_utils as pxr_utils
from pxr import Usd, Gf, UsdShade, UsdPhysics
from scipy.spatial.transform import Rotation
from dataclasses import dataclass, field
from typing import Tuple
class TypeFactoryBuilder:
def __init__(self):
self.creators = {}
def register_instance(self, type):
self.creators[type.__name__] = type
def get_item(self, params):
assert "name" in list(params.keys()), "The name of the type must be provided."
assert params["name"] in self.creators, "Unknown type."
return self.creators[params["name"]](**params)
####################################################################################################
## Define the types of the geometric primitives
####################################################################################################
@dataclass
class GeometricPrimitive:
refinement: int = 2
has_collider: bool = False
is_rigid: bool = False
def __post_init__(self):
assert self.refinement > 0, "The refinement level must be larger than 0."
self.refinement = int(self.refinement)
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
raise NotImplementedError
def add_positional_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
raise NotImplementedError
def add_orientation_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
raise NotImplementedError
@dataclass
class Cylinder(GeometricPrimitive):
name: str = "Cylinder"
radius: float = 0.1
height: float = 0.1
def __post_init__(self):
assert self.radius > 0, "The radius must be larger than 0."
assert self.height > 0, "The height must be larger than 0."
assert self.refinement > 0, "The refinement level must be larger than 0."
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
path, geom = pxr_utils.createCylinder(
stage, path, self.radius, self.height, self.refinement
)
prim = stage.GetPrimAtPath(path)
if self.has_collider:
pxr_utils.applyCollider(prim, enable=True)
if self.is_rigid:
pxr_utils.applyRigidBody(prim)
return path, prim
def add_positional_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
sphere_path, sphere_geom = pxr_utils.createSphere(
stage,
marker_path + "/marker_sphere",
0.05,
self.refinement,
)
pxr_utils.setTranslate(sphere_geom, Gf.Vec3d([0, 0, self.height / 2]))
pxr_utils.applyMaterial(marker_prim, color)
def add_orientation_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
pxr_utils.createArrow(
stage,
path,
0.1,
0.5,
[self.radius, 0, 0],
self.refinement,
)
marker_prim = stage.GetPrimAtPath(path)
pxr_utils.applyMaterial(marker_prim, color)
@dataclass
class Sphere(GeometricPrimitive):
name: str = "Sphere"
radius: float = 0.1
def __post_init__(self):
assert self.radius > 0, "The radius must be larger than 0."
assert self.refinement > 0, "The refinement level must be larger than 0."
self.refinement = int(self.refinement)
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
path, geom = pxr_utils.createSphere(stage, path, self.radius, self.refinement)
prim = stage.GetPrimAtPath(path)
if self.has_collider:
pxr_utils.applyCollider(prim, enable=True)
if self.is_rigid:
pxr_utils.applyRigidBody(prim)
return path, prim
def add_positional_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
sphere_path, sphere_geom = pxr_utils.createSphere(
stage,
marker_path + "/marker_sphere",
0.05,
self.refinement,
)
pxr_utils.setTranslate(sphere_geom, Gf.Vec3d([0, 0, self.radius]))
pxr_utils.applyMaterial(marker_prim, color)
def add_orientation_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
pxr_utils.createArrow(
stage,
marker_path + "/marker_arrow",
0.1,
0.5,
[self.radius, 0, 0],
self.refinement,
)
pxr_utils.applyMaterial(marker_prim, color)
@dataclass
class Capsule(GeometricPrimitive):
name: str = "Capsule"
radius: float = 0.1
height: float = 0.1
def __post_init__(self):
assert self.radius > 0, "The radius must be larger than 0."
assert self.height > 0, "The height must be larger than 0."
self.refinement = int(self.refinement)
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
path, geom = pxr_utils.createCapsule(
stage, path, self.radius, self.height, self.refinement
)
prim = stage.GetPrimAtPath(path)
if self.has_collider:
pxr_utils.applyCollider(prim, enable=True)
if self.is_rigid:
pxr_utils.applyRigidBody(prim)
return path, prim
def add_positional_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
sphere_path, sphere_geom = pxr_utils.createSphere(
stage,
marker_path + "/marker_sphere",
0.05,
self.refinement,
)
pxr_utils.setTranslate(
sphere_geom, Gf.Vec3d([0, 0, self.height / 2 + self.radius])
)
pxr_utils.applyMaterial(marker_prim, color)
def add_orientation_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
pxr_utils.createArrow(
stage,
marker_path + "/marker_arrow",
0.1,
0.5,
[self.radius, 0, 0],
self.refinement,
)
pxr_utils.applyMaterial(marker_prim, color)
@dataclass
class Cube(GeometricPrimitive):
name: str = "Cube"
depth: float = 0.1
width: float = 0.1
height: float = 0.1
def __post_init__(self):
assert self.depth > 0, "The depth must be larger than 0."
assert self.width > 0, "The width must be larger than 0."
assert self.height > 0, "The height must be larger than 0."
assert self.refinement > 0, "The refinement level must be larger than 0."
self.refinement = int(self.refinement)
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
path, prim = pxr_utils.createXform(stage, path)
body_path, body_geom = pxr_utils.createCube(
stage, path + "/body", self.depth, self.width, self.height, self.refinement
)
if self.has_collider:
prim = stage.GetPrimAtPath(body_path)
pxr_utils.applyCollider(prim, enable=True)
if self.is_rigid:
prim = stage.GetPrimAtPath(path)
pxr_utils.applyRigidBody(prim)
return path, prim
def add_positional_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
sphere_path, sphere_geom = pxr_utils.createSphere(
stage,
marker_path + "/marker_sphere",
0.05,
self.refinement,
)
pxr_utils.setTranslate(sphere_geom, Gf.Vec3d([0, 0, self.height / 2]))
pxr_utils.applyMaterial(marker_prim, color)
def add_orientation_marker(
self, stage: Usd.Stage, path: str, color: UsdShade.Material
) -> None:
marker_path, marker_prim = pxr_utils.createXform(stage, path)
pxr_utils.createArrow(
stage,
marker_path + "/marker_arrow",
0.1,
0.5,
[self.depth / 2, 0, 0],
self.refinement,
)
pxr_utils.applyMaterial(marker_prim, color)
GeometricPrimitiveFactory = TypeFactoryBuilder()
GeometricPrimitiveFactory.register_instance(Cylinder)
GeometricPrimitiveFactory.register_instance(Sphere)
GeometricPrimitiveFactory.register_instance(Capsule)
GeometricPrimitiveFactory.register_instance(Cube)
####################################################################################################
## Define the type of physics materials
####################################################################################################
@dataclass
class SimpleColorTexture:
r: float = 0.0
g: float = 0.0
b: float = 0.0
roughness: float = 0.5
def __post_init__(self):
assert 0 <= self.r <= 1, "The red channel must be between 0 and 1."
assert 0 <= self.g <= 1, "The green channel must be between 0 and 1."
assert 0 <= self.b <= 1, "The blue channel must be between 0 and 1."
assert 0 <= self.roughness <= 1, "The roughness must be between 0 and 1."
@dataclass
class PhysicsMaterial:
static_friction: float = 0.5
dynamic_friction: float = 0.5
restitution: float = 0.5
friction_combine_mode: str = "average"
restitution_combine_mode: str = "average"
def __post_init__(self):
combine_modes = ["average", "min", "max", "multiply"]
assert (
0 <= self.static_friction <= 1
), "The static friction must be between 0 and 1."
assert (
0 <= self.dynamic_friction <= 1
), "The dynamic friction must be between 0 and 1."
assert 0 <= self.restitution <= 1, "The restitution must be between 0 and 1."
assert (
self.friction_combine_mode in combine_modes
), "The friction combine mode must be one of 'average', 'min', 'max', or 'multiply'."
assert (
self.restitution_combine_mode in combine_modes
), "The restitution combine mode must be one of 'average', 'min', 'max', or 'multiply'."
def build(self, stage, material_path):
material = pxr_utils.createPhysicsMaterial(
stage,
material_path,
static_friction=self.static_friction,
dynamic_friction=self.dynamic_friction,
restitution=self.restitution,
friction_combine_mode=self.friction_combine_mode,
restitution_combine_mode=self.restitution_combine_mode,
)
return material
####################################################################################################
## Define the type of joint actuators
####################################################################################################
@dataclass
class PrismaticJoint:
name: str = "PrismaticActuator"
axis: str = "X"
lower_limit: float = None
upper_limit: float = None
velocity_limit: float = None
enable_drive: bool = False
force_limit: float = None
damping: float = 1e10
stiffness: float = 0.0
def __post_init__(self):
if (self.lower_limit is not None) and (self.upper_limit is not None):
assert (
self.lower_limit < self.upper_limit
), "The lower limit must be smaller than the upper limit."
if self.velocity_limit is not None:
assert self.velocity_limit > 0, "The velocity limit must be larger than 0."
if self.force_limit is not None:
assert self.force_limit > 0, "The force limit must be larger than 0."
assert self.damping >= 0, "The damping must be larger than 0."
assert self.stiffness >= 0, "The stiffness must be larger than or equal to 0."
def build(
self,
stage: Usd.Stage,
joint_path: str,
body1_path: str,
body2_path: str,
) -> UsdPhysics.PrismaticJoint:
joint = pxr_utils.createPrismaticJoint(
stage,
joint_path,
body1_path,
body2_path,
axis=self.axis,
limit_low=self.lower_limit,
limit_high=self.upper_limit,
enable_drive=self.enable_drive,
damping=self.damping,
stiffness=self.stiffness,
force_limit=self.force_limit,
)
return joint
@dataclass
class RevoluteJoint:
name: str = "RevoluteActuator"
axis: str = "X"
lower_limit: float = None
upper_limit: float = None
velocity_limit: float = None
enable_drive: bool = False
force_limit: float = None
damping: float = 1e10
stiffness: float = 0.0
def __post_init__(self):
if (self.lower_limit is not None) and (self.upper_limit is not None):
assert (
self.lower_limit < self.upper_limit
), "The lower limit must be smaller than the upper limit."
if self.velocity_limit is not None:
assert self.velocity_limit > 0, "The velocity limit must be larger than 0."
if self.force_limit is not None:
assert self.force_limit > 0, "The force limit must be larger than 0."
assert self.damping >= 0, "The damping must be larger than 0."
assert self.stiffness >= 0, "The stiffness must be larger than or equal to 0."
def build(
self,
stage: Usd.Stage,
joint_path: str,
body1_path: str,
body2_path: str,
) -> UsdPhysics.RevoluteJoint:
joint = pxr_utils.createRevoluteJoint(
stage,
joint_path,
body1_path,
body2_path,
axis=self.axis,
limit_low=self.lower_limit,
limit_high=self.upper_limit,
enable_drive=self.enable_drive,
damping=self.damping,
stiffness=self.stiffness,
force_limit=self.force_limit,
)
return joint
JointActuatorFactory = TypeFactoryBuilder()
JointActuatorFactory.register_instance(PrismaticJoint)
JointActuatorFactory.register_instance(RevoluteJoint)
####################################################################################################
## Define different type of dynamics
####################################################################################################
@dataclass
class ZeroOrderDynamics:
name: str = "zero_order"
@dataclass
class FirstOrderDynamics:
name: str = "first_order"
time_constant: float = 0.1
delay: float = 0.0
def __post_init__(self):
assert self.time_constant > 0, "The time constant must be larger than 0."
assert self.delay >= 0, "The delay must be larger than or equal to 0."
@dataclass
class SecondOrderDynamics:
name: str = "second_order"
damping_ratio: float = 0.7
natural_frequency: float = 1.0
delay: float = 0.0
def __post_init__(self):
assert (
0 <= self.damping_ratio <= 1
), "The damping ratio must be between 0 and 1."
assert (
self.natural_frequency > 0
), "The natural frequency must be larger than 0."
assert self.delay >= 0, "The delay must be larger than or equal to 0."
DynamicsFactory = TypeFactoryBuilder()
DynamicsFactory.register_instance(ZeroOrderDynamics)
DynamicsFactory.register_instance(FirstOrderDynamics)
DynamicsFactory.register_instance(SecondOrderDynamics)
####################################################################################################
## Define the type of high level actuators
####################################################################################################
@dataclass
class Wheel:
visual_shape: GeometricPrimitive = field(default_factory=dict)
collider_shape: GeometricPrimitive = field(default_factory=dict)
mass: float = 1.0
# physics_material: PhysicsMaterial = field(default_factory=dict)
# visual_material: SimpleColorTexture = field(default_factory=dict)
def __post_init__(self):
# Force the collision shape to have a collider
self.collider_shape["has_collider"] = True
# Force the visual and collision shapes to be non-rigid
self.collider_shape["is_rigid"] = False
self.visual_shape["is_rigid"] = False
self.visual_shape = GeometricPrimitiveFactory.get_item(self.visual_shape)
self.collider_shape = GeometricPrimitiveFactory.get_item(self.collider_shape)
# self.physics_material = PhysicsMaterial(**self.physics_material)
# self.visual_material = SimpleColorTexture(**self.visual_material)
def build(self, stage: Usd.Stage, path: str = None) -> Tuple[str, Usd.Prim]:
wheel_path, wheel_prim = pxr_utils.createXform(stage, path)
visual_path, visual_prim = self.visual_shape.build(stage, path + "/visual")
collider_path, collider_prim = self.collider_shape.build(
stage, path + "/collision"
)
collider_prim.GetAttribute("visibility").Set("invisible")
pxr_utils.applyRigidBody(wheel_prim)
pxr_utils.applyMass(wheel_prim, self.mass)
# pxr_utils.applyMaterial(visual_prim, self.visual_material)
# pxr_utils.applyMaterial(collision_prim, self.visual_material)
return wheel_path, wheel_prim
@dataclass
class DirectDriveWheel:
wheel: Wheel = field(default_factory=dict)
actuator: RevoluteJoint = field(default_factory=dict)
# dynamics: dict = field(default_factory=dict)
offset: Tuple = (0, 0, 0)
orientation: Tuple = (0, 90, 0)
def __post_init__(self):
self.wheel = Wheel(**self.wheel)
self.actuator = JointActuatorFactory.get_item(self.actuator)
# self.dynamics = DynamicsFactory.get_item(self.dynamics)
def build(
self,
stage: Usd.Stage,
joint_path: str = None,
wheel_path: str = None,
body_path: str = None,
) -> Tuple[str, Usd.Prim]:
# Create the wheel
wheel_path, wheel_prim = self.wheel.build(stage, wheel_path)
pxr_utils.setTranslate(wheel_prim, Gf.Vec3d(*self.offset))
q_xyzw = Rotation.from_euler("xyz", self.orientation, degrees=True).as_quat()
pxr_utils.setOrient(
wheel_prim, Gf.Quatd(q_xyzw[3], Gf.Vec3d([q_xyzw[0], q_xyzw[1], q_xyzw[2]]))
)
# Create the joint
self.actuator.build(stage, joint_path, body_path, wheel_path)
return wheel_path, wheel_prim
@dataclass
class ZeroFrictionSphere:
name: str = "ZeroFrictionSphere"
radius: float = 0.1
mass: float = 1.0
offset: Tuple = (0, 0, 0)
def __post_init__(self):
assert self.radius > 0, "The radius must be larger than 0."
assert self.mass > 0, "The mass must be larger than 0."
self.zero_friction = {
"static_friction": 0.0,
"dynamic_friction": 0.0,
"restitution": 0.8,
"friction_combine_mode": "min",
"restitution_combine_mode": "average",
}
shape = {
"name": "Sphere",
"radius": self.radius,
"has_collider": True,
"is_rigid": True,
"refinement": 2,
}
self.shape = GeometricPrimitiveFactory.get_item(shape)
def build(
self,
stage: Usd.Stage,
joint_path: str = None,
material_path: str = None,
path: str = None,
body_path: str = None,
) -> Tuple[str, Usd.Prim]:
path, prim = self.shape.build(stage, path)
pxr_utils.applyMass(prim, self.mass)
pxr_utils.setTranslate(prim, Gf.Vec3d(*self.offset))
pxr_utils.createFixedJoint(stage, joint_path, body_path, path)
if not stage.GetPrimAtPath(material_path).IsValid():
mat = PhysicsMaterial(**self.zero_friction).build(stage, material_path)
mat = UsdShade.Material.Get(stage, material_path)
else:
mat = UsdShade.Material.Get(stage, material_path)
pxr_utils.applyMaterial(prim, mat, purpose="physics")
return path, prim
@dataclass
class CasterWheel:
name: str = "CasterWheel"
wheel: Wheel = field(default_factory=dict)
wheel_joint: RevoluteJoint = field(default_factory=dict)
caster_joint: RevoluteJoint = field(default_factory=dict)
caster_offset: Tuple = (0, 0, 0)
wheel_offset: Tuple = (0, 0, 0)
wheel_orientation: Tuple = (90, 0, 0)
def __post_init__(self):
self.wheel = Wheel(**self.wheel)
self.caster_joint["name"] = "RevoluteJoint"
self.wheel_joint["name"] = "RevoluteJoint"
self.caster_joint["enable_drive"] = False
self.wheel_joint["enable_drive"] = False
self.caster_joint = JointActuatorFactory.get_item(self.caster_joint)
self.wheel_joint = JointActuatorFactory.get_item(self.wheel_joint)
def build(
self,
stage: Usd.Stage,
joint_path: str = None,
material_path: str = None,
path: str = None,
body_path: str = None,
) -> Tuple[str, Usd.Prim]:
# Create the xform that will hold the caster wheel
caster_wheel_path, caster_wheel_prim = pxr_utils.createXform(stage, path)
# Create the wheel
wheel_path, wheel_prim = self.wheel.build(stage, caster_wheel_path + "/wheel")
pxr_utils.setTranslate(wheel_prim, Gf.Vec3d(*self.wheel_offset))
q_xyzw = Rotation.from_euler(
"xyz", self.wheel_orientation, degrees=True
).as_quat()
pxr_utils.setOrient(
wheel_prim, Gf.Quatd(q_xyzw[3], Gf.Vec3d([q_xyzw[0], q_xyzw[1], q_xyzw[2]]))
)
# Create the caster
caster_path, caster_prim = pxr_utils.createXform(
stage, caster_wheel_path + "/caster"
)
pxr_utils.applyRigidBody(caster_prim)
pxr_utils.applyMass(caster_prim, 0.0005)
pxr_utils.setTranslate(caster_prim, Gf.Vec3d(*self.caster_offset))
# Create the joints
self.caster_joint.build(stage, joint_path + "_caster", body_path, caster_path)
self.wheel_joint.build(stage, joint_path + "_wheel", caster_path, wheel_path)
return wheel_path, wheel_prim
PassiveWheelFactory = TypeFactoryBuilder()
PassiveWheelFactory.register_instance(ZeroFrictionSphere)
PassiveWheelFactory.register_instance(CasterWheel)
| 22,789 | Python | 34.665102 | 100 | 0.586643 |
elharirymatteo/RANS/omniisaacgymenvs/robots/articulations/utils/MFP_utils.py | __author__ = "Antoine Richard, Matteo El Hariry, Junnosuke Kamohara"
__copyright__ = (
"Copyright 2023-24, Space Robotics Lab, SnT, University of Luxembourg, SpaceR"
)
__license__ = "GPL"
__version__ = "2.1.0"
__maintainer__ = "Antoine Richard"
__email__ = "[email protected]"
__status__ = "development"
import omni
from typing import List, Tuple
from pxr import Gf, UsdPhysics, UsdGeom, UsdShade, Sdf, Usd, PhysxSchema
import numpy as np
# ==================================================================================================
# Utils for Xform manipulation
# ==================================================================================================
def setXformOp(prim: Usd.Prim, value, property: UsdGeom.XformOp.Type) -> None:
"""
Sets a transform operatios on a prim.
Args:
prim (Usd.Prim): The prim to set the transform operation.
value: The value of the transform operation.
property (UsdGeom.XformOp.Type): The type of the transform operation.
"""
xform = UsdGeom.Xformable(prim)
op = None
for xformOp in xform.GetOrderedXformOps():
if xformOp.GetOpType() == property:
op = xformOp
if op:
xform_op = op
else:
xform_op = xform.AddXformOp(property, UsdGeom.XformOp.PrecisionDouble, "")
xform_op.Set(value)
def setScale(prim: Usd.Prim, value: Gf.Vec3d) -> None:
"""
Sets the scale of a prim.
Args:
prim (Usd.Prim): The prim to set the scale.
value (Gf.Vec3d): The value of the scale.
"""
setXformOp(prim, value, UsdGeom.XformOp.TypeScale)
def setTranslate(prim: Usd.Prim, value: Gf.Vec3d) -> None:
"""
Sets the translation of a prim.
Args:
prim (Usd.Prim): The prim to set the translation.
value (Gf.Vec3d): The value of the translation.
"""
setXformOp(prim, value, UsdGeom.XformOp.TypeTranslate)
def setRotateXYZ(prim: Usd.Prim, value: Gf.Vec3d) -> None:
"""
Sets the rotation of a prim.
Args:
prim (Usd.Prim): The prim to set the rotation.
value (Gf.Vec3d): The value of the rotation.
"""
setXformOp(prim, value, UsdGeom.XformOp.TypeRotateXYZ)
def setOrient(prim: Usd.Prim, value: Gf.Quatd) -> None:
"""
Sets the rotation of a prim.
Args:
prim (Usd.Prim): The prim to set the rotation.
value (Gf.Quatd): The value of the rotation.
"""
setXformOp(prim, value, UsdGeom.XformOp.TypeOrient)
def setTransform(prim, value: Gf.Matrix4d) -> None:
"""
Sets the transform of a prim.
Args:
prim (Usd.Prim): The prim to set the transform.
value (Gf.Matrix4d): The value of the transform.
"""
setXformOp(prim, value, UsdGeom.XformOp.TypeTransform)
def setXformOps(
prim,
translate: Gf.Vec3d = Gf.Vec3d([0, 0, 0]),
orient: Gf.Quatd = Gf.Quatd(1, Gf.Vec3d([0, 0, 0])),
scale: Gf.Vec3d = Gf.Vec3d([1, 1, 1]),
) -> None:
"""
Sets the transform of a prim.
Args:
prim (Usd.Prim): The prim to set the transform.
translate (Gf.Vec3d): The value of the translation.
orient (Gf.Quatd): The value of the rotation.
scale (Gf.Vec3d): The value of the scale.
"""
setTranslate(prim, translate)
setOrient(prim, orient)
setScale(prim, scale)
def getTransform(prim: Usd.Prim, parent: Usd.Prim) -> Gf.Matrix4d:
"""
Gets the transform of a prim relative to its parent.
Args:
prim (Usd.Prim): The prim to get the transform.
parent (Usd.Prim): The parent of the prim.
"""
return UsdGeom.XformCache(0).ComputeRelativeTransform(prim, parent)[0]
# ==================================================================================================
# Utils for API manipulation
# ==================================================================================================
def applyMaterial(
prim: Usd.Prim,
material: UsdShade.Material,
purpose: str = None,
weaker_than_descendants=False,
) -> UsdShade.MaterialBindingAPI:
"""
Applies a material to a prim.
Args:
prim (Usd.Prim): The prim to apply the material.
material (UsdShade.Material): The material to apply.
purpose (None): The purpose of the material.
weaker_than_descendants (bool): The material is weaker than its descendants.
Returns:
UsdShade.MaterialBindingAPI: The MaterialBindingAPI.
"""
binder = UsdShade.MaterialBindingAPI.Apply(prim)
if purpose is None:
if weaker_than_descendants:
binder.Bind(
material,
bindingStrength=UsdShade.Tokens.weakerThanDescendants,
)
else:
binder.Bind(
material,
bindingStrength=UsdShade.Tokens.strongerThanDescendants,
)
else:
assert purpose in [
"allPurpose",
"all",
"preview",
"physics",
], "Purpose must be 'allPurpose', 'all', 'preview' or 'physics'."
if weaker_than_descendants:
binder.Bind(
material,
materialPurpose=purpose,
bindingStrength=UsdShade.Tokens.weakerThanDescendants,
)
else:
binder.Bind(
material,
materialPurpose=purpose,
bindingStrength=UsdShade.Tokens.strongerThanDescendants,
)
return binder
def applyRigidBody(prim: Usd.Prim) -> UsdPhysics.RigidBodyAPI:
"""
Applies a RigidBodyAPI to a prim.
Args:
prim (Usd.Prim): The prim to apply the RigidBodyAPI.
Returns:
UsdPhysics.RigidBodyAPI: The RigidBodyAPI.
"""
rigid = UsdPhysics.RigidBodyAPI.Apply(prim)
return rigid
def applyCollider(prim: Usd.Prim, enable: bool = False) -> UsdPhysics.CollisionAPI:
"""
Applies a ColliderAPI to a prim.
Args:
prim (Usd.Prim): The prim to apply the ColliderAPI.
enable (bool): Enable or disable the collider.
Returns:
UsdPhysics.CollisionAPI: The ColliderAPI.
"""
collider = UsdPhysics.CollisionAPI.Apply(prim)
collider.CreateCollisionEnabledAttr(enable)
return collider
def applyMass(
prim: Usd.Prim, mass: float, CoM: Gf.Vec3d = Gf.Vec3d([0, 0, 0])
) -> UsdPhysics.MassAPI:
"""
Applies a MassAPI to a prim.
Sets the mass and the center of mass of the prim.
Args:
prim (Usd.Prim): The prim to apply the MassAPI.
mass (float): The mass of the prim.
CoM (Gf.Vec3d): The center of mass of the prim.
Returns:
UsdPhysics.MassAPI: The MassAPI.
"""
massAPI = UsdPhysics.MassAPI.Apply(prim)
massAPI.CreateMassAttr().Set(mass)
massAPI.CreateCenterOfMassAttr().Set(CoM)
return massAPI
def createDrive(
joint: Usd.Prim,
token: str = "transX",
damping: float = 1e3,
stiffness: float = 1e6,
max_force: float = None,
) -> UsdPhysics.DriveAPI:
"""
Creates a DriveAPI on a joint.
List of allowed tokens:
"transX", "transY", "transZ", "linear"
"rotX", "rotY", "rotZ", "angular"
Args:
joint (Usd.Prim): The joint to apply the DriveAPI.
token (str, optional): The type of the drive.
damping (float, optional): The damping of the drive.
stiffness (float, optional): The stiffness of the drive.
max_force (float, optional): The maximum force of the drive.
Returns:
UsdPhysics.DriveAPI: The DriveAPI.
"""
driveAPI = UsdPhysics.DriveAPI.Apply(joint, token)
driveAPI.CreateTypeAttr("force")
driveAPI.CreateDampingAttr(damping)
driveAPI.CreateStiffnessAttr(stiffness)
if max_force is not None:
driveAPI.CreateMaxForceAttr(max_force)
return driveAPI
def createLimit(
joint: Usd.Prim,
token: str = "transX",
low: float = None,
high: float = None,
) -> UsdPhysics.LimitAPI:
"""
Creates a LimitAPI on a joint.
List of allowed tokens:
"transX", "transY", "transZ", "linear"
"rotX", "rotY", "rotZ", "angular"
Args:
joint (Usd.Prim): The joint to apply the LimitAPI.
token (str, optional): The type of the limit.
low (float, optional): The lower limit of the joint.
high (float, optional): The upper limit of the joint.
Returns:
UsdPhysics.LimitAPI: The LimitAPI.
"""
limitAPI = UsdPhysics.LimitAPI.Apply(joint, token)
if low:
limitAPI.CreateLowAttr(low)
if high:
limitAPI.CreateHighAttr(high)
return limitAPI
# ==================================================================================================
# Utils for Geom manipulation
# ==================================================================================================
def createXform(
stage: Usd.Stage,
path: str,
) -> Tuple[str, Usd.Prim]:
"""
Creates an Xform prim.
And sets the default transform operations.
Args:
stage (Usd.Stage): The stage to create the Xform prim.
path (str): The path of the Xform prim.
Returns:
Tuple[str, Usd.Prim]: The path and the prim of the Xform prim.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
prim = stage.DefinePrim(path, "Xform")
setXformOps(prim)
return path, prim
def refineShape(stage: Usd.Stage, path: str, refinement: int) -> None:
"""
Refines the geometry of a shape.
This operation is purely visual, it does not affect the physics simulation.
Args:
stage (Usd.Stage): The stage to refine the shape.
path (str): The path of the shape.
refinement (int): The number of times to refine the shape.
"""
prim = stage.GetPrimAtPath(path)
prim.CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int)
prim.GetAttribute("refinementLevel").Set(refinement)
prim.CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool)
prim.GetAttribute("refinementEnableOverride").Set(True)
def createSphere(
stage: Usd.Stage,
path: str,
radius: float,
refinement: int,
) -> Tuple[str, UsdGeom.Sphere]:
"""
Creates a sphere.
Args:
stage (Usd.Stage): The stage to create the sphere.
path (str): The path of the sphere.
radius (float): The radius of the sphere.
refinement (int): The number of times to refine the sphere.
Returns:
Tuple[str, UsdGeom.Sphere]: The path and the prim of the sphere.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
sphere_geom = UsdGeom.Sphere.Define(stage, path)
sphere_geom.GetRadiusAttr().Set(radius)
setXformOps(sphere_geom)
refineShape(stage, path, refinement)
return path, sphere_geom
def createCylinder(
stage: Usd.Stage,
path: str,
radius: float,
height: float,
refinement: int,
) -> Tuple[str, UsdGeom.Cylinder]:
"""
Creates a cylinder.
Args:
stage (Usd.Stage): The stage to create the cylinder.
path (str): The path of the cylinder.
radius (float): The radius of the cylinder.
height (float): The height of the cylinder.
refinement (int): The number of times to refine the cylinder.
Returns:
Tuple[str, UsdGeom.Cylinder]: The path and the prim of the cylinder.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
cylinder_geom = UsdGeom.Cylinder.Define(stage, path)
cylinder_geom.GetRadiusAttr().Set(radius)
cylinder_geom.GetHeightAttr().Set(height)
setXformOps(cylinder_geom)
refineShape(stage, path, refinement)
return path, cylinder_geom
def createCapsule(
stage: Usd.Stage,
path: str,
radius: float,
height: float,
refinement: int,
) -> Tuple[str, UsdGeom.Capsule]:
"""
Creates a capsule.
Args:
stage (Usd.Stage): The stage to create the capsule.
path (str): The path of the capsule.
radius (float): The radius of the capsule.
height (float): The height of the capsule.
refinement (int): The number of times to refine the capsule.
Returns:
Tuple[str, UsdGeom.Capsule]: The path and the prim of the capsule.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
capsule_geom = UsdGeom.Capsule.Define(stage, path)
capsule_geom.GetRadiusAttr().Set(radius)
capsule_geom.GetHeightAttr().Set(height)
setXformOps(capsule_geom)
refineShape(stage, path, refinement)
return path, capsule_geom
def createCube(
stage: Usd.Stage,
path: str,
depth: float,
width: float,
height: float,
refinement: int,
) -> Tuple[str, UsdGeom.Cube]:
"""
Creates a cube.
Args:
stage (Usd.Stage): The stage to create the cube.
path (str): The path of the cube.
depth (float): The depth of the cube.
width (float): The width of the cube.
height (float): The height of the cube.
refinement (int): The number of times to refine the cube.
Returns:
Tuple[str, UsdGeom.Cube]: The path and the prim of the cube.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
cube_geom = UsdGeom.Cube.Define(stage, path)
cube_geom.GetSizeAttr().Set(1)
setXformOps(cube_geom, scale=Gf.Vec3d([depth, width, height]))
refineShape(stage, path, refinement)
return path, cube_geom
def createCone(
stage: Usd.Stage,
path: str,
radius: float,
height: float,
refinement: int,
) -> Tuple[str, UsdGeom.Cone]:
"""
Creates a cone.
Args:
stage (Usd.Stage): The stage to create the cone.
path (str): The path of the cone.
radius (float): The radius of the cone.
height (float): The height of the cone.
refinement (int): The number of times to refine the cone.
Returns:
Tuple[str, UsdGeom.Cone]: The path and the prim of the cone.
"""
path = omni.usd.get_stage_next_free_path(stage, path, False)
cone_geom = UsdGeom.Cone.Define(stage, path)
cone_geom.GetRadiusAttr().Set(radius)
cone_geom.GetHeightAttr().Set(height)
setXformOps(cone_geom)
refineShape(stage, path, refinement)
return path, cone_geom
def createArrow(
stage: Usd.Stage,
path: int,
radius: float,
length: float,
offset: list,
refinement: int,
) -> None:
"""
Creates an arrow.
Args:
stage (Usd.Stage): The stage to create the arrow.
path (str): The path of the arrow.
radius (float): The radius of the arrow.
length (float): The length of the arrow.
offset (list): The offset of the arrow.
refinement (int): The number of times to refine the arrow.
Returns:
Tuple[str, UsdGeom.Cone]: The path and the prim of the arrow.
"""
length = length / 2
body_path, body_geom = createCylinder(
stage, path + "/arrow_body", radius, length, refinement
)
setTranslate(body_geom, Gf.Vec3d([offset[0] + length * 0.5, 0, offset[2]]))
setOrient(body_geom, Gf.Quatd(0.707, Gf.Vec3d(0, 0.707, 0)))
head_path, head_geom = createCone(
stage, path + "/arrow_head", radius * 1.5, length, refinement
)
setTranslate(head_geom, Gf.Vec3d([offset[0] + length * 1.5, 0, offset[2]]))
setOrient(head_geom, Gf.Quatd(0.707, Gf.Vec3d(0, 0.707, 0)))
def createThrusterShape(
stage: Usd.Stage,
path: str,
radius: float,
height: float,
refinement: int,
) -> None:
"""
Creates a thruster.
Args:
stage (Usd.Stage): The stage to create the thruster.
path (str): The path of the thruster.
radius (float): The radius of the thruster.
height (float): The height of the thruster.
refinement (int): The number of times to refine the thruster.
Returns:
Tuple[str, UsdGeom.Cone]: The path and the prim of the thruster.
"""
height /= 2
# Creates a cylinder
cylinder_path, cylinder_geom = createCylinder(
stage, path + "/cylinder", radius, height, refinement
)
cylinder_prim = stage.GetPrimAtPath(cylinder_geom.GetPath())
applyCollider(cylinder_prim)
setTranslate(cylinder_geom, Gf.Vec3d([0, 0, height * 0.5]))
setScale(cylinder_geom, Gf.Vec3d([1, 1, 1]))
# Create a cone
cone_path, cone_geom = createCone(stage, path + "/cone", radius, height, refinement)
cone_prim = stage.GetPrimAtPath(cone_geom.GetPath())
applyCollider(cone_prim)
setTranslate(cone_geom, Gf.Vec3d([0, 0, height * 1.5]))
setRotateXYZ(cone_geom, Gf.Vec3d([0, 180, 0]))
def createColor(
stage: Usd.Stage,
material_path: str,
color: list,
) -> UsdShade.Material:
"""
Creates a color material.
Args:
stage (Usd.Stage): The stage to create the color material.
material_path (str): The path of the material.
color (list): The color of the material
Returns:
UsdShade.Material: The material.
"""
material_path = omni.usd.get_stage_next_free_path(stage, material_path, False)
material = UsdShade.Material.Define(stage, material_path)
shader = UsdShade.Shader.Define(stage, material_path + "/shader")
shader.CreateIdAttr("UsdPreviewSurface")
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Float3).Set(Gf.Vec3f(color))
material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
return material
def createPhysicsMaterial(
stage: Usd.Stage,
material_path: str,
static_friction: float,
dynamic_friction: float,
restitution: float,
friction_combine_mode: str = "average",
restitution_combine_mode: str = "average",
) -> UsdPhysics.MaterialAPI:
"""
Creates a physics material.
Args:
stage (Usd.Stage): The stage to create the physics material.
material_path (str): The path of the material.
static_friction (float): The static friction of the material.
dynamic_friction (float): The dynamic friction of the material.
restitution (float): The restitution of the material.
friction_combine_mode (str, optional): The way the friction between two surfaces is combined.
restitution_combine_mode (str, optional): The way the friction between two surfaces is combined.
Returns:
UsdPhysics.MaterialAPI: The physics material.
"""
if not friction_combine_mode in ["multiply", "average", "min", "max"]:
raise ValueError("average_friction_mode must be average, multiply, min or max")
if not restitution_combine_mode in ["multiply", "average", "min", "max"]:
raise ValueError(
"average_restitution_mode must be average, multiply, min or max"
)
material_path = omni.usd.get_stage_next_free_path(stage, material_path, False)
visual_material = UsdShade.Material.Define(stage, material_path)
prim = stage.GetPrimAtPath(material_path)
material = UsdPhysics.MaterialAPI.Apply(prim)
material.CreateStaticFrictionAttr().Set(static_friction)
material.CreateDynamicFrictionAttr().Set(dynamic_friction)
material.CreateRestitutionAttr().Set(restitution)
physx_material = PhysxSchema.PhysxMaterialAPI.Apply(prim)
physx_material.CreateFrictionCombineModeAttr().Set(friction_combine_mode)
physx_material.CreateRestitutionCombineModeAttr().Set(restitution_combine_mode)
return material
def createArticulation(
stage: Usd.Stage,
path: str,
) -> Tuple[str, Usd.Prim]:
"""
Creates an ArticulationRootAPI on a prim.
Args:
stage (Usd.Stage): The stage to create the ArticulationRootAPI.
path (str): The path of the ArticulationRootAPI.
Returns:
Tuple[str, Usd.Prim]: The path and the prim of the ArticulationRootAPI.
"""
# Creates the Xform of the platform
path, prim = createXform(stage, path)
setXformOps(prim)
# Creates the Articulation root
root = UsdPhysics.ArticulationRootAPI.Apply(prim)
return path, prim
def createFixedJoint(
stage: Usd.Stage,
path: str,
body_path1: str = None,
body_path2: str = None,
) -> UsdPhysics.FixedJoint:
"""
Creates a fixed joint between two bodies.
Args:
stage (Usd.Stage): The stage to create the fixed joint.
path (str): The path of the fixed joint.
body_path1 (str, optional): The path of the first body.
body_path2 (str, optional): The path of the second body.
Returns:
UsdPhysics.FixedJoint: The fixed joint.
"""
# Create fixed joint
joint = UsdPhysics.FixedJoint.Define(stage, path)
# Set body targets
if body_path1 is not None:
joint.CreateBody0Rel().SetTargets([body_path1])
if body_path2 is not None:
joint.CreateBody1Rel().SetTargets([body_path2])
if (body_path1 is not None) and (body_path2 is not None):
# Get from the simulation the position/orientation of the bodies
body_1_prim = stage.GetPrimAtPath(body_path1)
body_2_prim = stage.GetPrimAtPath(body_path2)
xform_body_1 = UsdGeom.Xformable(body_1_prim)
xform_body_2 = UsdGeom.Xformable(body_2_prim)
transform_body_1 = xform_body_1.ComputeLocalToWorldTransform(0.0)
transform_body_2 = xform_body_2.ComputeLocalToWorldTransform(0.0)
t12 = np.matmul(
np.linalg.inv(transform_body_1).T, np.array(transform_body_2).T
).T
translate_body_12 = Gf.Vec3f([t12[3][0], t12[3][1], t12[3][2]])
Q_body_12 = Gf.Transform(Gf.Matrix4d(t12.tolist())).GetRotation().GetQuat()
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(translate_body_12)
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(Q_body_12))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
else:
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
return joint
def createRevoluteJoint(
stage: Usd.Stage,
path: str,
body_path1: str = None,
body_path2: str = None,
axis: str = "Z",
limit_low: float = None,
limit_high: float = None,
enable_drive: bool = False,
damping: float = 1e3,
stiffness: float = 1e6,
force_limit: float = None,
) -> UsdPhysics.RevoluteJoint:
"""
Creates a revolute joint between two bodies.
Args:
stage (Usd.Stage): The stage to create the revolute joint.
path (str): The path of the revolute joint.
body_path1 (str, optional): The path of the first body.
body_path2 (str, optional): The path of the second body.
axis (str, optional): The axis of rotation.
limit_low (float, optional): The lower limit of the joint.
limit_high (float, optional): The upper limit of the joint.
enable_drive (bool, optional): Enable or disable the drive.
damping (float, optional): The damping of the drive.
stiffness (float, optional): The stiffness of the drive.
force_limit (float, optional): The force limit of the drive.
Returns:
UsdPhysics.RevoluteJoint: The revolute joint.
"""
# Create revolute joint
joint = UsdPhysics.RevoluteJoint.Define(stage, path)
# Set body targets
if not body_path1 is None:
joint.CreateBody0Rel().SetTargets([body_path1])
if not body_path2 is None:
joint.CreateBody1Rel().SetTargets([body_path2])
if (body_path1 is not None) and (body_path2 is not None):
# Get from the simulation the position/orientation of the bodies
body_1_prim = stage.GetPrimAtPath(body_path1)
body_2_prim = stage.GetPrimAtPath(body_path2)
xform_body_1 = UsdGeom.Xformable(body_1_prim)
xform_body_2 = UsdGeom.Xformable(body_2_prim)
transform_body_1 = xform_body_1.ComputeLocalToWorldTransform(0.0)
transform_body_2 = xform_body_2.ComputeLocalToWorldTransform(0.0)
t12 = np.matmul(
np.linalg.inv(transform_body_1).T, np.array(transform_body_2).T
).T
translate_body_12 = Gf.Vec3f([t12[3][0], t12[3][1], t12[3][2]])
Q_body_12 = Gf.Transform(Gf.Matrix4d(t12.tolist())).GetRotation().GetQuat()
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(translate_body_12)
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(Q_body_12))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
else:
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
if axis in ["X", "Y", "Z"]:
joint.CreateAxisAttr(axis)
else:
raise ValueError("Axis must be X, Y or Z")
if limit_low is not None:
joint.CreateLowerLimitAttr(limit_low)
if limit_high is not None:
joint.CreateUpperLimitAttr(limit_high)
if enable_drive:
joint_prim = stage.GetPrimAtPath(joint.GetPath())
createDrive(
joint_prim,
token="angular",
damping=damping,
stiffness=stiffness,
max_force=force_limit,
)
return joint
def createPrismaticJoint(
stage: Usd.Stage,
path: str,
body_path1: str = None,
body_path2: str = None,
axis: str = "Z",
limit_low: float = None,
limit_high: float = None,
enable_drive: bool = False,
damping: float = 1e3,
stiffness: float = 1e6,
force_limit: float = None,
) -> UsdPhysics.PrismaticJoint:
"""
Creates a prismatic joint between two bodies.
Args:
stage (Usd.Stage): The stage to create the revolute joint.
path (str): The path of the revolute joint.
body_path1 (str, optional): The path of the first body.
body_path2 (str, optional): The path of the second body.
axis (str, optional): The axis of rotation.
limit_low (float, optional): The lower limit of the joint.
limit_high (float, optional): The upper limit of the joint.
enable_drive (bool, optional): Enable or disable the drive.
damping (float, optional): The damping of the drive.
stiffness (float, optional): The stiffness of the drive.
force_limit (float, optional): The force limit of the drive.
Returns:
UsdPhysics.PrismaticJoint: The prismatic joint.
"""
# Create revolute joint
joint = UsdPhysics.PrismaticJoint.Define(stage, path)
# Set body targets
if body_path1 is not None:
joint.CreateBody0Rel().SetTargets([body_path1])
if body_path2 is not None:
joint.CreateBody1Rel().SetTargets([body_path2])
if (body_path1 is not None) and (body_path2 is not None):
# Get from the simulation the position/orientation of the bodies
body_1_prim = stage.GetPrimAtPath(body_path1)
body_2_prim = stage.GetPrimAtPath(body_path2)
xform_body_1 = UsdGeom.Xformable(body_1_prim)
xform_body_2 = UsdGeom.Xformable(body_2_prim)
transform_body_1 = xform_body_1.ComputeLocalToWorldTransform(0.0)
transform_body_2 = xform_body_2.ComputeLocalToWorldTransform(0.0)
t12 = np.matmul(
np.linalg.inv(transform_body_1).T, np.array(transform_body_2).T
).T
translate_body_12 = Gf.Vec3f([t12[3][0], t12[3][1], t12[3][2]])
Q_body_12 = Gf.Transform(Gf.Matrix4d(t12.tolist())).GetRotation().GetQuat()
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(translate_body_12)
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(Q_body_12))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
joint.CreateAxisAttr(axis)
else:
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
joint.CreateAxisAttr(axis)
if axis in ["X", "Y", "Z"]:
joint.CreateAxisAttr(axis)
else:
raise ValueError("Axis must be X, Y or Z")
if limit_low is not None:
joint.CreateLowerLimitAttr(limit_low)
if limit_high is not None:
joint.CreateUpperLimitAttr(limit_high)
if enable_drive:
joint_prim = stage.GetPrimAtPath(joint.GetPath())
createDrive(
joint_prim,
token="linear",
damping=damping,
stiffness=stiffness,
max_force=force_limit,
)
return joint
def createP3Joint(
stage: Usd.Stage,
path: str,
body_path1: str,
body_path2: str,
damping: float = 1e3,
stiffness: float = 1e6,
articulation_root: str = None,
prefix: str = "",
enable_drive: bool = False,
) -> Tuple[
UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint
]:
"""
Creates 3 Prismatic joints between two bodies. One for each axis (X,Y,Z).
To create this joint, it needs to add two dummy bodies, to do this it
needs to create them at the same position as the 1st body, and then
apply a RigidBodyAPI and a MassAPI to them. The addition of these bodies is
automated, and can fail to recover the position of the 1st body correctly.
Args:
stage (Usd.Stage): The stage to create the prismatic joint.
path (str): The path of the prismatic joint.
body_path1 (str): The path of the first body.
body_path2 (str): The path of the second body.
damping (float, optional): The damping of the drive.
stiffness (float, optional): The stiffness of the drive.
articulation_root (str, optional): The path of the articulation root.
enable_drive (bool, optional): Enable or disable the drive.
Returns:
Tuple[UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint]: The prismatic joints.
"""
# Get the position/orientation of the two bodies
body_1_prim = stage.GetPrimAtPath(body_path1)
body_2_prim = stage.GetPrimAtPath(body_path2)
if articulation_root is not None:
root_prim = stage.GetPrimAtPath(articulation_root)
transform_body_1 = getTransform(body_1_prim, root_prim)
transform_body_2 = getTransform(body_2_prim, root_prim)
else:
xform_body_1 = UsdGeom.Xformable(body_1_prim)
xform_body_2 = UsdGeom.Xformable(body_2_prim)
transform_body_1 = xform_body_1.ComputeLocalToWorldTransform(0.0)
transform_body_2 = xform_body_2.ComputeLocalToWorldTransform(0.0)
translate_body_1 = Gf.Vec3f(
[transform_body_1[3][0], transform_body_1[3][1], transform_body_1[3][2]]
)
Q_body_1d = Gf.Transform(transform_body_1).GetRotation().GetQuat()
# Generates dummy bodies for the joints at the position of the 1st body
xaxis_body_path, xaxis_body_prim = createXform(stage, path + "/x_axis_body")
yaxis_body_path, yaxis_body_prim = createXform(stage, path + "/y_axis_body")
setTranslate(xaxis_body_prim, translate_body_1)
setTranslate(yaxis_body_prim, translate_body_1)
setOrient(xaxis_body_prim, Q_body_1d)
setOrient(yaxis_body_prim, Q_body_1d)
applyRigidBody(xaxis_body_prim)
applyRigidBody(yaxis_body_prim)
applyMass(xaxis_body_prim, 0.0000001)
applyMass(yaxis_body_prim, 0.0000001)
# Create the 3 prismatic joints
xaxis_joint = createPrismaticJoint(
stage, path + "/" + prefix + "x_axis_joint", body_path1, xaxis_body_path, "X"
)
yaxis_joint = createPrismaticJoint(
stage,
path + "/" + prefix + "y_axis_joint",
xaxis_body_path,
yaxis_body_path,
"Y",
)
zaxis_joint = createPrismaticJoint(
stage, path + "/" + prefix + "z_axis_joint", yaxis_body_path, body_path2, "Z"
)
# Get the delta transform between the 1st and 2nd body
t12 = np.matmul(np.linalg.inv(transform_body_1), transform_body_2)
translate_body_12 = Gf.Vec3f([t12[3][0], t12[3][1], t12[3][2]])
Q_body_12 = Gf.Transform(Gf.Matrix4d(t12.tolist())).GetRotation().GetQuat()
# Set the transform between the bodies inside the joints
xaxis_joint.CreateLocalPos0Attr().Set(Gf.Vec3f([0, 0, 0]))
yaxis_joint.CreateLocalPos0Attr().Set(Gf.Vec3f([0, 0, 0]))
zaxis_joint.CreateLocalPos0Attr().Set(translate_body_12)
xaxis_joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
yaxis_joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
zaxis_joint.CreateLocalRot0Attr().Set(Gf.Quatf(Q_body_12))
xaxis_joint.CreateLocalPos1Attr().Set(Gf.Vec3f([0, 0, 0]))
yaxis_joint.CreateLocalPos1Attr().Set(Gf.Vec3f([0, 0, 0]))
zaxis_joint.CreateLocalPos1Attr().Set(Gf.Vec3f([0, 0, 0]))
xaxis_joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
yaxis_joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
zaxis_joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
# Add drives to the joints
if enable_drive:
xaxis_drive = createDrive(
stage.GetPrimAtPath(path + "/" + prefix + "x_axis_joint"),
token="linear",
damping=damping,
stiffness=stiffness,
)
yaxis_drive = createDrive(
stage.GetPrimAtPath(path + "/" + prefix + "y_axis_joint"),
token="linear",
damping=damping,
stiffness=stiffness,
)
zaxis_drive = createDrive(
stage.GetPrimAtPath(path + "/" + prefix + "z_axis_joint"),
token="linear",
damping=damping,
stiffness=stiffness,
)
return (xaxis_joint, yaxis_joint, zaxis_joint)
def createP2Joint(
stage: Usd.Stage,
path: str,
body_path1: str,
body_path2: str,
damping: float = 1e3,
stiffness: float = 1e6,
articulation_root: str = None,
prefix: str = "",
enable_drive: bool = False,
) -> Tuple[UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint]:
"""
Creates 2 Prismatic joints between two bodies. One for each axis (X,Y).
To create this joint, it needs to add one dummy body, to do this it
needs to create it at the same position as the 1st body, and then
apply a RigidBodyAPI and a MassAPI to it. The addition of these bodies is
automated, and can fail to recover the position of the 1st body correctly.
Args:
stage (Usd.Stage): The stage to create the prismatic joint.
path (str): The path of the prismatic joint.
body_path1 (str): The path of the first body.
body_path2 (str): The path of the second body.
damping (float, optional): The damping of the drive.
stiffness (float, optional): The stiffness of the drive.
articulation_root (str, optional): The path of the articulation root.
enable_drive (bool, optional): Enable or disable the drive.
Returns:
Tuple[UsdPhysics.PrismaticJoint, UsdPhysics.PrismaticJoint]: The prismatic joints.
"""
# Get the position/orientation of the two bodies
body_1_prim = stage.GetPrimAtPath(body_path1)
body_2_prim = stage.GetPrimAtPath(body_path2)
if articulation_root is not None:
root_prim = stage.GetPrimAtPath(articulation_root)
transform_body_1 = getTransform(body_1_prim, root_prim)
transform_body_2 = getTransform(body_2_prim, root_prim)
else:
xform_body_1 = UsdGeom.Xformable(body_1_prim)
xform_body_2 = UsdGeom.Xformable(body_2_prim)
transform_body_1 = xform_body_1.ComputeLocalToWorldTransform(0.0)
transform_body_2 = xform_body_2.ComputeLocalToWorldTransform(0.0)
translate_body_1 = Gf.Vec3f(
[transform_body_1[3][0], transform_body_1[3][1], transform_body_1[3][2]]
)
Q_body_1d = Gf.Transform(transform_body_1).GetRotation().GetQuat()
# Generates dummy body for the joints at the position of the 1st body
xaxis_body_path, xaxis_body_prim = createXform(stage, path + "/x_axis_body")
setTranslate(xaxis_body_prim, translate_body_1)
setOrient(xaxis_body_prim, Q_body_1d)
applyRigidBody(xaxis_body_prim)
applyMass(xaxis_body_prim, 0.0000001)
# Create the 3 prismatic joints
xaxis_joint = createPrismaticJoint(
stage, path + "/" + prefix + "x_axis_joint", body_path1, xaxis_body_path, "X"
)
yaxis_joint = createPrismaticJoint(
stage, path + "/" + prefix + "y_axis_joint", xaxis_body_path, body_path2, "Y"
)
# Get the delta transform between the 1st and 2nd body
t12 = np.matmul(np.linalg.inv(transform_body_1), transform_body_2)
translate_body_12 = Gf.Vec3f([t12[3][0], t12[3][1], t12[3][2]])
Q_body_12 = Gf.Transform(Gf.Matrix4d(t12.tolist())).GetRotation().GetQuat()
# Set the transform between the bodies inside the joints
xaxis_joint.CreateLocalPos0Attr().Set(Gf.Vec3f([0, 0, 0]))
yaxis_joint.CreateLocalPos0Attr().Set(translate_body_12)
xaxis_joint.CreateLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0))
yaxis_joint.CreateLocalRot0Attr().Set(Gf.Quatf(Q_body_12))
xaxis_joint.CreateLocalPos1Attr().Set(Gf.Vec3f([0, 0, 0]))
yaxis_joint.CreateLocalPos1Attr().Set(Gf.Vec3f([0, 0, 0]))
xaxis_joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
yaxis_joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
# Add drives to the joints
if enable_drive:
xaxis_drive = createDrive(
stage.GetPrimAtPath(path + "/" + prefix + "x_axis_joint"),
token="linear",
damping=damping,
stiffness=stiffness,
)
yaxis_drive = createDrive(
stage.GetPrimAtPath(path + "/" + prefix + "y_axis_joint"),
token="linear",
damping=damping,
stiffness=stiffness,
)
return (xaxis_joint, yaxis_joint)
def create3DOFJoint(
stage: Usd.Stage,
path: str,
body_path1: str,
body_path2: str,
) -> UsdPhysics.FixedJoint:
"""
Creates a D6 joint with limits between two bodies to constrain motionin in 2D plane.
Args:
stage (Usd.Stage): The stage to create the fixed joint.
path (str): The path of the fixed joint.
body_path1 (str): The path of the first body.
body_path2 (str): The path of the second body.
Returns:
UsdPhysics.FixedJoint: The fixed joint.
"""
# Create fixed joint
joint = UsdPhysics.Joint.Define(stage, path)
# Set body targets
joint.CreateBody0Rel().SetTargets([body_path1])
joint.CreateBody1Rel().SetTargets([body_path2])
# Get from the simulation the position/orientation of the bodies
translate = Gf.Vec3d(
stage.GetPrimAtPath(body_path2).GetAttribute("xformOp:translate").Get()
)
Q = stage.GetPrimAtPath(body_path2).GetAttribute("xformOp:orient").Get()
quat0 = Gf.Quatf(
Q.GetReal(), Q.GetImaginary()[0], Q.GetImaginary()[1], Q.GetImaginary()[2]
)
# Set the transform between the bodies inside the joint
joint.CreateLocalPos0Attr().Set(translate)
joint.CreateLocalPos1Attr().Set(Gf.Vec3d([0, 0, 0]))
joint.CreateLocalRot0Attr().Set(quat0)
joint.CreateLocalRot1Attr().Set(Gf.Quatf(1, 0, 0, 0))
d6prim = stage.GetPrimAtPath(path)
for dof in ["transX", "transY", "transZ", "rotX", "rotY", "rotZ"]:
if dof in ["transZ", "rotX", "rotY"]:
limitAPI = UsdPhysics.LimitAPI.Apply(d6prim, dof)
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
return joint
| 40,156 | Python | 33.06022 | 117 | 0.633006 |
elharirymatteo/RANS/docs/release_notes.md | Release Notes
=============
2023.1.1a - March 14, 2024
--------------------------
Fixes
-----
- Add workaround for nucleus hang issue on startup
- Fix USD update flags being reset after creating new stage. This should fix the long hang when running the Humanoid environment with `headless=False`.
Known Issues
------------
- A segmentation fault may occasionally occur at the end of a training run. This does not prevent the training from completing successfully.
2023.1.1 - December 12, 2023
----------------------------
Additions
---------
- Add support for viewport recording during training/inferencing using gym wrapper class `RecordVideo`
- Add `enable_recording`, `recording_interval`, `recording_length`, and `recording_fps`, `recording_dir` arguments to config/command-line for video recording
- Add `moviepy` as dependency for video recording
- Add video tutorial for extension workflow, available at [docs/framework/extension_workflow.md](docs/framework/extension_workflow.md)
- Add camera clipping for CartpoleCamera to avoid seeing other environments in the background
Changes
-------
- Use rl_device for sampling random policy (https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/pull/51)
- Add FPS printouts for random policy
- Use absolute path for default checkpoint folder for consistency between Python and extension workflows
- Change camera creation API in CartpoleCamera to use USD APIs instead of `rep.create`
Fixes
-----
- Fix missing device in warp kernel launch for Ant and Humanoid
- Fix typo for velocity iteration (https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/pull/111)
- Clean up private variable access in task classes in favour of property getters
- Clean up private variable access in extension.py in favour of setter methods
- Unregister replicator in extension workflow on training completion to allow for restart
2023.1.0b - November 02, 2023
-----------------------------
Changes
-------
- Update docker scripts to Isaac Sim docker image 2023.1.0-hotfix.1
- Use omniisaacgymenvs module root for app file parsing
- Update FrankaDeformable physics dt for better training stability
Fixes
-----
- Fix CartpoleCamera num_observations value
- Fix missing import in startup randomization for mass and density
2023.1.0a - October 20, 2023
----------------------------
Fixes
-----
- Fix extension loading error in camera app file
2023.1.0 - October 18, 2023
---------------------------
Additions
---------
- Add support for Warp backend task implementation
- Add Warp-based RL examples: Cartpole, Ant, Humanoid
- Add new Factory environments for place and screw: FactoryTaskNutBoltPlace and FactoryTaskNutBoltScrew
- Add new camera-based Cartpole example: CartpoleCamera
- Add new deformable environment showing Franka picking up a deformable tube: FrankaDeformable
- Add support for running OIGE as an extension in Isaac Sim
- Add options to filter collisions between environments and specify global collision filter paths to `RLTask.set_to_scene()`
- Add multinode training support
- Add dockerfile with OIGE
- Add option to select kit app file from command line argument `kit_app`
- Add `rendering_dt` parameter to the task config file for setting rendering dt. Defaults to the same value as the physics dt.
Changes
-------
- `use_flatcache` flag has been renamed to `use_fabric`
- Update hydra-core version to 1.3.2, omegaconf version to 2.3.0
- Update rlgames to version 1.6.1.
- The `get_force_sensor_forces` API for articulations is now deprecated and replaced with `get_measured_joint_forces`
- Remove unnecessary cloning of buffers in VecEnv classes
- Only enable omni.replicator.isaac when domain randomization or cameras are enabled
- The multi-threaded launch script `rlgames_train_mt.py` has been re-designed to support the extension workflow. This script can no longer be used to launch a training run from python. Please use `rlgames_train.py` instead.
- Restructures for environments to support the new extension-based workflow
- Add async workflow to factory pick environment to support extension-based workflow
- Update docker scripts with cache directories
Fixes
-----
- Fix errors related to setting velocities to kinematic markers in Ingenuity and Quadcopter environments
- Fix contact-related issues with quadruped assets
- Fix errors in physics APIs when returning empty tensors
- Fix orientation correctness issues when using some assets with omni.isaac.core. Additional orientations applied to accommodate for the error are no longer required (i.e. ShadowHand)
- Updated the deprecated config name `seq_len` used with RNN networks to `seq_length`
2022.2.1 - March 16, 2023
-------------------------
Additions
---------
- Add FactoryTaskNutBoltPick example
- Add Ant and Humanoid SAC training examples
- Add multi-GPU support for training
- Add utility scripts for launching Isaac Sim docker with OIGE
- Add support for livestream through the Omniverse Streaming Client
Changes
-------
- Change rigid body fixed_base option to make_kinematic, avoiding creation of unnecessary articulations
- Update ShadowHand, Ingenuity, Quadcopter and Crazyflie marker objects to use kinematics
- Update ShadowHand GPU buffer parameters
- Disable PyTorch nvFuser for better performance
- Enable viewport and replicator extensions dynamically to maintain order of extension startup
- Separate app files for headless environments with rendering (requires Isaac Sim update)
- Update rl-games to v1.6.0
Fixes
-----
- Fix material property randomization at run-time, including friction and restitution (requires Isaac Sim update)
- Fix a bug in contact reporting API where incorrect values were being reported (requires Isaac Sim update)
- Enable render flag in Isaac Sim when enable_cameras is set to True
- Add root pose and velocity reset to BallBalance environment
2.0.0 - December 15, 2022
-------------------------
Additions
---------
- Update to Viewport 2.0
- Allow for runtime mass randomization on GPU pipeline
- Add runtime mass randomization to ShadowHand environments
- Introduce `disable_contact_processing` simulation parameter for faster contact processing
- Use physics replication for cloning by default for faster load time
Changes
-------
- Update AnymalTerrain environment to use contact forces
- Update Quadcopter example to apply local forces
- Update training parameters for ShadowHandOpenAI_FF environment
- Rename rlgames_play.py to rlgames_demo.py
Fixes
-----
- Remove fix_base option from articulation configs
- Fix in_hand_manipulation random joint position sampling on reset
- Fix mass and density randomization in MT training script
- Fix actions/observations noise randomization in MT training script
- Fix random seed when domain randomization is enabled
- Check whether simulation is running before executing pre_physics_step logic
1.1.0 - August 22, 2022
-----------------------
Additions
---------
- Additional examples: Anymal, AnymalTerrain, BallBalance, Crazyflie, FrankaCabinet, Ingenuity, Quadcopter
- Add OpenAI variantions for Feed-Forward and LSTM networks for ShadowHand
- Add domain randomization framework `using omni.replicator.isaac`
- Add AnymalTerrain interactable demo
- Automatically disable `omni.kit.window.viewport` and `omni.physx.flatcache` extensions in headless mode to improve start-up load time
- Introduce `reset_xform_properties` flag for initializing Views of cloned environments to reduce load time
- Add WandB support
- Update RL-Games version to 1.5.2
Fixes
-----
- Correctly sets simulation device for GPU simulation
- Fix omni.client import order
- Fix episode length reset condition for ShadowHand and AllegroHand
1.0.0 - June 03, 2022
----------------------
- Initial release for RL examples with Isaac Sim
- Examples provided: AllegroHand, Ant, Cartpole, Humanoid, ShadowHand | 7,825 | Markdown | 40.850267 | 223 | 0.764089 |
elharirymatteo/RANS/docs/examples/training_with_camera.md | ## Reinforcement Learning with Vision in the Loop
Some reinforcement learning tasks can benefit from having image data in the pipeline by collecting sensor data from cameras to use as observations. However, high fidelity rendering can be expensive when scaled up towards thousands of environments during training.
Although Isaac Sim does not currently have the capability to scale towards thousands of environments, we are continually working on improvements to reach the goal. As a starting point, we are providing a simple example showcasing a proof-of-concept for reinforcement learning with vision in the loop.
### CartpoleCamera [cartpole_camera.py](../../omniisaacgymenvs/tasks/cartpole_camera.py)
As an example showcasing the possiblity of reinforcmenet learning with vision in the loop, we provide a variation of the Cartpole task, which uses RGB image data as observations. This example
can be launched with command line argument `task=CartpoleCamera`.
Config files used for this task are:
- **Task config**: [CartpoleCamera.yaml](../../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml)
- **rl_games training config**: [CartpoleCameraPPO.yaml](../../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml)
### Working with Cameras
We have provided an individual app file `apps/omni.isaac.sim.python.gym.camera.kit`, designed specifically towards vision-based RL tasks. This app file provides necessary settings to enable multiple cameras to be rendered each frame. Additional settings are also applied to increase performance when rendering cameras across multiple environments.
In addition, the following settings can be added to the app file to increase performance at a cost of accuracy. By setting these flags to `false`, data collected from the cameras may have a 1 to 2 frame delay.
```
app.renderer.waitIdle=false
app.hydraEngine.waitIdle=false
```
We can also render in white-mode by adding the following line:
```
rtx.debugMaterialType=0
```
### Config Settings
In order for rendering to occur during training, tasks using camera rendering must have the `enable_cameras` flag set to `True` in the task config file. By default, the `omni.isaac.sim.python.gym.camera.kit` app file will be used automatically when `enable_cameras` is set to `True`. This flag is located in the task config file, under the `sim` section.
In addition, the `rendering_dt` parameter can be used to specify the rendering frequency desired. Similar to `dt` for physics simulation frequency, the `rendering_dt` specifies the amount of time in `s` between each rendering step. The `rendering_dt` should be larger or equal to the physics `dt`, and be a multiple of physics `dt`. Note that specifying the `controlFrequencyInv` flag will reduce the control frequency in terms of the physics simulation frequency.
For example, assume control frequency is 30hz, physics simulation frequency is 120 hz, and rendering frequency is 10hz. In the task config file, we can set `dt: 1/120`, `controlFrequencyInv: 4`, such that control is applied every 4 physics steps, and `rendering_dt: 1/10`. In this case, render data will only be updated once every 12 physics steps. Note that both `dt` and `rendering_dt` parameters are under the `sim` section of the config file, while `controlFrequencyInv` is under the `env` section.
### Environment Setup
To set up a task for vision-based RL, we will first need to add a camera to each environment in the scene and wrap it in a Replicator `render_product` to use the vectorized rendering API available in Replicator.
This can be done with the following code in `set_up_scene`:
```python
self.render_products = []
env_pos = self._env_pos.cpu()
for i in range(self._num_envs):
camera = self.rep.create.camera(
position=(-4.2 + env_pos[i][0], env_pos[i][1], 3.0), look_at=(env_pos[i][0], env_pos[i][1], 2.55))
render_product = self.rep.create.render_product(camera, resolution=(self.camera_width, self.camera_height))
self.render_products.append(render_product)
```
Next, we need to initialize Replicator and the PytorchListener, which will be used to collect rendered data.
```python
# start replicator to capture image data
self.rep.orchestrator._orchestrator._is_started = True
# initialize pytorch writer for vectorized collection
self.pytorch_listener = self.PytorchListener()
self.pytorch_writer = self.rep.WriterRegistry.get("PytorchWriter")
self.pytorch_writer.initialize(listener=self.pytorch_listener, device="cuda")
self.pytorch_writer.attach(self.render_products)
```
Then, we can simply collect rendered data from each environment using a single API call:
```python
# retrieve RGB data from all render products
images = self.pytorch_listener.get_rgb_data()
``` | 4,737 | Markdown | 58.974683 | 502 | 0.776019 |
elharirymatteo/RANS/docs/examples/rl_examples.md | ## Reinforcement Learning Examples
We introduce the following reinforcement learning examples that are implemented using
Isaac Sim's RL framework.
Pre-trained checkpoints can be found on the Nucleus server. To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html).
*Note: All commands should be executed from `omniisaacgymenvs/omniisaacgymenvs`.*
- [Reinforcement Learning Examples](#reinforcement-learning-examples)
- [Cartpole cartpole.py](#cartpole-cartpolepy)
- [Ant ant.py](#ant-antpy)
- [Humanoid humanoid.py](#humanoid-humanoidpy)
- [Shadow Hand Object Manipulation shadow_hand.py](#shadow-hand-object-manipulation-shadow_handpy)
- [OpenAI Variant](#openai-variant)
- [LSTM Training Variant](#lstm-training-variant)
- [Allegro Hand Object Manipulation allegro_hand.py](#allegro-hand-object-manipulation-allegro_handpy)
- [ANYmal anymal.py](#anymal-anymalpy)
- [Anymal Rough Terrain anymal_terrain.py](#anymal-rough-terrain-anymal_terrainpy)
- [NASA Ingenuity Helicopter ingenuity.py](#nasa-ingenuity-helicopter-ingenuitypy)
- [Quadcopter quadcopter.py](#quadcopter-quadcopterpy)
- [Crazyflie crazyflie.py](#crazyflie-crazyfliepy)
- [Ball Balance ball_balance.py](#ball-balance-ball_balancepy)
- [Franka Cabinet franka_cabinet.py](#franka-cabinet-franka_cabinetpy)
- [Franka Deformable franka_deformable.py](#franka-deformablepy)
- [Factory: Fast Contact for Robotic Assembly](#factory-fast-contact-for-robotic-assembly)
### Cartpole [cartpole.py](../../omniisaacgymenvs/tasks/cartpole.py)
Cartpole is a simple example that demonstrates getting and setting usage of DOF states using
`ArticulationView` from `omni.isaac.core`. The goal of this task is to move a cart horizontally
such that the pole, which is connected to the cart via a revolute joint, stays upright.
Joint positions and joint velocities are retrieved using `get_joint_positions` and
`get_joint_velocities` respectively, which are required in computing observations. Actions are
applied onto the cartpoles via `set_joint_efforts`. Cartpoles are reset by using `set_joint_positions`
and `set_joint_velocities`.
Training can be launched with command line argument `task=Cartpole`.
Training using the Warp backend can be launched with `task=Cartpole warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Cartpole test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/cartpole.pth`
Config files used for this task are:
- **Task config**: [Cartpole.yaml](../../omniisaacgymenvs/cfg/task/Cartpole.yaml)
- **rl_games training config**: [CartpolePPO.yaml](../../omniisaacgymenvs/cfg/train/CartpolePPO.yaml)
#### CartpoleCamera [cartpole_camera.py](../../omniisaacgymenvs/tasks/cartpole_camera.py)
A variation of the Cartpole task showcases the usage of RGB image data as observations. This example
can be launched with command line argument `task=CartpoleCamera`. Note that to use camera data as
observations, `enable_cameras` must be set to `True` in the task config file. In addition, the example must be run with the `omni.isaac.sim.python.gym.camera.kit` app file provided under `apps`, which applies necessary settings to enable camera training. By default, this app file will be used automatically when `enable_cameras` is set to `True`. Due to this limitation, this
example is currently not available in the extension workflow.
Config files used for this task are:
- **Task config**: [CartpoleCamera.yaml](../../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml)
- **rl_games training config**: [CartpoleCameraPPO.yaml](../../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml)
For more details on training with camera data, please visit [here](training_with_camera.md).
<img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/>
### Ant [ant.py](../../omniisaacgymenvs/tasks/ant.py)
Ant is an example of a simple locomotion task. The goal of this task is to train
quadruped robots (ants) to run forward as fast as possible. This example inherets
from [LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py),
which is a shared class between this example and the humanoid example; this simplifies
implementations for both environemnts since they compute rewards, observations,
and resets in a similar manner. This framework allows us to easily switch between
robots used in the task.
The Ant task includes more examples of utilizing `ArticulationView` from `omni.isaac.core`, which
provides various functions to get and set both DOF states and articulation root states
in a tensorized fashion across all of the actors in the environment. `get_world_poses`,
`get_linear_velocities`, and `get_angular_velocities`, can be used to determine whether the
ants have been moving towards the desired direction and whether they have fallen or flipped over.
Actions are applied onto the ants via `set_joint_efforts`, which moves the ants by setting
torques to the DOFs.
Note that the previously used force sensors and `get_force_sensor_forces` API are now deprecated.
Force sensors can now be retrieved directly using `get_measured_joint_forces` from `ArticulationView`.
Training with PPO can be launched with command line argument `task=Ant`.
Training with SAC with command line arguments `task=AntSAC train=AntSAC`.
Training using the Warp backend can be launched with `task=Ant warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Ant test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth`
Config files used for this task are:
- **PPO task config**: [Ant.yaml](../../omniisaacgymenvs/cfg/task/Ant.yaml)
- **rl_games PPO training config**: [AntPPO.yaml](../../omniisaacgymenvs/cfg/train/AntPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/>
### Humanoid [humanoid.py](../../omniisaacgymenvs/tasks/humanoid.py)
Humanoid is another environment that uses
[LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py). It is conceptually
very similar to the Ant example, where the goal for the humanoid is to run forward
as fast as possible.
Training can be launched with command line argument `task=Humanoid`.
Training with SAC with command line arguments `task=HumanoidSAC train=HumanoidSAC`.
Training using the Warp backend can be launched with `task=Humanoid warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Humanoid test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/humanoid.pth`
Config files used for this task are:
- **PPO task config**: [Humanoid.yaml](../../omniisaacgymenvs/cfg/task/Humanoid.yaml)
- **rl_games PPO training config**: [HumanoidPPO.yaml](../../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/>
### Shadow Hand Object Manipulation [shadow_hand.py](../../omniisaacgymenvs/tasks/shadow_hand.py)
The Shadow Hand task is an example of a challenging dexterity manipulation task with complex contact
dynamics. It resembles OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/)
project and [Robotics Shadow Hand](https://github.com/openai/gym/tree/v0.21.0/gym/envs/robotics)
training environments. The goal of this task is to orient the object in the robot hand to match
a random target orientation, which is visually displayed by a goal object in the scene.
This example inherets from [InHandManipulationTask](../../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py),
which is a shared class between this example and the Allegro Hand example. The idea of
this shared [InHandManipulationTask](../../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py) class
is similar to that of the [LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py);
since the Shadow Hand example and the Allegro Hand example only differ by the robot hand used
in the task, using this shared class simplifies implementation across the two.
In this example, motion of the hand is controlled using position targets with `set_joint_position_targets`.
The object and the goal object are reset using `set_world_poses`; their states are retrieved via
`get_world_poses` for computing observations. It is worth noting that the Shadow Hand model in
this example also demonstrates the use of tendons, which are imported using the `omni.isaac.mjcf` extension.
Training can be launched with command line argument `task=ShadowHand`.
Training with Domain Randomization can be launched with command line argument `task.domain_randomization.randomize=True`.
For best training results with DR, use `num_envs=16384`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand.pth`
Config files used for this task are:
- **Task config**: [ShadowHand.yaml](../../omniisaacgymenvs/cfg/task/ShadowHand.yaml)
- **rl_games training config**: [ShadowHandPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml)
#### OpenAI Variant
In addition to the basic version of this task, there is an additional variant matching OpenAI's
[Learning Dexterity](https://openai.com/blog/learning-dexterity/) project. This variant uses the **openai**
observations in the policy network, but asymmetric observations of the **full_state** in the value network.
This can be launched with command line argument `task=ShadowHandOpenAI_FF`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_FF test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_ff.pth`
Config files used for this are:
- **Task config**: [ShadowHandOpenAI_FF.yaml](../../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_FF.yaml)
- **rl_games training config**: [ShadowHandOpenAI_FFPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml).
#### LSTM Training Variant
This variant uses LSTM policy and value networks instead of feed forward networks, and also asymmetric
LSTM critic designed for the OpenAI variant of the task. This can be launched with command line argument
`task=ShadowHandOpenAI_LSTM`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_LSTM test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_lstm.pth`
Config files used for this are:
- **Task config**: [ShadowHandOpenAI_LSTM.yaml](../../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml)
- **rl_games training config**: [ShadowHandOpenAI_LSTMPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.yaml).
<img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/>
### Allegro Hand Object Manipulation [allegro_hand.py](../../omniisaacgymenvs/tasks/allegro_hand.py)
This example performs the same object orientation task as the Shadow Hand example,
but using the Allegro hand instead of the Shadow hand.
Training can be launched with command line argument `task=AllegroHand`.
Running inference with pre-trained model can be launched with command line argument `task=AllegroHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/allegro_hand.pth`
Config files used for this task are:
- **Task config**: [AllegroHand.yaml](../../omniisaacgymenvs/cfg/task/Allegro.yaml)
- **rl_games training config**: [AllegroHandPPO.yaml](../../omniisaacgymenvs/cfg/train/AllegroHandPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/>
### ANYmal [anymal.py](../../omniisaacgymenvs/tasks/anymal.py)
This example trains a model of the ANYmal quadruped robot from ANYbotics
to follow randomly chosen x, y, and yaw target velocities.
Training can be launched with command line argument `task=Anymal`.
Running inference with pre-trained model can be launched with command line argument `task=Anymal test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal.pth`
Config files used for this task are:
- **Task config**: [Anymal.yaml](../../omniisaacgymenvs/cfg/task/Anymal.yaml)
- **rl_games training config**: [AnymalPPO.yaml](../../omniisaacgymenvs/cfg/train/AnymalPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/>
### Anymal Rough Terrain [anymal_terrain.py](../../omniisaacgymenvs/tasks/anymal_terrain.py)
A more complex version of the above Anymal environment that supports
traversing various forms of rough terrain.
Training can be launched with command line argument `task=AnymalTerrain`.
Running inference with pre-trained model can be launched with command line argument `task=AnymalTerrain test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth`
- **Task config**: [AnymalTerrain.yaml](../../omniisaacgymenvs/cfg/task/AnymalTerrain.yaml)
- **rl_games training config**: [AnymalTerrainPPO.yaml](../../omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml)
**Note** during test time use the last weights generated, rather than the usual best weights.
Due to curriculum training, the reward goes down as the task gets more challenging, so the best weights
do not typically correspond to the best outcome.
**Note** if you use the ANYmal rough terrain environment in your work, please ensure you cite the following work:
```
@misc{rudin2021learning,
title={Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning},
author={Nikita Rudin and David Hoeller and Philipp Reist and Marco Hutter},
year={2021},
journal = {arXiv preprint arXiv:2109.11978}
```
**Note** The OmniIsaacGymEnvs implementation slightly differs from the implementation used in the paper above, which also
uses a different RL library and PPO implementation. The original implementation is made available [here](https://github.com/leggedrobotics/legged_gym). Results reported in the Isaac Gym technical paper are based on that repository, not this one.
<img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="300" height="150"/>
### NASA Ingenuity Helicopter [ingenuity.py](../../omniisaacgymenvs/tasks/ingenuity.py)
This example trains a simplified model of NASA's Ingenuity helicopter to navigate to a moving target.
It showcases the use of velocity tensors and applying force vectors to rigid bodies.
Note that we are applying force directly to the chassis, rather than simulating aerodynamics.
This example also demonstrates using different values for gravitational forces.
Ingenuity Helicopter visual 3D Model courtesy of NASA: https://mars.nasa.gov/resources/25043/mars-ingenuity-helicopter-3d-model/.
Training can be launched with command line argument `task=Ingenuity`.
Running inference with pre-trained model can be launched with command line argument `task=Ingenuity test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ingenuity.pth`
Config files used for this task are:
- **Task config**: [Ingenuity.yaml](../../omniisaacgymenvs/cfg/task/Ingenuity.yaml)
- **rl_games training config**: [IngenuityPPO.yaml](../../omniisaacgymenvs/cfg/train/IngenuityPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/>
### Quadcopter [quadcopter.py](../../omniisaacgymenvs/tasks/quadcopter.py)
This example trains a very simple quadcopter model to reach and hover near a fixed position.
Lift is achieved by applying thrust forces to the "rotor" bodies, which are modeled as flat cylinders.
In addition to thrust, the pitch and roll of each rotor is controlled using DOF position targets.
Training can be launched with command line argument `task=Quadcopter`.
Running inference with pre-trained model can be launched with command line argument `task=Quadcopter test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/quadcopter.pth`
Config files used for this task are:
- **Task config**: [Quadcopter.yaml](../../omniisaacgymenvs/cfg/task/Quadcopter.yaml)
- **rl_games training config**: [QuadcopterPPO.yaml](../../omniisaacgymenvs/cfg/train/QuadcopterPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/>
### Crazyflie [crazyflie.py](../../omniisaacgymenvs/tasks/crazyflie.py)
This example trains the Crazyflie drone model to hover near a fixed position. It is achieved by applying thrust forces to the four rotors.
Training can be launched with command line argument `task=Crazyflie`.
Running inference with pre-trained model can be launched with command line argument `task=Crazyflie test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/crazyflie.pth`
Config files used for this task are:
- **Task config**: [Crazyflie.yaml](../../omniisaacgymenvs/cfg/task/Crazyflie.yaml)
- **rl_games training config**: [CrazyfliePPO.yaml](../../omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml)
<img src="https://user-images.githubusercontent.com/6352136/185715165-b430a0c7-948b-4dce-b3bb-7832be714c37.gif" width="300" height="150"/>
### Ball Balance [ball_balance.py](../../omniisaacgymenvs/tasks/ball_balance.py)
This example trains balancing tables to balance a ball on the table top.
This is a great example to showcase the use of force and torque sensors, as well as DOF states for the table and root states for the ball.
In this example, the three-legged table has a force sensor attached to each leg.
We use the force sensor APIs to collect force and torque data on the legs, which guide position target outputs produced by the policy.
Training can be launched with command line argument `task=BallBalance`.
Running inference with pre-trained model can be launched with command line argument `task=BallBalance test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ball_balance.pth`
Config files used for this task are:
- **Task config**: [BallBalance.yaml](../../omniisaacgymenvs/cfg/task/BallBalance.yaml)
- **rl_games training config**: [BallBalancePPO.yaml](../../omniisaacgymenvs/cfg/train/BallBalancePPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/>
### Franka Cabinet [franka_cabinet.py](../../omniisaacgymenvs/tasks/franka_cabinet.py)
This Franka example demonstrates interaction between Franka arm and cabinet, as well as setting states of objects inside the drawer.
It also showcases control of the Franka arm using position targets.
In this example, we use DOF state tensors to retrieve the state of the Franka arm, as well as the state of the drawer on the cabinet.
Actions are applied as position targets to the Franka arm DOFs.
Training can be launched with command line argument `task=FrankaCabinet`.
Running inference with pre-trained model can be launched with command line argument `task=FrankaCabinet test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_cabinet.pth`
Config files used for this task are:
- **Task config**: [FrankaCabinet.yaml](../../omniisaacgymenvs/cfg/task/FrankaCabinet.yaml)
- **rl_games training config**: [FrankaCabinetPPO.yaml](../../omniisaacgymenvs/cfg/train/FrankaCabinetPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/>
### Franka Deformable [franka_deformable.py](../../omniisaacgymenvs/tasks/franka_deformable.py)
This Franka example demonstrates interaction between Franka arm and a deformable tube. It demonstrates the manipulation of deformable objects, using nodal positions and velocities of the simulation mesh as observations.
Training can be launched with command line argument `task=FrankaDeformable`.
Running inference with pre-trained model can be launched with command line argument `task=FrankaDeformable test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_deformable.pth`
Config files used for this task are:
- **Task config**: [FrankaDeformable.yaml](../../omniisaacgymenvs/cfg/task/FrankaDeformable.yaml)
- **rl_games training config**: [FrankaCabinetFrankaDeformable.yaml](../../omniisaacgymenvs/cfg/train/FrankaDeformablePPO.yaml)
### Factory: Fast Contact for Robotic Assembly
We provide a set of Factory example tasks, [**FactoryTaskNutBoltPick**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_pick.py), [**FactoryTaskNutBoltPlace**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_place.py), and [**FactoryTaskNutBoltScrew**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_screw.py),
`FactoryTaskNutBoltPick` can be executed with `python train.py task=FactoryTaskNutBoltPick`. This task trains policy for the Pick task, a simplified version of the corresponding task in the Factory paper. The policy may take ~1 hour to achieve high success rates on a modern GPU.
- The general configuration file for the above task is [FactoryTaskNutBoltPick.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPick.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltPickPPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPickPPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPick test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_pick.pth`
`FactoryTaskNutBoltPlace` can be executed with `python train.py task=FactoryTaskNutBoltPlace`. This task trains policy for the Place task.
- The general configuration file for the above task is [FactoryTaskNutBoltPlace.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPlace.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltPlacePPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPlacePPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPlace test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_place.pth`
`FactoryTaskNutBoltScrew` can be executed with `python train.py task=FactoryTaskNutBoltScrew`. This task trains policy for the Screw task.
- The general configuration file for the above task is [FactoryTaskNutBoltScrew.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltScrew.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltScrewPPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltScrewPPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltScrew test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_screw.pth`
If you use the Factory simulation methods (e.g., SDF collisions, contact reduction) or Factory learning tools (e.g., assets, environments, or controllers) in your work, please cite the following paper:
```
@inproceedings{
narang2022factory,
author = {Yashraj Narang and Kier Storey and Iretiayo Akinola and Miles Macklin and Philipp Reist and Lukasz Wawrzyniak and Yunrong Guo and Adam Moravanszky and Gavriel State and Michelle Lu and Ankur Handa and Dieter Fox},
title = {Factory: Fast contact for robotic assembly},
booktitle = {Robotics: Science and Systems},
year = {2022}
}
```
Also note that our original formulations of SDF collisions and contact reduction were developed by [Macklin, et al.](https://dl.acm.org/doi/abs/10.1145/3384538) and [Moravanszky and Terdiman](https://scholar.google.com/scholar?q=Game+Programming+Gems+4%2C+chapter+Fast+Contact+Reduction+for+Dynamics+Simulation), respectively.
<img src="https://user-images.githubusercontent.com/6352136/205978286-fa2ae714-a3cb-4acd-9f5f-a467338a8bb3.gif"/>
| 25,398 | Markdown | 64.46134 | 377 | 0.787188 |
elharirymatteo/RANS/docs/examples/transfering_policies_from_isaac_gym.md | ## Transfering Policies from Isaac Gym Preview Releases
This section delineates some of the differences between the standalone
[Isaac Gym Preview Releases](https://developer.nvidia.com/isaac-gym) and
Isaac Sim reinforcement learning extensions, in hopes of facilitating the
process of transferring policies trained in the standalone preview releases
to Isaac Sim.
### Isaac Sim RL Extensions
Unlike the monolithic standalone Isaac Gym Preview Releases, Omniverse is
a highly modular system, with functionality split between various [Extensions](https://docs.omniverse.nvidia.com/extensions/latest/index.html).
The APIs used by typical robotics RL systems are split between a handful of
extensions in Isaac Sim. These include `omni.isaac.core`, which provides
tensorized access to physics simulation state as well as a task management
framework, the `omni.isaac.cloner` extension for creating many copies of
your environments, and the `omni.isaac.gym` extension for interfacing with
external RL training libraries.
For naming clarity, we'll refer collectively to the extensions used for RL
within Isaac Sim as the **Isaac Sim RL extensions**, in contrast with the
older **Isaac Gym Preview Releases**.
### Quaternion Convention
The Isaac Sim RL extensions use various classes and methods in `omni.isaac.core`,
which adopts `wxyz` as the quaternion convention. However, the quaternion
convention used in Isaac Gym Preview Releases is `xyzw`. Therefore, if a policy
trained in one of the Isaac Gym Preview Releases takes in quaternions as part
of its observations, remember to switch all quaternions to use the `xyzw` convention
in the observation buffer `self.obs_buf`. Similarly, please ensure all quaternions
are in `wxyz` before passing them in any of the utility functions in `omni.isaac.core`.
### Assets
Isaac Sim provides [URDF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_urdf.html)
and [MJCF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_mjcf.html) importers for translating URDF and MJCF assets into USD format.
Any robot or object assets must be in .usd, .usda, or .usdc format for Isaac Sim and Omniverse.
For more details on working with USD, please see https://docs.omniverse.nvidia.com/isaacsim/latest/reference_glossary.html#usd.
Importer tools are also available for other common geometry file formats, such as .obj, .fbx, and more.
Please see [Asset Importer](https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-importer.html) for more details.
### Joint Order
Isaac Sim's `ArticulationView` in `omni.isaac.core` assumes a breadth-first
ordering for the joints in a given kinematic tree. Specifically, for the following
kinematic tree, the method `ArticulationView.get_joint_positions` returns a
tensor of shape `(number of articulations in the view, number of joints in the articulation)`.
Along the second dimension of this tensor, the values represent the articulation's joint positions
in the following order: `[Joint 1, Joint 2, Joint 4, Joint 3, Joint 5]`. On the other hand,
the Isaac Gym Preview Releases assume a depth-first ordering for the joints in the kinematic
tree; In the example below, the joint orders would be the following: `[Joint 1, Joint 2, Joint 3, Joint 4, Joint 5]`.
<img src="./media/KinematicTree.png" height="300"/>
With this in mind, it is important to change the joint order to depth-first in
the observation buffer before feeding it into an existing policy trained in one of the
Isaac Gym Preview Releases. Similarly, you would also need to change the joint order
in the output (the action buffer) of the Isaac Gym Preview Release trained policy
to breadth-first before applying joint actions to articulations via methods in `ArticulationView`.
### Physics Parameters
One factor that could dictate the success of policy transfer from Isaac Gym Preview
Releases to Isaac Sim is to ensure the physics parameters used in both simulations are
identical or very similar. In general, the `sim` parameters specified in the
task configuration `yaml` file overwrite the corresponding parameters in the USD asset.
However, there are additional parameters in the USD asset that are not included
in the task configuration `yaml` file. These additional parameters may sometimes
impact the performance of Isaac Gym Preview Release trained policies and hence need
modifications in the USD asset itself to match the values set in Isaac Gym Preview Releases.
For instance, the following parameters in the `RigidBodyAPI` could be modified in the
USD asset to yield better policy transfer performance:
| RigidBodyAPI Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases |
|:----------------------:|:--------------------------:|:--------------------------:|
| Linear Damping | 0.00 | 0.00 |
| Angular Damping | 0.05 | 0.00 |
| Max Linear Velocity | inf | 1000 |
| Max Angular Velocity | 5729.58008 (deg/s) | 64 (rad/s) |
| Max Contact Impulse | inf | 1e32 |
<img src="./media/RigidBodyAPI.png" width="500"/>
Parameters in the `JointAPI` as well as the `DriveAPI` could be altered as well. Note
that the Isaac Sim UI assumes the unit of angle to be degrees. It is particularly
worth noting that the `Damping` and `Stiffness` paramters in the `DriveAPI` have the unit
of `1/deg` in the Isaac Sim UI but `1/rad` in Isaac Gym Preview Releases.
| Joint Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases |
|:----------------------:|:--------------------------:|:--------------------------:|
| Maximum Joint Velocity | 1000000.0 (deg) | 100.0 (rad) |
<img src="./media/JointAPI.png" width="500"/>
### Differences in APIs
APIs for accessing physics states in Isaac Sim require the creation of an ArticulationView or RigidPrimView
object. Multiple view objects can be initialized for different articulations or bodies in the scene by defining
a regex expression that matches the paths of the desired objects. This approach eliminates the need of retrieving
body handles to slice states for specific bodies in the scene.
We have also removed `acquire` and `refresh` APIs in Isaac Sim. Physics states can be directly applied or retrieved
by using `set`/`get` APIs defined for the views.
New APIs provided in Isaac Sim no longer require explicit wrapping and un-wrapping of underlying buffers.
APIs can now work with tensors directly for reading and writing data. Most APIs in Isaac Sim also provide
the option to specify an `indices` parameter, which can be used when reading or writing data for a subset
of environments. Note that when setting states with the `indices` parameter, the shape of the states buffer
should match with the dimension of the `indices` list.
Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Sim. Most `dof` related APIs have been
named to `joint` in Isaac Sim. `root_states` is now separated into different APIs for `world_poses` and `velocities`.
Similary, `dof_states` are retrieved individually in Isaac Sim as `joint_positions` and `joint_velocities`.
APIs in Isaac Sim also no longer follow the explicit `_tensors` or `_tensor_indexed` suffixes in naming.
Indexed versions of APIs now happen implicitly through the optional `indices` parameter.
### Task Configuration Files
There are a few modifications that need to be made to an existing Isaac Gym Preview Release
task `yaml` file in order for it to be compatible with the Isaac Sim RL extensions.
#### Frequencies of Physics Simulation and RL Policy
The way in which physics simulation frequency and RL policy frequency are specified is different
between Isaac Gym Preview Releases and Isaac Sim, dictated by the following three
parameters: `dt`, `substeps`, and `controlFrequencyInv`.
- `dt`: The simulation time difference between each simulation step.
- `substeps`: The number of physics steps within one simulation step. *i.e.* if `dt: 1/60`
and `substeps: 4`, physics is simulated at 240 hz.
- `controlFrequencyInv`: The control decimation of the RL policy, which is the number of
simulation steps between RL actions. *i.e.* if `dt: 1/60` and `controlFrequencyInv: 2`,
RL policy is running at 30 hz.
In Isaac Gym Preview Releases, all three of the above parameters are used to specify
the frequencies of physics simulation and RL policy. However, Isaac Sim only uses `controlFrequencyInv` and `dt` as `substeps` is always fixed at `1`. Note that despite
only using two parameters, Isaac Sim can still achieve the same substeps definition
as Isaac Gym. For example, if in an Isaac Gym Preview Release policy, we set `substeps: 2`,
`dt: 1/60` and `controlFrequencyInv: 1`, we can achieve the equivalent in Isaac Sim
by setting `controlFrequencyInv: 2` and `dt: 1/120`.
In the Isaac Sim RL extensions, `dt` is specified in the task configuration `yaml` file
under `sim`, whereas `controlFrequencyInv` is a parameter under `env`.
#### Physx Parameters
Parameters under `physx` in the task configuration `yaml` file remain mostly unchanged.
In Isaac Gym Preview Releases, `use_gpu` is frequently set to
`${contains:"cuda",${....sim_device}}`. For Isaac Sim, please ensure this is changed
to `${eq:${....sim_device},"gpu"}`.
In Isaac Gym Preview Releases, GPU buffer sizes are specified using the following two parameters:
`default_buffer_size_multiplier` and `max_gpu_contact_pairs`. With the Isaac Sim RL extensions,
these two parameters are no longer used; instead, the various GPU buffer sizes can be
set explicitly.
For instance, in the [Humanoid task configuration file](../omniisaacgymenvs/cfg/task/Humanoid.yaml),
GPU buffer sizes are specified as follows:
```yaml
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
```
Please refer to the [Troubleshooting](./troubleshoot.md#simulation) documentation should
you encounter errors related to GPU buffer sizes.
#### Articulation Parameters
The articulation parameters of each actor can now be individually specified tn the Isaac Sim
task configuration `yaml` file. The following is an example template for setting these parameters:
```yaml
ARTICULATION_NAME:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 10.0
```
These articulation parameters can be parsed using the `parse_actor_config` method in the
[SimConfig](../omniisaacgymenvs/utils/config_utils/sim_config.py) class, which can then be applied
to a prim in simulation via the `apply_articulation_settings` method. A concrete example of this
is the following code snippet from the [HumanoidTask](../omniisaacgymenvs/tasks/humanoid.py#L75):
```python
self._sim_config.apply_articulation_settings("Humanoid", get_prim_at_path(humanoid.prim_path), self._sim_config.parse_actor_config("Humanoid"))
```
#### Additional Simulation Parameters
- `use_fabric`: Setting this paramter to `True` enables [PhysX Fabric](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#flatcache), which offers a significant increase in simulation speed. However, this parameter must
be set to `False` if soft-body simulation is required because `PhysX Fabric` curently only supports rigid-body simulation.
- `enable_scene_query_support`: Setting this paramter to `True` allows the user to interact with prims in the scene. Keeping this setting to `False` during
training improves simulation speed. Note that this parameter is always set to `True` if in test/inference mode to enable user interaction with trained models.
### Training Configuration Files
The Omniverse Isaac Gym RL Environments are trained using a third-party highly-optimized RL library,
[rl_games](https://github.com/Denys88/rl_games), which is also used to train the Isaac Gym Preview Release examples
in [IsaacGymEnvs](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs). Therefore, the rl_games training
configuration `yaml` files in Isaac Sim are compatible with those from IsaacGymEnvs. However, please
add the following lines under `config` in the training configuration `yaml` files (*i.e.*
line 41-42 in [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml#L41)) to ensure
RL training runs on the intended device.
```yaml
device: ${....rl_device}
device_name: ${....rl_device}
``` | 13,250 | Markdown | 55.387234 | 252 | 0.749585 |
elharirymatteo/RANS/docs/framework/domain_randomization.md | Domain Randomization
====================
Overview
--------
We sometimes need our reinforcement learning agents to be robust to
different physics than they are trained with, such as when attempting a
sim2real policy transfer. Using domain randomization (DR), we repeatedly
randomize the simulation dynamics during training in order to learn a
good policy under a wide range of physical parameters.
OmniverseIsaacGymEnvs supports "on the fly" domain randomization, allowing
dynamics to be changed without requiring reloading of assets. This allows
us to efficiently apply domain randomizations without common overheads like
re-parsing asset files.
The OmniverseIsaacGymEnvs DR framework utilizes the `omni.replicator.isaac`
extension in its backend to perform "on the fly" randomization. Users can
add domain randomization by either directly using methods provided in
`omni.replicator.isaac` in python, or specifying DR settings in the
task configuration `yaml` file. The following sections will focus on setting
up DR using the `yaml` file interface. For more detailed documentations
regarding methods provided in the `omni.replicator.isaac` extension, please
visit [here](https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.replicator.isaac/docs/index.html).
Domain Randomization Options
-------------------------------
We will first explain what can be randomized in the scene and the sampling
distributions. There are five main parameter groups that support randomization.
They are:
- `observations`: Add noise directly to the agent observations
- `actions`: Add noise directly to the agent actions
- `simulation`: Add noise to physical parameters defined for the entire
scene, such as `gravity`
- `rigid_prim_views`: Add noise to properties belonging to rigid prims,
such as `material_properties`.
- `articulation_views`: Add noise to properties belonging to articulations,
such as `stiffness` of joints.
For each parameter you wish to randomize, you can specify two ways that
determine when the randomization is applied:
- `on_reset`: Adds correlated noise to a parameter of an environment when
that environment gets reset. This correlated noise will remain
with an environment until that environemnt gets reset again, which
will then set a new correlated noise. To trigger `on_reset`,
the indices for the environemnts that need to be reset must be passed in
to `omni.replicator.isaac.physics_view.step_randomization(reset_inds)`.
- `on_interval`: Adds uncorrelated noise to a parameter at a frequency specified
by `frequency_interval`. If a parameter also has `on_reset` randomization,
the `on_interval` noise is combined with the noise applied at `on_reset`.
- `on_startup`: Applies randomization once prior to the start of the simulation. Only available
to rigid prim scale, mass, density and articulation scale parameters.
For `on_reset`, `on_interval`, and `on_startup`, you can specify the following settings:
- `distribution`: The distribution to generate a sample `x` from. The available distributions
are listed below. Note that parameters `a` and `b` are defined by the
`distribution_parameters` setting.
- `uniform`: `x ~ unif(a, b)`
- `loguniform`: `x ~ exp(unif(log(a), log(b)))`
- `gaussian`: `x ~ normal(a, b)`
- `distribution_parameters`: The parameters to the distribution.
- For observations and actions, this setting is specified as a tuple `[a, b]` of
real values.
- For simulation and view parameters, this setting is specified as a nested tuple
in the form of `[[a_1, a_2, ..., a_n], [[b_1, b_2, ..., b_n]]`, where the `n` is
the dimension of the parameter (*i.e.* `n` is 3 for position). It can also be
specified as a tuple in the form of `[a, b]`, which will be broadcasted to the
correct dimensions.
- For `uniform` and `loguniform` distributions, `a` and `b` are the lower and
upper bounds.
- For `gaussian`, `a` is the distribution mean and `b` is the variance.
- `operation`: Defines how the generated sample `x` will be applied to the original
simulation parameter. The options are `additive`, `scaling`, `direct`.
- `additive`:, add the sample to the original value.
- `scaling`: multiply the original value by the sample.
- `direct`: directly sets the sample as the parameter value.
- `frequency_interval`: Specifies the number of steps to apply randomization.
- Only used with `on_interval`.
- Steps of each environemnt are incremented with each
`omni.replicator.isaac.physics_view.step_randomization(reset_inds)` call and
reset if the environment index is in `reset_inds`.
- `num_buckets`: Only used for `material_properties` randomization
- Physx only allows 64000 unique physics materials in the scene at once. If more than
64000 materials are needed, increase `num_buckets` to allow materials to be shared
between prims.
YAML Interface
--------------
Now that we know what options are available for domain randomization,
let's put it all together in the YAML config. In your `omniverseisaacgymenvs/cfg/task`
yaml file, you can specify your domain randomization parameters under the
`domain_randomization` key. First, we turn on domain randomization by setting
`randomize` to `True`:
```yaml
domain_randomization:
randomize: True
randomization_params:
...
```
This can also be set as a command line argument at launch time with `task.domain_randomization.randomize=True`.
Next, we will define our parameters under the `randomization_params`
keys. Here you can see how we used the previous settings to define some
randomization parameters for a ShadowHand cube manipulation task:
```yaml
randomization_params:
randomization_params:
observations:
on_reset:
operation: "additive"
distribution: "gaussian"
distribution_parameters: [0, .0001]
on_interval:
frequency_interval: 1
operation: "additive"
distribution: "gaussian"
distribution_parameters: [0, .002]
actions:
on_reset:
operation: "additive"
distribution: "gaussian"
distribution_parameters: [0, 0.015]
on_interval:
frequency_interval: 1
operation: "additive"
distribution: "gaussian"
distribution_parameters: [0., 0.05]
simulation:
gravity:
on_reset:
operation: "additive"
distribution: "gaussian"
distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]]
rigid_prim_views:
object_view:
material_properties:
on_reset:
num_buckets: 250
operation: "scaling"
distribution: "uniform"
distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]]
articulation_views:
shadow_hand_view:
stiffness:
on_reset:
operation: "scaling"
distribution: "uniform"
distribution_parameters: [0.75, 1.5]
```
Note how we structured `rigid_prim_views` and `articulation_views`. When creating
a `RigidPrimView` or `ArticulationView` in the task python file, you have the option to
pass in `name` as an argument. **To use domain randomization, the name of the `RigidPrimView` or
`ArticulationView` must match the name provided in the randomization `yaml` file.** In the
example above, `object_view` is the name of a `RigidPrimView` and `shadow_hand_view` is the name
of the `ArticulationView`.
The exact parameters that can be randomized are listed below:
**simulation**:
- gravity (dim=3): The gravity vector of the entire scene.
**rigid\_prim\_views**:
- position (dim=3): The position of the rigid prim. In meters.
- orientation (dim=3): The orientation of the rigid prim, specified with euler angles. In radians.
- linear_velocity (dim=3): The linear velocity of the rigid prim. In m/s. **CPU pipeline only**
- angular_velocity (dim=3): The angular velocity of the rigid prim. In rad/s. **CPU pipeline only**
- velocity (dim=6): The linear + angular velocity of the rigid prim.
- force (dim=3): Apply a force to the rigid prim. In N.
- mass (dim=1): Mass of the rigid prim. In kg. **CPU pipeline only during runtime**.
- inertia (dim=3): The diagonal values of the inertia matrix. **CPU pipeline only**
- material_properties (dim=3): Static friction, Dynamic friction, and Restitution.
- contact_offset (dim=1): A small distance from the surface of the collision geometry at
which contacts start being generated.
- rest_offset (dim=1): A small distance from the surface of the collision geometry at
which the effective contact with the shape takes place.
- scale (dim=1): The scale of the rigid prim. `on_startup` only.
- density (dim=1): Density of the rigid prim. `on_startup` only.
**articulation\_views**:
- position (dim=3): The position of the articulation root. In meters.
- orientation (dim=3): The orientation of the articulation root, specified with euler angles. In radians.
- linear_velocity (dim=3): The linear velocity of the articulation root. In m/s. **CPU pipeline only**
- angular_velocity (dim=3): The angular velocity of the articulation root. In rad/s. **CPU pipeline only**
- velocity (dim=6): The linear + angular velocity of the articulation root.
- stiffness (dim=num_dof): The stiffness of the joints.
- damping (dim=num_dof): The damping of the joints
- joint_friction (dim=num_dof): The friction coefficient of the joints.
- joint_positions (dim=num_dof): The joint positions. In radians or meters.
- joint_velocities (dim=num_dof): The joint velocities. In rad/s or m/s.
- lower_dof_limits (dim=num_dof): The lower limit of the joints. In radians or meters.
- upper_dof_limits (dim=num_dof): The upper limit of the joints. In radians or meters.
- max_efforts (dim=num_dof): The maximum force or torque that the joints can exert. In N or Nm.
- joint_armatures (dim=num_dof): A value added to the diagonal of the joint-space inertia matrix.
Physically, it corresponds to the rotating part of a motor
- joint_max_velocities (dim=num_dof): The maximum velocity allowed on the joints. In rad/s or m/s.
- joint_efforts (dim=num_dof): Applies a force or a torque on the joints. In N or Nm.
- body_masses (dim=num_bodies): The mass of each body in the articulation. In kg. **CPU pipeline only**
- body_inertias (dim=num_bodies×3): The diagonal values of the inertia matrix of each body. **CPU pipeline only**
- material_properties (dim=num_bodies×3): The static friction, dynamic friction, and restitution of each body
in the articulation, specified in the following order:
[body_1_static_friciton, body_1_dynamic_friciton, body_1_restitution,
body_1_static_friciton, body_2_dynamic_friciton, body_2_restitution,
... ]
- tendon_stiffnesses (dim=num_tendons): The stiffness of the fixed tendons in the articulation.
- tendon_dampings (dim=num_tendons): The damping of the fixed tendons in the articulation.
- tendon_limit_stiffnesses (dim=num_tendons): The limit stiffness of the fixed tendons in the articulation.
- tendon_lower_limits (dim=num_tendons): The lower limits of the fixed tendons in the articulation.
- tendon_upper_limits (dim=num_tendons): The upper limits of the fixed tendons in the articulation.
- tendon_rest_lengths (dim=num_tendons): The rest lengths of the fixed tendons in the articulation.
- tendon_offsets (dim=num_tendons): The offsets of the fixed tendons in the articulation.
- scale (dim=1): The scale of the articulation. `on_startup` only.
Applying Domain Randomization
------------------------------
To parse the domain randomization configurations in the task `yaml` file and set up the DR pipeline,
it is necessary to call `self._randomizer.set_up_domain_randomization(self)`, where `self._randomizer`
is the `Randomizer` object created in RLTask's `__init__`.
It is worth noting that the names of the views provided under `rigid_prim_views` or `articulation_views`
in the task `yaml` file must match the names passed into `RigidPrimView` or `ArticulationView` objects
in the python task file. In addition, all `RigidPrimView` and `ArticulationView` that would have domain
randomizaiton applied must be added to the scene in the task's `set_up_scene()` via `scene.add()`.
To trigger `on_startup` randomizations, call `self._randomizer.apply_on_startup_domain_randomization(self)`
in `set_up_scene()` after all views are added to the scene. Note that `on_startup` randomizations
are only availble to rigid prim scale, mass, density and articulation scale parameters since these parameters
cannot be randomized after the simulation begins on GPU pipeline. Therefore, randomizations must be applied
to these parameters in `set_up_scene()` prior to the start of the simulation.
To trigger `on_reset` and `on_interval` randomizations, it is required to step the interal
counter of the DR pipeline in `pre_physics_step()`:
```python
if self._randomizer.randomize:
omni.replicator.isaac.physics_view.step_randomization(reset_inds)
```
`reset_inds` is a list of indices of the environments that need to be reset. For those environments, it will
trigger the randomizations defined with `on_reset`. All other environments will follow randomizations
defined with `on_interval`.
Randomization Scheduling
----------------------------
We provide methods to modify distribution parameters defined in the `yaml` file during training, which
allows custom DR scheduling. There are three methods from the `Randomizer` class
that are relevant to DR scheduling:
- `get_initial_dr_distribution_parameters`: returns a numpy array of the initial parameters (as defined in
the `yaml` file) of a specified distribution
- `get_dr_distribution_parameters`: returns a numpy array of the current parameters of a specified distribution
- `set_dr_distribution_parameters`: sets new parameters to a specified distribution
Using the DR configuration example defined above, we can get the current parameters and set new parameters
to gravity randomization and shadow hand joint stiffness randomization as follows:
```python
current_gravity_dr_params = self._randomizer.get_dr_distribution_parameters(
"simulation",
"gravity",
"on_reset",
)
self._randomizer.set_dr_distribution_parameters(
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.5]],
"simulation",
"gravity",
"on_reset",
)
current_joint_stiffness_dr_params = self._randomizer.get_dr_distribution_parameters(
"articulation_views",
"shadow_hand_view",
"stiffness",
"on_reset",
)
self._randomizer.set_dr_distribution_parameters(
[0.7, 1.55],
"articulation_views",
"shadow_hand_view",
"stiffness",
"on_reset",
)
```
The following is an example of using these methods to perform linear scheduling of gaussian noise
that is added to observations and actions in the above shadow hand example. The following method
linearly adds more noise to observations and actions every epoch up until the `schedule_epoch`.
This method can be added to the Task python class and be called in `pre_physics_step()`.
```python
def apply_observations_actions_noise_linear_scheduling(self, schedule_epoch=100):
current_epoch = self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"] // self._cfg["train"]["params"]["config"]["horizon_length"]
if current_epoch <= schedule_epoch:
if (self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"]) % self._cfg["train"]["params"]["config"]["horizon_length"] == 0:
for distribution_path in [("observations", "on_reset"), ("observations", "on_interval"), ("actions", "on_reset"), ("actions", "on_interval")]:
scheduled_params = self._randomizer.get_initial_dr_distribution_parameters(*distribution_path)
scheduled_params[1] = (1/schedule_epoch) * current_epoch * scheduled_params[1]
self._randomizer.set_dr_distribution_parameters(scheduled_params, *distribution_path)
```
| 16,889 | Markdown | 51.453416 | 156 | 0.68814 |
elharirymatteo/RANS/docs/framework/instanceable_assets.md | ## A Note on Instanceable USD Assets
The following section presents a method that modifies existing USD assets
which allows Isaac Sim to load significantly more environments. This is currently
an experimental method and has thus not been completely integrated into the
framework. As a result, this section is reserved for power users who wish to
maxmimize the performance of the Isaac Sim RL framework.
### Motivation
One common issue in Isaac Sim that occurs when we try to increase
the number of environments `numEnvs` is running out of RAM. This occurs because
the Isaac Sim RL framework uses `omni.isaac.cloner` to duplicate environments.
As a result, there are `numEnvs` number of identical copies of the visual and
collision meshes in the scene, which consumes lots of memory. However, only one
copy of the meshes are needed on stage since prims in all other environments could
merely reference that one copy, thus reducing the amount of memory used for loading
environments. To enable this functionality, USD assets need to be modified to be
`instanceable`.
### Creating Instanceable Assets
Assets can now be directly imported as Instanceable assets through the URDF and MJCF importers provided in Isaac Sim. By selecting this option, imported assets will be split into two separate USD files that follow the above hierarchy definition. Any mesh data will be written to an USD stage to be referenced by the main USD stage, which contains the main robot definition.
To use the Instanceable option in the importers, first check the `Create Instanceable Asset` option. Then, specify a file path to indicate the location for saving the mesh data in the `Instanceable USD Path` textbox. This will default to `./instanceable_meshes.usd`, which will generate a file `instanceable_meshes.usd` that is saved to the current directory.
Once the asset is imported with these options enabled, you will see the robot definition in the stage - we will refer to this stage as the master stage. If we expand the robot hierarchy in the Stage, we will notice that the parent prims that have mesh decendants have been marked as Instanceable and they reference a prim in our `Instanceable USD Path` USD file. We are also no longer able to modify attributes of descendant meshes.
To add the instanced asset into a new stage, we will simply need to add the master USD file.
### Converting Existing Assets
We provide the utility function `convert_asset_instanceable`, which creates an instanceable
version of a given USD asset in `/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py`.
To run this function, launch Isaac Sim and open the script editor via `Window -> Script Editor`.
Enter the following script and press `Run (Ctrl + Enter)`:
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import convert_asset_instanceable
convert_asset_instanceable(
asset_usd_path=ASSET_USD_PATH,
source_prim_path=SOURCE_PRIM_PATH,
save_as_path=SAVE_AS_PATH
)
```
Note that `ASSET_USD_PATH` is the file path to the USD asset (*e.g.* robot_asset.usd).
`SOURCE_PRIM_PATH` is the USD path of the root prim of the asset on stage. `SAVE_AS_PATH`
is the file path of the generated instanceable version of the asset
(*e.g.* robot_asset_instanceable.usd).
Assuming that `SAVE_AS_PATH` is `OUTPUT_NAME.usd`, the above script will generate two files:
`OUTPUT_NAME.usd` and `OUTPUT_NAME_meshes.usd`. `OUTPUT_NAME.usd` is the instanceable version
of the asset that can be imported to stage and used by `omni.isaac.cloner` to create numerous
duplicates without consuming much memory. `OUTPUT_NAME_meshes.usd` contains all the visual
and collision meshes that `OUTPUT_NAME.usd` references.
It is worth noting that any [USD Relationships](https://graphics.pixar.com/usd/dev/api/class_usd_relationship.html)
on the referenced meshes are removed in `OUTPUT_NAME.usd`. This is because those USD Relationships
originally have targets set to prims in `OUTPUT_NAME_meshes.usd` and hence cannot be accessed
from `OUTPUT_NAME.usd`. Common examples of USD Relationships that could exist on the meshes are
visual materials, physics materials, and filtered collision pairs. Therefore, it is recommanded
to set these USD Relationships on the meshes' parent Xforms instead of the meshes themselves.
In a case where we would like to update the main USD file where the instanceable USD file is being referenced from, we also provide a utility method to update all references in the stage that matches a source reference path to a new USD file path.
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import update_reference
update_reference(
source_prim_path=SOURCE_PRIM_PATH,
source_reference_path=SOURCE_REFERENCE_PATH,
target_reference_path=TARGET_REFERENCE_PATH
)
```
### Limitations
USD requires a specific structure in the asset tree definition in order for the instanceable flag to take action. To mark any mesh or primitive geometry prim in the asset as instanceable, the mesh prim requires a parent Xform prim to be present, which will be used to add a reference to a master USD file containing definition of the mesh prim.
For example, the following definition:
```
World
|_ Robot
|_ Collisions
|_ Sphere
|_ Box
```
would have to be modified to:
```
World
|_ Robot
|_ Collisions
|_ Sphere_Xform
| |_ Sphere
|_ Box_Xform
|_ Box
```
Any references that exist on the original `Sphere` and `Box` prims would have to be moved to `Sphere_Xform` and `Box_Xform` prims.
To help with the process of creating new parent prims, we provide a utility method `create_parent_xforms()` in `omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py` to automatically insert a new Xform prim as a parent of every mesh prim in the stage. This method can be run on an existing non-instanced USD file for an asset from the script editor:
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import create_parent_xforms
create_parent_xforms(
asset_usd_path=ASSET_USD_PATH,
source_prim_path=SOURCE_PRIM_PATH,
save_as_path=SAVE_AS_PATH
)
```
This method can also be run as part of `convert_asset_instanceable()` method, by passing in the argument `create_xforms=True`.
It is also worth noting that once an instanced asset is added to the stage, we can no longer modify USD attributes on the instanceable prims. For example, to modify attributes of collision meshes that are set as instanceable, we have to first modify the attributes on the corresponding prims in the master prim which our instanced asset references from. Then, we can allow the instanced asset to pick up the updated values from the master prim. | 6,846 | Markdown | 56.058333 | 444 | 0.76804 |
elharirymatteo/RANS/docs/framework/reproducibility.md | Reproducibility and Determinism
===============================
Seeds
-----
To achieve deterministic behavior on multiple training runs, a seed
value can be set in the training config file for each task. This will potentially
allow for individual runs of the same task to be deterministic when
executed on the same machine and system setup. Alternatively, a seed can
also be set via command line argument `seed=<seed>` to override any
settings in config files. If no seed is specified in either config files
or command line arguments, we default to generating a random seed. In
this case, individual runs of the same task should not be expected to be
deterministic. For convenience, we also support setting `seed=-1` to
generate a random seed, which will override any seed values set in
config files. By default, we have explicitly set all seed values in
config files to be 42.
PyTorch Deterministic Training
------------------------------
We also include a `torch_deterministic` argument for use when running RL
training. Enabling this flag (by passing `torch_deterministic=True`) will
apply additional settings to PyTorch that can force the usage of deterministic
algorithms in PyTorch, but may also negatively impact runtime performance.
For more details regarding PyTorch reproducibility, refer to
<https://pytorch.org/docs/stable/notes/randomness.html>. If both
`torch_deterministic=True` and `seed=-1` are set, the seed value will be
fixed to 42.
Runtime Simulation Changes / Domain Randomization
-------------------------------------------------
Note that using a fixed seed value will only **potentially** allow for deterministic
behavior. Due to GPU work scheduling, it is possible that runtime changes to
simulation parameters can alter the order in which operations take place, as
environment updates can happen while the GPU is doing other work. Because of the nature
of floating point numeric storage, any alteration of execution ordering can
cause small changes in the least significant bits of output data, leading
to divergent execution over the simulation of thousands of environments and
simulation frames.
As an example of this, runtime domain randomization of object scales
is known to cause both determinancy and simulation issues when running on the GPU
due to the way those parameters are passed from CPU to GPU in lower level APIs. Therefore,
this is only supported at setup time before starting simulation, which is specified by
the `on_startup` condition for Domain Randomization.
At this time, we do not believe that other domain randomizations offered by this
framework cause issues with deterministic execution when running GPU simulation,
but directly manipulating other simulation parameters outside of the omni.isaac.core View
APIs may induce similar issues.
Also due to floating point precision, states across different environments in the simulation
may be non-deterministic when the same set of actions are applied to the same initial
states. This occurs as environments are placed further apart from the world origin at (0, 0, 0).
As actors get placed at different origins in the world, floating point errors may build up
and result in slight variance in results even when starting from the same initial states. One
possible workaround for this issue is to place all actors/environments at the world origin
at (0, 0, 0) and filter out collisions between the environments. Note that this may induce
a performance degradation of around 15-50%, depending on the complexity of actors and
environment.
Another known cause of non-determinism is from resetting actors into contact states.
If actors within a scene is reset to a state where contacts are registered
between actors, the simulation may not be able to produce deterministic results.
This is because contacts are not recorded and will be re-computed from scratch for
each reset scenario where actors come into contact, which cannot guarantee
deterministic behavior across different computations.
| 4,017 | Markdown | 53.297297 | 96 | 0.787155 |
elharirymatteo/RANS/docs/framework/framework.md | ## RL Framework
### Overview
Our RL examples are built on top of Isaac Sim's RL framework provided in `omni.isaac.gym`. Tasks are implemented following `omni.isaac.core`'s Task structure. PPO training is performed using the [rl_games](https://github.com/Denys88/rl_games) library, but we provide the flexibility to use other RL libraries for training.
For a list of examples provided, refer to the
[RL List of Examples](../examples/rl_examples.md)
### Class Definition
The RL ecosystem can be viewed as three main pieces: the Task, the RL policy, and the Environment wrapper that provides an interface for communication between the task and the RL policy.
#### Task
The Task class is where main task logic is implemented, such as computing observations and rewards. This is where we can collect states of actors in the scene and apply controls or actions to our actors.
For convenience, we provide a base Task class, `RLTask`, which inherits from the `BaseTask` class in `omni.isaac.core`. This class is responsible for dealing with common configuration parsing, buffer initialization, and environment creation. Note that some config parameters and buffers in this class are specific to the rl_games library, and it is not necessary to inherit new tasks from `RLTask`.
A few key methods in `RLTask` include:
* `__init__(self, name: str, env: VecEnvBase, offset: np.ndarray = None)` - Parses config values common to all tasks and initializes action/observation spaces if not defined in the child class. Defines a GridCloner by default and creates a base USD scope for holding all environment prims. Can be called from child class.
* `set_up_scene(self, scene: Scene, replicate_physics=True, collision_filter_global_paths=[], filter_collisions=True)` - Adds ground plane and creates clones of environment 0 based on values specifid in config. Can be called from child class `set_up_scene()`.
* `pre_physics_step(self, actions: torch.Tensor)` - Takes in actions buffer from RL policy. Can be overriden by child class to process actions.
* `post_physics_step(self)` - Controls flow of RL data processing by triggering APIs to compute observations, retrieve states, compute rewards, resets, and extras. Will return observation, reward, reset, and extras buffers.
#### Environment Wrappers
As part of the RL framework in Isaac Sim, we have introduced environment wrapper classes in `omni.isaac.gym` for RL policies to communicate with simulation in Isaac Sim. This class provides a vectorized interface for common RL APIs used by `gym.Env` and can be easily extended towards RL libraries that require additional APIs. We show an example of this extension process in this repository, where we extend `VecEnvBase` as provided in `omni.isaac.gym` to include additional APIs required by the rl_games library.
Commonly used APIs provided by the base wrapper class `VecEnvBase` include:
* `render(self, mode: str = "human")` - renders the current frame
* `close(self)` - closes the simulator
* `seed(self, seed: int = -1)` - sets a seed. Use `-1` for a random seed.
* `step(self, actions: Union[np.ndarray, torch.Tensor])` - triggers task `pre_physics_step` with actions, steps simulation and renderer, computes observations, rewards, dones, and returns state buffers
* `reset(self)` - triggers task `reset()`, steps simulation, and re-computes observations
##### Multi-Threaded Environment Wrapper for Extension Workflows
`VecEnvBase` is a simple interface that’s designed to provide commonly used `gym.Env` APIs required by RL libraries. Users can create an instance of this class, attach your task to the interface, and provide your wrapper instance to the RL policy. Since the RL algorithm maintains the main loop of execution, interaction with the UI and environments in the scene can be limited and may interfere with the training loop.
We also provide another environment wrapper class called `VecEnvMT`, which is designed to isolate the RL policy in a new thread, separate from the main simulation and rendering thread. This class provides the same set of interface as `VecEnvBase`, but also provides threaded queues for sending and receiving actions and states between the RL policy and the task. In order to use this wrapper interface, users have to implement a `TrainerMT` class, which should implement a `run()` method that initiates the RL loop on a new thread. We show an example of this in OmniIsaacGymEnvs under `omniisaacgymenvs/utils/rlgames/rlgames_train_mt.py`. The setup for using `VecEnvMT` is more involved compared to the single-threaded `VecEnvBase` interface, but will allow users to have more control over starting and stopping the training loop through interaction with the UI.
Note that `VecEnvMT` has a timeout variable, which defaults to 90 seconds. If either the RL thread waiting for physics state exceeds the timeout amount or the simulation thread waiting for RL actions exceeds the timeout amount, the threaded queues will throw an exception and terminate training. For larger scenes that require longer simulation or training time, try increasing the timeout variable in `VecEnvMT` to prevent unnecessary timeouts. This can be done by passing in a `timeout` argument when calling `VecEnvMT.initialize()`.
This wrapper is currently only supported with the [extension workflow](extension_workflow.md).
### Creating New Examples
For simplicity, we will focus on using the single-threaded `VecEnvBase` interface in this tutorial.
To run any example, first make sure an instance of `VecEnvBase` or descendant of `VecEnvBase` is initialized.
This will be required as an argumet to our new Task. For example:
``` python
env = VecEnvBase(headless=False)
```
The headless parameter indicates whether a viewer should be created for visualizing results.
Then, create our task class, extending it from `RLTask`:
```python
class MyNewTask(RLTask):
def __init__(
self,
name: str, # name of the Task
sim_config: SimConfig, # SimConfig instance for parsing cfg
env: VecEnvBase, # env instance of VecEnvBase or inherited class
offset=None # transform offset in World
) -> None:
# parse configurations, set task-specific members
...
self._num_observations = 4
self._num_actions = 1
# call parent class’s __init__
RLTask.__init__(self, name, env)
```
The `__init__` method should take 4 arguments:
* `name`: a string for the name of the task (required by BaseTask)
* `sim_config`: an instance of `SimConfig` used for config parsing, can be `None`. This object is created in `omniisaacgymenvs/utils/task_utils.py`.
* `env`: an instance of `VecEnvBase` or an inherited class of `VecEnvBase`
* `offset`: any offset required to place the `Task` in `World` (required by `BaseTask`)
In the `__init__` method of `MyNewTask`, we can populate any task-specific parameters, such as dimension of observations and actions, and retrieve data from config dictionaries. Make sure to make a call to `RLTask`’s `__init__` at the end of the method to perform additional data initialization.
Next, we can implement the methods required by the RL framework. These methods follow APIs defined in `omni.isaac.core` `BaseTask` class. Below is an example of a simple implementation for each method.
```python
def set_up_scene(self, scene: Scene) -> None:
# implement environment setup here
add_prim_to_stage(my_robot) # add a robot actor to the stage
super().set_up_scene(scene) # pass scene to parent class - this method in RLTask also uses GridCloner to clone the robot and adds a ground plane if desired
self._my_robots = ArticulationView(...) # create a view of robots
scene.add(self._my_robots) # add view to scene for initialization
def post_reset(self):
# implement any logic required for simulation on-start here
pass
def pre_physics_step(self, actions: torch.Tensor) -> None:
# implement logic to be performed before physics steps
self.perform_reset()
self.apply_action(actions)
def get_observations(self) -> dict:
# implement logic to retrieve observation states
self.obs_buf = self.compute_observations()
def calculate_metrics(self) -> None:
# implement logic to compute rewards
self.rew_buf = self.compute_rewards()
def is_done(self) -> None:
# implement logic to update dones/reset buffer
self.reset_buf = self.compute_resets()
```
To launch the new example from one of our training scripts, add `MyNewTask` to `omniisaacgymenvs/utils/task_util.py`. In `initialize_task()`, add an import to the `MyNewTask` class and add an instance to the `task_map` dictionary to register it into the command line parsing.
To use the Hydra config parsing system, also add a task and train config files into `omniisaacgymenvs/cfg`. The config files should be named `cfg/task/MyNewTask.yaml` and `cfg/train/MyNewTaskPPO.yaml`.
Finally, we can launch `MyNewTask` with:
```bash
PYTHON_PATH random_policy.py task=MyNewTask
```
### Using a New RL Library
In this repository, we provide an example of extending Isaac Sim's environment wrapper classes to work with the rl_games library, which can be found at `omniisaacgymenvs/envs/vec_env_rlgames.py` and `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`.
The first script, `omniisaacgymenvs/envs/vec_env_rlgames.py`, extends from `VecEnvBase`.
```python
from omni.isaac.gym.vec_env import VecEnvBase
class VecEnvRLGames(VecEnvBase):
```
One of the features in rl_games is the support for asymmetrical actor-critic policies, which requires a `states` buffer in addition to the `observations` buffer. Thus, we have overriden a few of the class in `VecEnvBase` to incorporate this requirement.
```python
def set_task(
self, task, backend="numpy", sim_params=None, init_sim=True
) -> None:
super().set_task(task, backend, sim_params, init_sim) # class VecEnvBase's set_task to register task to the environment instance
# special variables required by rl_games
self.num_states = self._task.num_states
self.state_space = self._task.state_space
def step(self, actions):
# we clamp the actions so that values are within a defined range
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone()
# pass actions buffer to task for processing
self._task.pre_physics_step(actions)
# allow users to specify the control frequency through config
for _ in range(self._task.control_frequency_inv):
self._world.step(render=self._render)
self.sim_frame_count += 1
# compute new buffers
self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step()
self._states = self._task.get_states() # special buffer required by rl_games
# return buffers in format required by rl_games
obs_dict = {"obs": self._obs, "states": self._states}
return obs_dict, self._rew, self._resets, self._extras
```
Similarly, we also have a multi-threaded version of the rl_games environment wrapper implementation, `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. This class extends from `VecEnvMT` and `VecEnvRLGames`:
```python
from omni.isaac.gym.vec_env import VecEnvMT
from .vec_env_rlgames import VecEnvRLGames
class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT):
```
In this class, we also have a special method `_parse_data(self, data)`, which is required to be implemented to parse dictionary values passed through queues. Since multiple buffers of data are required by the RL policy, we concatenate all of the buffers in a single dictionary, and send that to the queue to be received by the RL thread.
```python
def _parse_data(self, data):
self._obs = torch.clamp(data["obs"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._rew = data["rew"].to(self._task.rl_device).clone()
self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = data["reset"].to(self._task.rl_device).clone()
self._extras = data["extras"].copy()
```
| 12,172 | Markdown | 60.791878 | 862 | 0.747453 |
elharirymatteo/RANS/docs/framework/limitations.md | ### API Limitations
#### omni.isaac.core Setter APIs
Setter APIs in omni.isaac.core for ArticulationView, RigidPrimView, and RigidContactView should only be called once per simulation step for
each view instance per API. This means that for use cases where multiple calls to the same setter API from the same view instance is required,
users will need to cache the states to be set for intermmediate calls, and make only one call to the setter API prior to stepping physics with
the complete buffer containing all cached states.
If multiple calls to the same setter API from the same view object are made within the simulation step,
subsequent calls will override the states that have been set by prior calls to the same API,
voiding the previous calls to the API. The API can be called again once a simulation step is made.
For example, the below code will override states.
```python
my_view.set_world_poses(positions=[[0, 0, 1]], orientations=[[1, 0, 0, 0]], indices=[0])
# this call will void the previous call
my_view.set_world_poses(positions=[[0, 1, 1]], orientations=[[1, 0, 0, 0]], indices=[1])
my_world.step()
```
Instead, the below code should be used.
```python
my_view.set_world_poses(positions=[[0, 0, 1], [0, 1, 1]], orientations=[[1, 0, 0, 0], [1, 0, 0, 0]], indices=[0, 1])
my_world.step()
```
#### omni.isaac.core Getter APIs
Getter APIs for cloth simulation may return stale states when used with the GPU pipeline. This is because the physics simulation requires a simulation step
to occur in order to refresh the GPU buffers with new states. Therefore, when a getter API is called after a setter API before a
simulation step, the states returned from the getter API may not reflect the values that were set using the setter API.
For example:
```python
my_view.set_world_positions(positions=[[0, 0, 1]], indices=[0])
# Values may be stale when called before step
positions = my_view.get_world_positions() # positions may not match [[0, 0, 1]]
my_world.step()
# Values will be updated when called after step
positions = my_view.get_world_positions() # positions will reflect the new states
```
#### Performing Resets
When resetting the states of actors, impulses generated by previous target or effort controls
will continue to be carried over from the previous states in simulation.
Therefore, depending on the time step, the masses of the objects, and the magnitude of the impulses,
the difference between the desired reset state and the observed first state after reset can be large.
To eliminate this issue, users should also reset any position/velocity targets or effort controllers
to the reset state or zero state when resetting actor states. For setting joint positions and velocities
using the omni.isaac.core ArticulationView APIs, position targets and velocity targets will
automatically be set to the same states as joint positions and velocities.
#### Massless Links
It may be helpful in some scenarios to introduce dummy bodies into articulations for
retrieving transformations at certain locations of the articulation. Although it is possible
to introduce rigid bodies with no mass and colliders APIs and attach them to the articulation
with fixed joints, this can sometimes cause physics instabilities in simulation. To prevent
instabilities from occurring, it is recommended to add a dummy geometry to the rigid body
and include both Mass and Collision APIs. The mass of the geometry can be set to a very
small value, such as 0.0001, to avoid modifying physical behaviors of the articulation.
Similarly, we can also disable collision on the Collision API of the geometry to preserve
contact behavior of the articulation. | 3,685 | Markdown | 52.420289 | 155 | 0.775577 |
AnyoneClown/omniverse-scene-modifier/README.md | # Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "sensor" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 2,030 | Markdown | 37.320754 | 258 | 0.75665 |
AnyoneClown/omniverse-scene-modifier/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
AnyoneClown/omniverse-scene-modifier/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
AnyoneClown/omniverse-scene-modifier/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# 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 logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/extension.py | import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None | 915 | Python | 34.230768 | 119 | 0.679781 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/viewport_scene.py | from omni.ui import scene as sc
import omni.ui as ui
from .sensor_info_manipulator import ObjInfoManipulator
from .sensor_info_model import ObjInfoModel
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
# Create a unique frame for our SceneView
with self.viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self.scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self.scene_view.scene:
ObjInfoManipulator(model=ObjInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
# Empty the SceneView of any elements it may have
self.scene_view.scene.clear()
# un-register the SceneView from Viewport updates
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
# Remove our references to these objects
self.viewport_window = None
self.scene_view = None
| 1,431 | Python | 37.702702 | 89 | 0.649895 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/sensor_info_model.py | from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe() | 4,113 | Python | 34.465517 | 111 | 0.598347 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/sensor_info_manipulator.py | from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
| 1,164 | Python | 33.264705 | 141 | 0.648625 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/sensor/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import sensor
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = sensor.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,648 | Python | 34.085106 | 142 | 0.679612 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "sensor"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import sensor".
[[python.module]]
name = "sensor"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,544 | TOML | 31.187499 | 118 | 0.742876 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/docs/README.md | # Python Extension Example [sensor]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 165 | Markdown | 32.199994 | 126 | 0.781818 |
AnyoneClown/omniverse-scene-modifier/exts/sensor/docs/index.rst | sensor
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"sensor"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 313 | reStructuredText | 13.95238 | 43 | 0.600639 |
williamjsmith15/OmniFlow/docker-compose-openmc.yml | version: "3.9"
services:
openmc:
build:
context: .
dockerfile: OpenMC/Dockerfile
volumes:
- ../OmniFlow/:/OmniFlow/
- /tmp/:/tmp/
tty: true
stdin_open: true
# docker compose -f "docker-compose-openmc.yml" build
# docker compose -f "docker-compose-openmc.yml" up | 307 | YAML | 17.117646 | 53 | 0.615635 |
williamjsmith15/OmniFlow/Install_Win_wip.md |
# Setup
## Environment Setup
Download and install [WSL2](https://learn.microsoft.com/en-us/windows/wsl/install) and follow all the instructions given by microsoft. The default installation options here are fine (system tested running with an Ubuntu distro install)
Download and install [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/), follow the instalation steps and set up docker with the WSL 2 install in the previous step.
Can verify the version and installation of both of these running these commands in PowerShell or the Command Prompt:
``
wsl -l -v
docker version
``
Next, on wsl, install cwltool and the toil-cwl-runner, fist update the installer:
```
sudo apt-get update
```
followed by
```
sudo apt-get install cwltool
sudo apt-get install python3-pip
pip install toil[cwl]
```
both of the workflow runners can be tested later when the repository is cloned on the test OpenMC cases.
To save time later when running the Monte Carlo solver, the Docker image for this can be downloaded now by running
```
docker run -it williamjsmith15/omniflow-openmc:latest
```
and then when the image is installed and running, in the command line run
```
python
import openmc
```
if this throws no errors then the container has been downloaded and the packages inside set up correctly. This can now be exited by running:
```
exit()
exit
```
For visualisation, ParaView is the viewer of choice and comes with a connector that can be installed to allow operation with Omniverse. Paraview can be downloaded from [here](paraview.org/download/). ParaView versions 5.9, 5.10 and 5.11 are all currently supported by Omniverse.
Finally, download and install [NVIDIA Omniverse](https://www.nvidia.com/en-sg/omniverse/download/). The extension should work in most apps but to start, Omniverse create is reccommended.
## Extension Download & Testing
Clone the repository with
```
git clone https://github.com/williamjsmith15/OmniFlow
```
After cloning test that all the environments are working so far, this can be done from the main OmniFlow directory with the following commands:
```
python test/cwltool_test.py [CREATE THESE TEST MODULES]
python test/toil_test.py
```
verify that there are no errors in the terminal output and see that the output files are correctly saved in the folders /test/cwltool/toy/ /test/cwltool/simple/ /test/toil/toy/ /test/toil/simple/ and the vtk files in the simple tests can both be opened in ParaView to visually test and to check correct install of ParaView [SCREENSHOTS]
## Connect Extension to Omniverse
Open -> Extension Manager -> blah balh blah
TODO:
Screenshots for everything
Create test modules
Create a win and linux file to autoinstall most things | 2,732 | Markdown | 38.042857 | 336 | 0.777452 |
williamjsmith15/OmniFlow/docker-compose-toil.yml | version: "3.9"
services:
toil:
build:
context: .
dockerfile: ToilRunner/Dockerfile
volumes:
- ../OmniFlow/:/OmniFlow/
- /tmp/:/tmp/
tty: true
stdin_open: true
# docker compose -f "docker-compose-toil.yml" build
# docker compose -f "docker-compose-toil.yml" up | 305 | YAML | 16.999999 | 51 | 0.613115 |
williamjsmith15/OmniFlow/README.md | # OmniFlow
NVIDIA Omniverse Simulation Integration System
To start the docker container:
First time only to build - docker compose -f "docker-compose-toil.yml" build
Every time after to launch - docker compose -f "docker-compose-toil.yml" up
Set the paths to the individual extensions in Omniverse, for example in the case of OpenMC:
Launch the Omniverse app, go window > extensions > settings and add the <installation-folder>/OmniFlow/OpenMC/omni-kit-extension/exts/ folder to the filepaths
Back onto the extensions manager search for the extension name (or there is a button to filter for just 3rd Party Exts) and find the extension
Click on the toggle switch to launch the extenion (and can select to autoload so next time it will already be loaded on lauch)
To Install:
pip install docker
pip install cwltool
pip install toil
sudo apt install git
sudo apt install python3-pip
sudo apt install libfuse2 # For omni - needs it
git clone https://github.com/williamjsmith15/OmniFlow
should point omni to ext path
get onto correct branch (feature branch) | 1,083 | Markdown | 44.166665 | 162 | 0.78024 |
williamjsmith15/OmniFlow/OpenMC/README.md | # MScDIssertation
Colleciton of Files and Scripts that contain the work performed for a MSc Strucutral Engineering dissertation
Extra Dependencies:
pip install cwltool
For OpenMC Conda Env:
conda create <env_name> # Create the new conda environment to install into
conda activate <env_name> # Activate the environment
conda install -c conda-forge mamba # Install the package manager mamba
mabma install openmc # Install OpenMC and all its dependencies through mamba
To run:
cwltool, needs argument --no-pass-user when using the openMC docker container as this means the CWL tool can access the root user and not userID 1000:
cwl-runner --no-match-user workflows/openmc_workflow.cwl workflows/script_loc.yml # Can also use toil-cwl-runner insteaed
docker container normally:
docker run -it -v <parent_folder>/MScDIssertation/:/home/MScDissertation/ openmc/openmc:develop-dagmc-libmesh # Links the git repo folder to folder /home/MScDissertation on the Docker container
To install extension into Omniverse:
Launch app, go window > extensions > settings and add the <parent_folder>/omni-kit-extension/exts fiel to the filepaths
Back onto teh extensions manager search fro OpenMC and it should be the only result
Click on the toggle switch (and can select to autoload so next time it will already be loaded on lauch)
| 1,394 | Markdown | 59.652171 | 198 | 0.761119 |
williamjsmith15/OmniFlow/OpenMC/tools/dagmc_material_name/extract_mats.py | # Short python script to obtain materials from a list given by MOAB using mbsize command
import os
sep = os.sep
path_py = os.path.realpath(__file__)
list_path = ''
if "MScDIssertation" in path_py:
cwl_folder = path_py.split(f"{sep}MScDIssertation", 1)[0]
elif "cwl" in path_py:
cwl_folder = path_py.split(f"{sep}cwl", 1)[0]
for root, dirs, files in os.walk(cwl_folder):
for file in files:
if file.endswith("mat_list.txt"):
list_path = os.path.join(root, file)
mats = []
check_str = 'NAME = mat:'
with open(list_path) as old, open('materials.txt', 'w') as new:
for line in old: # Loop through lines in old txt
if check_str in line: # check against check string
if not any(material in line for material in mats): # check against existing materials
new.write(line.replace('NAME = mat:', ''))
| 869 | Python | 28.999999 | 97 | 0.642117 |
williamjsmith15/OmniFlow/OpenMC/tools/dagmc_material_name/dagmc_materials.yml | usd_CAD:
class: File
path: ../../output/omni/dagmc.usd
extract_script:
class: File
path: extract_mats.py
usd_h5m_script:
class: File
path: ../file_converters/usd_h5m.py
settings:
class: File
path: ../../output/omni/settings.txt | 243 | YAML | 19.333332 | 38 | 0.679012 |
williamjsmith15/OmniFlow/OpenMC/tools/main/script_loc.yml | script:
class: File
path: general_CAD.py
str: dagmc.vtk
usd_CAD:
class: File
path: ../../output/omni/dagmc.usd
settings:
class: File
path: ../../output/omni/settings.txt
usd_h5m_script:
class: File
path: ../file_converters/usd_h5m.py
# Test running:
# cwltool --outdir /home/williamjsmith15/PhD/OmniFlow/TEST/Test_USD/output /home/williamjsmith15/PhD/OmniFlow/OpenMC/tools/file_converters/usd_h5m_convert.cwl /home/williamjsmith15/PhD/OmniFlow/OpenMC/tools/file_converters/usd_h5m_convert.yml
# cwltool --no-match-user --outdir /home/williamjsmith15/PhD/OmniFlow/TEST/Test_USD/output/ /home/williamjsmith15/PhD/OmniFlow/OpenMC/tools/main/openmc_workflow.cwl /home/williamjsmith15/PhD/OmniFlow/OpenMC/tools/main/script_loc.yml | 751 | YAML | 40.777776 | 244 | 0.76032 |
williamjsmith15/OmniFlow/OpenMC/tools/main/general_CAD.py | # Steps for this workflow:
# CAD through cubit and then into h5m format (throuigh mb convert)
# Cubit adds materials etc etc
# Run send CAD file along with this script into the DOCKER container
import openmc
import os
import math
import openmc_plasma_source as ops
import numpy as np
# Find the settings file
sep = os.sep
path_py = os.path.realpath(__file__)
settings_path = ''
geometry_path = ''
# Find parent folder path
if "MScDIssertation" in path_py:
cwl_folder = path_py.split(f"{sep}MScDIssertation", 1)[0]
elif "cwl" in path_py:
cwl_folder = path_py.split(f"{sep}cwl", 1)[0]
# Find settings and dagmc files
for root, dirs, files in os.walk(cwl_folder):
for file in files:
if file.endswith("settings.txt"):
settings_path = os.path.join(root, file)
if file.endswith("dagmc.h5m"):
geometry_path = os.path.join(root, file)
# Get all settings out
materials_input = []
sources_input = []
settings_input = []
ex_settings = []
position = 0
with open(settings_path) as f:
for line in f:
if position == 0:
if "MATERIALS" in line:
position = 1
elif position == 1:
if "SOURCES" in line:
position = 2
else:
materials_input.append(line.split())
elif position == 2:
if "SETTINGS" in line:
position = 3
else:
sources_input.append(line.split())
elif position == 3:
if "EXT_SETTINGS" in line:
position = 4
else:
settings_input.append(line.split())
elif position == 4:
ex_settings.append(line.split())
##################
# DEFINE MATERIALS
##################
tmp_material_array = []
# Temp for testing
# for material in materials_input:
# tmp_material = openmc.Material(name = material[0])
# tmp_material.add_element('Fe', 1, 'ao')
# tmp_material.set_density("g/cm3", 7.7)
# tmp_material_array.append(tmp_material)
for material in materials_input:
tmp_material = openmc.Material(name = material[0])
tmp_material.add_element(material[1], 1, "ao")
tmp_material.set_density("g/cm3", float(material[2]))
tmp_material_array.append(tmp_material)
materials = openmc.Materials(tmp_material_array)
materials.export_to_xml()
##################
# DEFINE GEOMETRY
##################
# Hack to handle the boundaires for the geometry (for now) - future look at how to handle this
# Took from the paramak examples https://github.com/fusion-energy/magnetic_fusion_openmc_dagmc_paramak_example/blob/main/2_run_openmc_dagmc_simulation.py
dagmc_univ = openmc.DAGMCUniverse(filename=geometry_path)
# geometry = openmc.Geometry(root=dagmc_univ)
# geometry.export_to_xml()
# creates an edge of universe boundary surface
vac_surf = openmc.Sphere(r=1000, surface_id=9999, boundary_type="vacuum") # Normally like 100000
# lead_surf = -openmc.Sphere(r=60000) & + openmc.Sphere(r=50000)
# lead = openmc.Material(name='lead')
# lead.set_density('g/cc', 11.4)
# lead.add_element('Pb', 1)
# lead_cell = openmc.Cell(fill=lead, region=lead_surf)
# adds reflective surface for the sector model at 0 degrees
reflective_1 = openmc.Plane(
a=math.sin(0),
b=-math.cos(0),
c=0.0,
d=0.0,
surface_id=9991,
boundary_type="reflective",
)
# adds reflective surface for the sector model at 90 degrees
reflective_2 = openmc.Plane(
a=math.sin(math.radians(90)),
b=-math.cos(math.radians(90)),
c=0.0,
d=0.0,
surface_id=9990,
boundary_type="reflective",
)
# specifies the region as below the universe boundary and inside the reflective surfaces
region = -vac_surf # & -reflective_1 & +reflective_2 DEBUGGING
# creates a cell from the region and fills the cell with the dagmc geometry
containing_cell = openmc.Cell(cell_id=9999, region=region, fill=dagmc_univ)
geometry = openmc.Geometry(root=[containing_cell])
geometry.export_to_xml()
##################
# DEFINE SETTINGS
##################
settings = openmc.Settings()
source_type = ''
for ex_setting in ex_settings:
if ex_setting[0] == "source_type":
source_type = " ".join(ex_setting[1:])
else:
print(f"Don't know what to do with {ex_setting}")
# Sources
sources = []
angle_conversion = (2*np.pi)/360
if source_type == 'Point Source': # If a point source
for source in sources_input:
source_pnt = openmc.stats.Point(xyz=(float(source[1]), float(source[2]), float(source[3])))
source = openmc.Source(space=source_pnt, energy=openmc.stats.Discrete(x=[float(source[0]),], p=[1.0,]))
sources.append(source)
source_str = 1.0 / len(sources)
for source in sources:
source.strength = source_str
elif source_type == 'Fusion Point Source':
for source in sources_input:
source_single = ops.FusionPointSource(
)
sources.append(source_single)
elif source_type == 'Fusion Ring Source':
for source in sources_input:
source_single = ops.FusionRingSource(
angles = (float(source[2])*angle_conversion, float(source[3])*angle_conversion),
radius = float(source[0]),
temperature = float(source[4]),
fuel = str(source[1]),
z_placement = float(source[5])
)
sources.append(source_single)
elif source_type == 'Tokamak Source':
for source in sources_input:
source_single = ops.TokamakSource(
).make_openmc_sources()
sources.append(source_single)
else:
print(f'I dont know what to do with {source_type}')
settings.source = sources
# Settings
for setting in settings_input:
try:
if setting[0] == "batches": # Apparently the version of python being used is not new enough for swtich statements... :(
settings.batches = int(setting[1])
elif setting[0] == "particles":
settings.particles = int(setting[1])
elif setting[0] == "run_mode":
settings.run_mode = str(" ".join(setting[1:]))
else:
print(f"Setting: {setting} did not match one of the expected cases.")
except:
print(f"There was an error with setting {setting} somewhere...")
settings.export_to_xml()
openmc.run(tracks=True) # Run in tracking mode for visualisation of tracks through CAD
| 6,382 | Python | 31.902062 | 153 | 0.632404 |
williamjsmith15/OmniFlow/OpenMC/tools/tests/simple/simple_CAD.py | #From https://nbviewer.org/github/openmc-dev/openmc-notebooks/blob/main/cad-based-geometry.ipynb
import urllib.request
import openmc
from matplotlib import pyplot as plt
##################
# DEFINE MATERIALS
##################
water = openmc.Material(name="water")
water.add_nuclide('H1', 2.0, 'ao')
water.add_nuclide('O16', 1.0, 'ao')
water.set_density('g/cc', 1.0)
#water.add_s_alpha_beta('c_H_in_H2O') Have to remove due to issue in new docker container - see OmniFlow doc 03/01/23
water.id = 41
iron = openmc.Material(name="iron")
iron.add_nuclide("Fe54", 0.0564555822608)
iron.add_nuclide("Fe56", 0.919015287728)
iron.add_nuclide("Fe57", 0.0216036861685)
iron.add_nuclide("Fe58", 0.00292544384231)
iron.set_density("g/cm3", 7.874)
mats = openmc.Materials([iron, water])
mats.export_to_xml()
##################
# DEFINE GEOMETRY
##################
teapot_url = 'https://tinyurl.com/y4mcmc3u' # 29 MB
def download(url):
"""
Helper function for retrieving dagmc models
"""
u = urllib.request.urlopen(url)
if u.status != 200:
raise RuntimeError("Failed to download file.")
# save file as dagmc.h5m
with open("dagmc.h5m", 'wb') as f:
f.write(u.read())
download(teapot_url)
dagmc_univ = openmc.DAGMCUniverse(filename="dagmc.h5m")
geometry = openmc.Geometry(root=dagmc_univ)
geometry.export_to_xml()
##################
# DEFINE SETTINGS
##################
settings = openmc.Settings()
settings.batches = 10
settings.particles = 5000
settings.run_mode = "fixed source"
src_locations = ((-4.0, 0.0, -2.0),
( 4.0, 0.0, -2.0),
( 4.0, 0.0, -6.0),
(-4.0, 0.0, -6.0),
(10.0, 0.0, -4.0),
(-8.0, 0.0, -4.0))
# we'll use the same energy for each source
src_e = openmc.stats.Discrete(x=[12.0,], p=[1.0,])
# create source for each location
sources = []
for loc in src_locations:
src_pnt = openmc.stats.Point(xyz=loc)
src = openmc.Source(space=src_pnt, energy=src_e)
sources.append(src)
src_str = 1.0 / len(sources)
for source in sources:
source.strength = src_str
settings.source = sources
settings.export_to_xml()
mesh = openmc.RegularMesh()
mesh.dimension = (120, 1, 40)
mesh.lower_left = (-20.0, 0.0, -10.0)
mesh.upper_right = (20.0, 1.0, 4.0)
mesh_filter = openmc.MeshFilter(mesh)
pot_filter = openmc.CellFilter([1])
pot_tally = openmc.Tally()
pot_tally.filters = [mesh_filter, pot_filter]
pot_tally.scores = ['flux']
water_filter = openmc.CellFilter([5])
water_tally = openmc.Tally()
water_tally.filters = [mesh_filter, water_filter]
water_tally.scores = ['flux']
tallies = openmc.Tallies([pot_tally, water_tally])
tallies.export_to_xml()
openmc.run(tracks=True) # Run in tracking mode for visualisation of tracks through CAD
##################
# PLOTTING
##################
sp = openmc.StatePoint("statepoint.10.h5")
water_tally = sp.get_tally(scores=['flux'], id=water_tally.id)
water_flux = water_tally.mean
water_flux.shape = (40, 120)
water_flux = water_flux[::-1, :]
pot_tally = sp.get_tally(scores=['flux'], id=pot_tally.id)
pot_flux = pot_tally.mean
pot_flux.shape = (40, 120)
pot_flux = pot_flux[::-1, :]
del sp
p = openmc.Plot()
p.basis = 'xz'
p.origin = (0.0, 0.0, 0.0)
p.width = (30.0, 20.0)
p.pixels = (450, 300)
p.color_by = 'material'
p.colors = {iron: 'gray', water: 'blue'}
openmc.plot_inline(p)
plt.savefig('Plot_1.png')
plt.clf()
fig = plt.figure(figsize=(18, 16))
sub_plot1 = plt.subplot(121, title="Kettle Flux")
sub_plot1.imshow(pot_flux)
sub_plot2 = plt.subplot(122, title="Water Flux")
sub_plot2.imshow(water_flux)
plt.savefig('Flux.png')
plt.clf()
| 3,690 | Python | 19.853107 | 117 | 0.630352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.