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
|
---|---|---|---|---|---|---|
williamjsmith15/OmniFlow/OpenMC/tools/tests/toy/toy.py | # From https://nbviewer.org/github/openmc-dev/openmc-notebooks/blob/main/pincell.ipynb
# An OpenMC python script that runs a toy problem example
import openmc
import matplotlib.pyplot as plt # Extra to save plots produced in the process
import openmc_data_downloader as odd # Removes need to have the --no-match-user in the CWL call, this downloads the data files needed for the neutronics code automatically
import os
# #Set cross sections XML path
# os.environ["OPENMC_CROSS_SECTIONS"] = str('/home/nndc_hdf5/cross_sections.xml')
####################
# DEFINING MATERIALS
####################
# Uranium Dioxide Fuel
uo2 = openmc.Material(name="uo2") # Create material variable with name uo2
uo2.add_nuclide('U235', 0.03) # Add nuclides to material
uo2.add_nuclide('U238', 0.97)
uo2.add_nuclide('O16', 2.0)
uo2.set_density('g/cm3', 10.0) # Set density of material
# Zirchonium Casing
zirconium = openmc.Material(name="zirconium")
zirconium.add_element('Zr', 1.0) # Use of add element as elemental material
zirconium.set_density('g/cm3', 6.6)
# Water Coolant
water = openmc.Material(name="h2o") # Same process as uo2
water.add_nuclide('H1', 2.0)
water.add_nuclide('O16', 1.0)
water.set_density('g/cm3', 1.0)
# water.add_s_alpha_beta('c_H_in_H2O') # So bound-atom cross section is used as thermal energies rather than free-atom
mats = openmc.Materials([uo2, zirconium, water]) # Add all materials to a group of materials
# odd.just_in_time_library_generator(
# libraries = 'ENDFB-7.1-NNDC',
# materials = mats
# )
# os.environ["OPENMC_CROSS_SECTIONS"] = str('/home/nndc_hdf5/cross_sections.xml')
mats.export_to_xml() # Export the material data to a .xml file that the solver will use later on
os.system('cat materials.xml')
####################
# DEFINING GEOMETRY
####################
# Set cylinders to define regions and then define regions from those cylinders
fuel_outer_radius = openmc.ZCylinder(r=0.39)
clad_inner_radius = openmc.ZCylinder(r=0.40)
clad_outer_radius = openmc.ZCylinder(r=0.46)
fuel_region = -fuel_outer_radius
gap_region = +fuel_outer_radius & -clad_inner_radius
clad_region = +clad_inner_radius & -clad_outer_radius
# Assign matreials and regions to cells
fuel = openmc.Cell(name='fuel')
fuel.fill = uo2
fuel.region = fuel_region
gap = openmc.Cell(name='air gap')
gap.region = gap_region
clad = openmc.Cell(name='clad')
clad.fill = zirconium
clad.region = clad_region
# Create a box around the cylinders and fill with water as coolant
pitch = 1.26
box = openmc.rectangular_prism(width=pitch, height=pitch, boundary_type='reflective')
water_region = box & +clad_outer_radius
moderator = openmc.Cell(name='moderator')
moderator.fill = water
moderator.region = water_region
# Add all cells to the overall universe and again push to .xml for use by the solver
root_universe = openmc.Universe(cells=(fuel, gap, clad, moderator))
geometry = openmc.Geometry(root_universe)
geometry.export_to_xml()
####################
# DEFINING SETTINGS
####################
# Create a point source
point = openmc.stats.Point((0, 0, 0))
source = openmc.Source(space=point)
# Set settings
settings = openmc.Settings()
settings.source = source
settings.batches = 100
settings.inactive = 10
settings.particles = 1000
# Push settings to .xml for solver
settings.export_to_xml()
####################
# DEFINING TALLIES
####################
cell_filter = openmc.CellFilter(fuel) # What space the tallies take place in
tally = openmc.Tally(1)
tally.filters = [cell_filter]
# Tell tally what to collect info on
tally.nuclides = ['U235']
tally.scores = ['total', 'fission', 'absorption', '(n,gamma)']
# Export to .xml for solver
tallies = openmc.Tallies([tally])
tallies.export_to_xml()
####################
# RUN
####################
openmc.run(tracks=True) # Run in tracking mode for visualisation of tracks through CAD
# Plot geometries
plot = openmc.Plot()
plot.filename = 'pinplot'
plot.width = (pitch, pitch)
plot.pixels = (200, 200)
plot.color_by = 'material'
plot.colors = {uo2: 'yellow', water: 'blue'}
plots = openmc.Plots([plot])
plots.export_to_xml()
openmc.plot_geometry()
| 4,142 | Python | 26.805369 | 174 | 0.697006 |
williamjsmith15/OmniFlow/OpenMC/tools/file_converters/vtk_obj.py | # Convert vtk to obj file format
# Credit: https://github.com/lodeguns/VTK-OBJ/blob/master/vtk_to_obj_converter.py
import pyvista as pv
import os
from pyvista import examples
# System separator
sep = os.sep
this_path = os.path.realpath(__file__)
parent_folder = this_path.split(f"{sep}file_convertors", 1)[0]
paths = {
"input" : f"{parent_folder}{sep}test_output",
"output" : f"{parent_folder}{sep}test_output"
}
def convert(indir, outdir) :
files = os.listdir(indir)
files = [ os.path.join(indir,f) for f in files if f.endswith('.vtk') ]
for f in files:
mesh = pv.read(f)
basename = os.path.basename(f)
print("Copying file:", basename)
basename = os.path.splitext(basename)[0]
print("File name:", basename)
othermesh = examples.load_uniform()
legend_entries = []
legend_entries.append(['Liver converted', 'w'])
legend_entries.append(['External marker', 'k'])
plotter = pv.Plotter()
_ = plotter.add_mesh(mesh)
_ = plotter.add_mesh(othermesh, 'k')
_ = plotter.add_legend(legend_entries)
_ = plotter.export_obj(outdir+"conv_"+basename+".obj")
plotter.export_obj(f"{basename}.obj")
convert(paths['input'], paths['output']) | 1,269 | Python | 30.749999 | 81 | 0.627266 |
williamjsmith15/OmniFlow/OpenMC/tools/file_converters/usd_h5m_convert.yml | usd_h5m_script:
class: File
path: usd_h5m.py
usd_CAD:
class: File
path: ../../output/omni/dagmc.usd # Need to reset this to where the usd file will output to
# path: ../../../TEST/Test_USD/Test_4_DonutOnCube.usd
# 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 | 487 | YAML | 47.799995 | 244 | 0.741273 |
williamjsmith15/OmniFlow/OpenMC/tools/file_converters/usd_h5m.py | from typing import Iterable
from pxr import Usd, UsdShade
from vertices_to_h5m import vertices_to_h5m
import numpy as np
import os, tempfile
sep = os.sep # System separator
ext_path = os.path.realpath(__file__) # File path of ext
parent_folder = ext_path.split(f"{sep}omni-kit", 1)[0] # File path of parent folder to extension
tmp = tempfile.gettempdir()
path_py = os.path.realpath(__file__)
# Name of file changeable for ease of testing... default should be 'dagmc.usd'
fname_root = 'dagmc' # Default
# fname_root = 'Test_1_Bucket' # TESTING
# fname_root = 'Test_2_MilkJug' # TESTING
# fname_root = 'Test_3_RubixCube' # TESTING
# fname_root = 'Test_4_DonutOnCube' # TESTING
# Grab the filepath of the usd file
def find_files(filename): # TODO: find a better way to search for this rather than search from root (lazy implementation)
search_path = os.path.abspath("/")
result = []
# Walking top-down from the root
for root, dir, files in os.walk(search_path):
if filename in files:
result.append(os.path.join(root, filename))
return result
# USD Helper Functions
def getValidProperty (primative, parameterName):
# Get param
prop = primative.GetProperty(parameterName)
# Test validity
if ( type(prop) == type(Usd.Attribute())): # is valid
return prop.Get()
else: # is not
print("Requested parameter is not valid!")
return None
#raise Exception("Requested parameter is not valid!")
def getProperty (primative, parameterName): # Unsafe
# Get param
prop = primative.GetProperty(parameterName).Get()
return prop
def propertyIsValid (primative, parameterName):
# Get param
prop = primative.GetProperty(parameterName)
# Test validity
if ( type(prop) == type(Usd.Attribute())): # is valid
return True
else:
return False
def get_rot(rotation):
# Calculates rotation matrix given a x,y,z rotation in degrees
factor = 2.0 * np.pi / 360.0 # Convert to radians
x_angle, y_angle, z_angle = rotation[0]*factor, rotation[1]*factor, rotation[2]*factor
x_rot = np.array([[1,0,0],[0,np.cos(x_angle),-np.sin(x_angle)],[0,np.sin(x_angle),np.cos(x_angle)]], dtype='float64')
y_rot = np.array([[np.cos(y_angle),0,np.sin(y_angle)],[0,1,0],[-np.sin(y_angle),0,np.cos(y_angle)]], dtype='float64')
z_rot = np.array([[np.cos(z_angle),-np.sin(z_angle),0],[np.sin(z_angle),np.cos(z_angle),0],[0,0,1]], dtype='float64')
rot_mat = np.dot(np.dot(x_rot,y_rot),z_rot)
return rot_mat
_ALLOWED_MATERIAL_PURPOSES = (
UsdShade.Tokens.full,
UsdShade.Tokens.preview,
UsdShade.Tokens.allPurpose,
)
def get_bound_material(
prim, material_purpose=UsdShade.Tokens.allPurpose, collection=""
):
# From https://github.com/ColinKennedy/USD-Cookbook/blob/master/tricks/bound_material_finder/python/material_binding_api.py 30/01/23
"""Find the strongest material for some prim / purpose / collection.
If no material is found for `prim`, this function will check every
ancestor of Prim for a bound material and return that, instead.
Reference:
https://graphics.pixar.com/usd/docs/UsdShade-Material-Assignment.html#UsdShadeMaterialAssignment-MaterialResolve:DeterminingtheBoundMaterialforanyGeometryPrim
Args:
prim (`pxr.Usd.Prim`):
The path to begin looking for material bindings.
material_purpose (str, optional):
A specific name to filter materials by. Available options
are: `UsdShade.Tokens.full`, `UsdShade.Tokens.preview`,
or `UsdShade.Tokens.allPurpose`.
Default: `UsdShade.Tokens.allPurpose`
collection (str, optional):
The name of a collection to filter by, for any found
collection bindings. If not collection name is given then
the strongest collection is used, instead. Though generally,
it's recommended to always provide a collection name if you
can. Default: "".
Raises:
ValueError:
If `prim` is invalid or if `material_purpose` is not an allowed purpose.
Returns:
`pxr.UsdShade.Material` or NoneType:
The strongest bound material, if one is assigned.
"""
def is_collection_binding_stronger_than_descendents(binding):
return (
UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(
binding.GetBindingRel()
)
== "strongerThanDescendents"
)
def is_binding_stronger_than_descendents(binding, purpose):
"""bool: Check if the given binding/purpose is allowed to override any descendent bindings."""
return (
UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(
binding.GetDirectBindingRel(materialPurpose=purpose)
)
== "strongerThanDescendents"
)
def get_collection_material_bindings_for_purpose(binding, purpose):
"""Find the closest ancestral collection bindings for some `purpose`.
Args:
binding (`pxr.UsdShade.MaterialBindingAPI`):
The material binding that will be used to search
for a direct binding.
purpose (str):
The name of some direct-binding purpose to filter by. If
no name is given, any direct-binding that is found gets
returned.
Returns:
list[`pxr.UsdShade.MaterialBindingAPI.CollectionBinding`]:
The found bindings, if any could be found.
"""
# XXX : Note, Normally I'd just do
# `UsdShadeMaterialBindingAPI.GetCollectionBindings` but, for
# some reason, `binding.GetCollectionBindings(purpose)` does not
# yield the same result as parsing the relationships, manually.
# Maybe it's a bug?
#
# return binding.GetCollectionBindings(purpose)
#
parent = binding.GetPrim()
# TODO : We're doing quadratic work here... not sure how to improve this section
while not parent.IsPseudoRoot():
binding = binding.__class__(parent)
material_bindings = [
UsdShade.MaterialBindingAPI.CollectionBinding(relationship)
for relationship in binding.GetCollectionBindingRels(purpose)
if relationship.IsValid()
]
if material_bindings:
return material_bindings
parent = parent.GetParent()
return []
def get_direct_bound_material_for_purpose(binding, purpose):
"""Find the bound material, using direct binding, if it exists.
Args:
binding (`pxr.UsdShade.MaterialBindingAPI`):
The material binding that will be used to search
for a direct binding.
purpose (str):
The name of some direct-binding purpose to filter by. If
no name is given, any direct-binding that is found gets
returned.
Returns:
`pxr.UsdShade.Material` or NoneType: The found material, if one could be found.
"""
relationship = binding.GetDirectBindingRel(materialPurpose=purpose)
direct = UsdShade.MaterialBindingAPI.DirectBinding(relationship)
if not direct.GetMaterial():
return None
material = direct.GetMaterialPath()
prim = binding.GetPrim().GetStage().GetPrimAtPath(material)
if not prim.IsValid():
return None
return UsdShade.Material(prim)
if not prim.IsValid():
raise ValueError('Prim "{prim}" is not valid.'.format(prim=prim))
if material_purpose not in _ALLOWED_MATERIAL_PURPOSES:
raise ValueError(
'Purpose "{material_purpose}" is not valid. Options were, "{options}".'.format(
material_purpose=material_purpose,
options=sorted(_ALLOWED_MATERIAL_PURPOSES),
)
)
purposes = {material_purpose, UsdShade.Tokens.allPurpose}
for purpose in purposes:
material = None
parent = prim
while not parent.IsPseudoRoot():
binding = UsdShade.MaterialBindingAPI(parent)
if not material or is_binding_stronger_than_descendents(binding, purpose):
material = get_direct_bound_material_for_purpose(binding, purpose)
for collection_binding in get_collection_material_bindings_for_purpose(
binding, purpose
):
binding_collection = collection_binding.GetCollection()
if collection and binding_collection.GetName() != collection:
continue
membership = binding_collection.ComputeMembershipQuery()
if membership.IsPathIncluded(parent.GetPath()) and (
not material
or is_collection_binding_stronger_than_descendents(
collection_binding
)
):
material = collection_binding.GetMaterial()
# Keep searching ancestors until we hit the scene root
parent = parent.GetParent()
if material:
return material
class USDtoDAGMC:
'''
Class to convert USD to h5m file format usable for DAGMC, for use with OpenMC
'''
def __init__(self):
# Initialise with blank numpy arrays
self.vertices = np.array([])
self.triangles = []
self.material_tags = []
def add_USD_file(self, filename: str = fname_root + '.usd'):
'''
Load parts form USD into class with their associated material tags and then converts to triangles for use
in the conversion script
Args:
filename: filename used to import the USD file with
'''
stage_file = filename
stage = Usd.Stage.Open(stage_file)
volumeOffset = 0 # Required as all vertices have to be in a global 1D array (all volumes) => this offsets the indexing
# for each individual volume as all vertices for new volumes are added into the same array as previous
# volumes (vertices is 1D, triangles is 2D with 2nd dimension have the number of volumes in)
material_count = 0 # For materials that 'fall through the net'
# Change as NVIDIA is annoying with its choice of up axis (they choose Y whereas it should be Z for OpenMC...)
# Find parent folder path
if "PhD" in path_py:
cwl_folder = path_py.split(f"{sep}PhD", 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)
with open(settings_path, 'r') as file:
for line in file:
if "up_axis" in line:
up_axis = line.split()[1]
for primID, x in enumerate(stage.Traverse()):
primType = x.GetTypeName()
print(f"PRIM: {str(primType)}")
print(f'PrimID is {primID}')
if str(primType) == 'Mesh':
material_count += 1
# Get the material type of the meshes
material_name = str(get_bound_material(x))
try:
material_name = material_name.split('<')[1] # Just get material name from between <>
material_name = material_name.split('>')[0] # In form of UsdShade.Material(Usd.Prim(</World/Looks/Aluminum_Anodized>))
material_name = material_name.split('/')[-1] # Get the last name from file path
print(f"Material name is: {material_name}")
except:
material_name = f"mesh_{material_count}"
print('No USD material found')
print(f'Setting material name to default: {material_name}')
# Get num of vertecies in elements
allVertexCounts = np.array(getValidProperty(x,"faceVertexCounts"))
allVertexIndices = np.array(getValidProperty(x,"faceVertexIndices"))
# Get if there is rotation or translation of the meshes
rotation = [0.0,0.0,0.0] if not propertyIsValid(x,"xformOp:rotateXYZ") else list(getProperty(x,"xformOp:rotateXYZ"))
translation = np.array([0,0,0]) if not propertyIsValid(x,"xformOp:translate") else np.array(list(getProperty(x,"xformOp:translate")))
print(f'Rotation is {rotation}')
print(f'Translation is {translation}')
# Handling for changing the up axis
if up_axis == 'X':
rotation[1] -= 90.0 # TODO: Check this is correct...
elif up_axis == 'Y':
rotation[0] += 90.0
elif up_axis == 'Z':
rotation = rotation
else:
print('Something went wrong with up_axis')
rot_matrix = get_rot(rotation)
# TODO: Make the rotation matrix multiplication better! Lazy coding for now...
newVertices = np.array(getValidProperty(x,"points"), dtype='float64') # Assign vertices here and add rotation and translation
newVertices = np.array([np.dot(rot_matrix,xyz) for xyz in newVertices]) # Have to rotate first before translating as it rotates around the origin
newVertices = newVertices + translation
if self.vertices.size == 0: # For first run though just set vertices to newVertices array
self.vertices = newVertices
else:
self.vertices = np.append(self.vertices, newVertices, axis=0)
globalCount = 0
extraPointCount = 0
endOfVolumeIdx = np.size(self.vertices,0)
trianglesForVolume = np.array([], dtype="int")
if np.all(allVertexCounts == 3): # Case where mesh is already in triangles (makes program run much faster - hopeuflly!)
trianglesForVolume = allVertexIndices.reshape((allVertexCounts.size,3)) + volumeOffset
else:
for Count in allVertexCounts:
if Count == 3: # Triangle
a, b, c = globalCount, globalCount+1, globalCount+2
# For explanation of +volumeOffset see initialisation of volumeOffset variable
if trianglesForVolume.size == 0: # This whole shenanegans is because i dont know how to use numpy arrays properly.... LEARN
trianglesForVolume = np.array([[allVertexIndices[a]+volumeOffset, allVertexIndices[b]+volumeOffset, allVertexIndices[c]+volumeOffset]])
else:
trianglesForVolume = np.append(trianglesForVolume, np.array([[allVertexIndices[a]+volumeOffset, allVertexIndices[b]+volumeOffset, allVertexIndices[c]+volumeOffset]]), axis=0)
elif Count == 4: # Quadrilateral => Split into 2 triangles
a, b, c, d = globalCount, globalCount+1, globalCount+2, globalCount+3
if trianglesForVolume.size == 0:
trianglesForVolume = np.array([[allVertexIndices[a]+volumeOffset, allVertexIndices[b]+volumeOffset, allVertexIndices[c]+volumeOffset]])
else:
trianglesForVolume = np.append(trianglesForVolume, np.array([[allVertexIndices[a]+volumeOffset, allVertexIndices[b]+volumeOffset, allVertexIndices[c]+volumeOffset]]), axis=0)
#Think this may cause issues with some quadrilaterials being split into 2 triangles that overlap and leave a gap - see latex doc
trianglesForVolume = np.append(trianglesForVolume, np.array([[allVertexIndices[a]+volumeOffset, allVertexIndices[c]+volumeOffset, allVertexIndices[d]+volumeOffset]]), axis=0)
elif Count > 4: # n points to triangles
indices = np.array([allVertexIndices[globalCount+i]+volumeOffset for i in range(Count)]) # Get array of indices of points
points = np.array([self.vertices[idx] for idx in indices]) # Get points that match those indices
# Find mifddle of n-sided polygon => can make triangles from every edge to centre point and add to end of vertices matrix
self.vertices = np.append(self.vertices, np.array([[np.average(points[:,dir]) for dir in range(3)]]), axis=0)
centrePointIdx = endOfVolumeIdx + extraPointCount
extraPointCount += 1 # Just added an extra point into the vertices array
for triangleNum in range(Count):
if triangleNum == Count - 1: # Last triangle
trianglesForVolume = np.append(trianglesForVolume, np.array([[indices[0], indices[triangleNum], centrePointIdx]]), axis=0)
else:
if trianglesForVolume.size == 0:
trianglesForVolume = np.array([[indices[triangleNum], indices[triangleNum+1], centrePointIdx]])
else:
trianglesForVolume = np.append(trianglesForVolume, np.array([[indices[triangleNum], indices[triangleNum+1], centrePointIdx]]), axis=0)
else:
print(f"I don't know what to do with a {Count} count yet...")
globalCount += Count
self.triangles.append(trianglesForVolume)
self.material_tags.append(material_name)
shapeVertices = np.shape(newVertices)
volumeOffset += shapeVertices[0] + extraPointCount # Account for all points plus any extras added in from Counts>4
else:
print(f"I don't know what to do with a {str(primType)} yet...")
print("\n\n")
def save_to_h5m(self, filename: str = fname_root + '.h5m'):
'''
Use the verticies saved in the class to convert to h5m using the vertices_to_h5m mini package
https://github.com/fusion-energy/vertices_to_h5m
Args:
filename: Filename to save the h5m file, default will be dagmc.h5m (as this is the format required by DAGMC)
'''
vertices_to_h5m(
vertices=self.vertices,
triangles=self.triangles,
material_tags=self.material_tags,
h5m_filename=filename,
)
filepath = find_files(fname_root + '.usd')
convert = USDtoDAGMC()
convert.add_USD_file(filename = filepath[0])
convert.save_to_h5m()
| 19,319 | Python | 44.352113 | 206 | 0.59589 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/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 "omni.hello.world" 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 omni.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,037 | Markdown | 37.452829 | 258 | 0.756505 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/tools/scripts/link_app.py | import os
import argparse
import sys
import json
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,813 | Python | 32.5 | 133 | 0.562389 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/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 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/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 zipfile
import tempfile
import sys
import shutil
__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,888 | Python | 31.568965 | 103 | 0.68697 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/config/extension.toml | [package]
title = "OpenMC Workflow Runner"
description = "OpenMC Workflow Runner built as part of MSc Dissertation Project"
version = "1.0"
category = "Example"
authors = ["William Smith"]
keywords = ["openmc", "runner"]
readme = "docs/README.md"
repository = ""
[dependencies]
"omni.kit.uiapp" = {}
"omni.ui" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.openmc.runner" | 390 | TOML | 21.999999 | 80 | 0.684615 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/ui_helpers.py | import omni.ui as ui
from .functions import *
import numpy as np
import os
class MinimalItem(ui.AbstractItem):
def __init__(self,text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class MinimalModel(ui.AbstractItemModel):
def __init__(self, items, value=0):
# Items is a 1D array of strings that are the options for the dropdown
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(
lambda a:self._item_changed(None))
self._items = [
MinimalItem(text)
for text in items
]
self._current_index.set_value(value)
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def set_model_state(self, value=0):
self._current_index.set_value(value) | 994 | Python | 26.638888 | 78 | 0.608652 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/test_cwlcall.py | import os
import subprocess, sys # Alternative to os to run shell commands - dont know why it wasn't working before...
import tempfile
###################################
## Set Paths & Get Temp Folders
###################################
sep = os.sep # System separator
ext_path = os.path.realpath(__file__) # File path of ext
parent_folder = ext_path.split(f"{sep}omni-kit", 1)[0] # File path of parent folder to extension
tmp = tempfile.gettempdir()
paths = {
"workflow" : f"{parent_folder}{sep}tools",
"output_container" : f"{sep}output", # IN container
"output_omni" : f"{parent_folder}{sep}output{sep}omni",
"output_sim" : f"{parent_folder}{sep}output{sep}simulation",
"output_test" : f"{parent_folder}{sep}output{sep}test",
"general_CAD" : f"{sep}paramak{sep}dagmc.h5m",
"sep" : sep,
"tmp" : tmp,
"share" : f"{tmp}{sep}share",
"usdTmp" : f"{tmp}{sep}usd",
"outTmpOpenMC" : f"{tmp}{sep}outOpenMC",
"workflowDest" : "/" # In container
}
cmd = f"toil-cwl-runner --outdir {paths['output_omni']} {paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.cwl {paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.yml"
# output = subprocess.run(["toil-cwl-runner", "--outdir", paths['output_omni'], f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.cwl", f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.yml"], capture_output=True, text=True)
output = subprocess.run([i for i in cmd.split(' ')], capture_output=True, text=True)
print(f'stdout:\n\n{output.stdout}\n\n')
print(f'stderr:\n\n{output.stderr}\n\n') | 1,774 | Python | 48.305554 | 256 | 0.588501 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/extension.py | __all__ = ["OpenMCExt"]
from .window import Window
from functools import partial
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
class OpenMCExt(omni.ext.IExt):
WINDOW_NAME = "OpenMC Window"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(OpenMCExt.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
OpenMCExt.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(OpenMCExt.WINDOW_NAME)
with ui.VStack():
ui.Button("Refresh", clicked_fn=lambda: OpenMCExt.show_window())
def on_shutdown(self):
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(OpenMCExt.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(OpenMCExt.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
if value:
self._window = Window(OpenMCExt.WINDOW_NAME, width=300, height=365)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
| 2,361 | Python | 32.267605 | 95 | 0.615841 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/__init__.py | __all__ = ["OpenMCExt", "Window"]
from .extension import OpenMCExt
from .window import Window
| 95 | Python | 18.199996 | 33 | 0.715789 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/functions.py | import os, tarfile, tempfile, pathlib # System packages
import omni
import subprocess, sys # Alternative to os to run shell commands - dont know why it wasn't working before...
#################################################################
## Set Paths for Folders & Create Cases for Linux vs Windows OS
#################################################################
sep = os.sep # System separator
ext_path = os.path.realpath(__file__) # File path of ext
parent_folder = ext_path.split(f"{sep}omni-kit", 1)[0] # File path of parent folder to extension
tmp = tempfile.gettempdir()
paths = {
"workflow" : f"{parent_folder}{sep}tools",
"output_container" : f"{sep}output", # IN container
"output_omni" : f"{parent_folder}{sep}output{sep}omni",
"output_sim" : f"{parent_folder}{sep}output{sep}simulation",
"output_test" : f"{parent_folder}{sep}output{sep}test",
"general_CAD" : f"{sep}paramak{sep}dagmc.h5m",
"tmp" : tmp,
"share" : f"{tmp}{sep}share",
"usdTmp" : f"{tmp}{sep}usd",
"outTmpOpenMC" : f"{tmp}{sep}outOpenMC",
"workflowDest" : "/" # In container
}
# Allow choice between toil runner and cwltool - useful for testing
toil_runner = True
if toil_runner:
runner = 'toil-cwl-runner'
else:
runner = 'cwltool'
# Get operating system and set a prefix for the workflow commands
platform = sys.platform
if platform == 'linux':
prefix_cmd = f'{runner}'
elif platform == 'win32':
prefix_cmd = f'wsl.exe {runner}'
else: # Unaccounted for OS
print(f"I don't know what to do with operating system type: {platform}")
###################################
## Helper Functions
###################################
def t_f(string):
"""
Convert string to bool with error handling
Parameters
----------
string: String
String to be tested if True or False
Returns
-------
bool: Default value of False
True or False
"""
if string == 'True':
return True
elif string == 'False':
return False
else:
print("I don't know what this is, returning default of false")
return False
def export_stage():
"""
Exports the current USD stage to an output file
"""
path = f"{paths['output_omni']}{sep}dagmc.usd"
print(f"Exporting stage to: {path}")
stage = omni.usd.get_context().get_stage()
stage.Export(path)
print("Successfully exported USD stage!")
def wsl_file_convert(win_path):
"""
Converts a windows file path, ie C:\PhD\OmniFlow....
to a wsl mount file path, ie /mnt/c/PhD/OmniFlow....
Parameters
----------
win_path: string
file path in normal windows format
Returns
-------
wsl_file: string
file path in wsl format
"""
step_in_path = win_path.split('\\')
drive_letter = step_in_path[0].replace(':', '')
wsl_file = f"/mnt/{drive_letter}"
for step in step_in_path[1:]:
wsl_file = f"{wsl_file}/{step}"
return wsl_file
###################################
## Workflows
###################################
def toy_test():
"""
Run a test module on a toy problem, validate base system is working
Writes files into test output folder
"""
print("Running Toy Test Workflow")
# Handling of different operating systems
if platform == 'linux':
out_dir = paths['output_test']
cwl_loc = f"{paths['workflow']}{sep}tests{sep}toy{sep}openmc_tool_toy.cwl"
yml_loc = f"{paths['workflow']}{sep}tests{sep}toy{sep}script_loc_toy.yml"
elif platform == 'win32':
out_dir = wsl_file_convert(paths['output_test'])
cwl_loc = wsl_file_convert(f"{paths['workflow']}{sep}tests{sep}toy{sep}openmc_tool_toy.cwl")
yml_loc = wsl_file_convert(f"{paths['workflow']}{sep}tests{sep}toy{sep}script_loc_toy.yml")
else:
print(f"Don't know how to handle platform: {platform} yet")
# Run the workflow
cmd = f"{prefix_cmd} --outdir {out_dir} {cwl_loc} {yml_loc}"
print(cmd)
output = subprocess.run([i for i in cmd.split(' ')], capture_output=True, text=True)
print(f'stdout:\n\n{output.stdout}\n\n')
print(f'stderr:\n\n{output.stderr}\n\n')
print(f"Toy Test Complete! Your files will be in: {paths['output_test']}")
def simple_CAD_test():
"""
Run a test module on a simple CAD problem, validate CAD system is working
Writes files into test output folder
"""
print("Running Simple CAD Test Workflow")
# Handling of different operating systems
if platform == 'linux':
out_dir = paths['output_test']
cwl_loc = f"{paths['workflow']}{sep}tests{sep}simple{sep}simple_CAD_workflow.cwl"
yml_loc = f"{paths['workflow']}{sep}tests{sep}simple{sep}script_loc_simple_CAD.yml"
elif platform == 'win32':
out_dir = wsl_file_convert(paths['output_test'])
cwl_loc = wsl_file_convert(f"{paths['workflow']}{sep}tests{sep}simple{sep}simple_CAD_workflow.cwl")
yml_loc = wsl_file_convert(f"{paths['workflow']}{sep}tests{sep}simple{sep}script_loc_simple_CAD.yml")
else:
print(f"Don't know how to handle platform: {platform} yet")
# Run the workflow
cmd = f"{prefix_cmd} --outdir {out_dir} {cwl_loc} {yml_loc}"
print(cmd)
output = subprocess.run([i for i in cmd.split(' ')], capture_output=True, text=True)
print(f'stdout:\n\n{output.stdout}\n\n')
print(f'stderr:\n\n{output.stderr}\n\n')
print(f"Simple CAD Test Complete! Your files will be in: {paths['output_test']}")
def run_workflow():
"""
Main OpenMC Workflow runner
Runs workflow with the settings file written to in the extension
Writes files to simulation folder
"""
print('Running OpenMC Workflow')
print("Exporting USD Stage")
export_stage()
print("Running Workflow")
# Handling of different operating systems
if platform == 'linux':
out_dir = paths['output_sim']
cwl_loc = f"{paths['workflow']}{sep}main{sep}openmc_workflow.cwl"
yml_loc = f"{paths['workflow']}{sep}main{sep}script_loc.yml"
elif platform == 'win32':
out_dir = wsl_file_convert(paths['output_sim'])
cwl_loc = wsl_file_convert(f"{paths['workflow']}{sep}main{sep}openmc_workflow.cwl")
yml_loc = wsl_file_convert(f"{paths['workflow']}{sep}main{sep}script_loc.yml")
else:
print(f"Don't know how to handle platform: {platform} yet")
# Run the workflow
cmd = f"{prefix_cmd} --outdir {out_dir} {cwl_loc} {yml_loc}"
print(cmd)
output = subprocess.run([i for i in cmd.split(' ')], capture_output=True, text=True)
print(f'stdout:\n\n{output.stdout}\n\n')
print(f'stderr:\n\n{output.stderr}\n\n')
print(f"Done! Your files will be in: {paths['output_sim']}")
def get_materials():
"""
Gets material names from the USD file in the current stage
Returns
-------
materials: 1D String Array
All material names present in the stage
"""
print("Getting Material Names")
print('Exporting File')
export_stage()
print(ext_path)
print('Running materials getter')
# Handling of different operating systems
if platform == 'linux':
out_dir = paths['output_omni']
cwl_loc = f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.cwl"
yml_loc = f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.yml"
elif platform == 'win32':
out_dir = wsl_file_convert(paths['output_omni'])
cwl_loc = wsl_file_convert(f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.cwl")
yml_loc = wsl_file_convert(f"{paths['workflow']}{sep}dagmc_material_name{sep}dagmc_materials.yml")
else:
print(f"Don't know how to handle platform: {platform} yet")
# Run the workflow
cmd = f"{prefix_cmd} --outdir {out_dir} {cwl_loc} {yml_loc}"
print(cmd)
output = subprocess.run([i for i in cmd.split(' ')], capture_output=True, text=True)
print(f'stdout:\n\n{output.stdout}\n\n')
print(f'stderr:\n\n{output.stderr}\n\n')
mat_file_path = f"{paths['output_omni']}{sep}materials.txt"
materials = []
if os.path.exists(mat_file_path):
with open(mat_file_path) as file:
for line in file:
materials.append(line)
print("Materials Getter Finished")
return materials | 8,561 | Python | 31.804598 | 109 | 0.598762 |
williamjsmith15/OmniFlow/OpenMC/omni-kit-extension/exts/omni.openmc.runner/omni/openmc/runner/window.py | __all__ = ["Window"]
import omni.ui as ui
from .functions import *
from .ui_helpers import *
import numpy as np
import os
LABEL_WIDTH = 120
SPACING = 4
default_dict = {
'sources' : [],
'materials' : [],
# Run settings
'batches' : 0,
'particles' : 0,
'run_mode' : 'fixed source',
# All system / extension settings
'num_sources' : 1,
'source_type' : 'Point Source', # 0=point, 1=plasma
'up_axis' : 'Z', # 0=X 1=Y 2=Z
'test_dropdown' : False,
'mats_dropdown' : False,
'sets_dropdown' : True,
'srcs_dropdown' : False
}
class Window(ui.Window):
"""The class that represents the window"""
# Create dict to store variables
settings_dict = default_dict
previous_settings = default_dict
# Options for dropdowns
run_type_options = np.array(['fixed source','eigenvalue','volume','plot','particle restart'])
source_type_options = np.array(['Point Source', 'Fusion Point Source', 'Fusion Ring Source', 'Tokamak Source'])
up_axis_choice = np.array(['X','Y','Z'])
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
##########################
# --- BUILD FRAMES ---
##########################
def _build_run(self):
# Build the widgets of the Run group
with ui.VStack(height=0, spacing=SPACING):
ui.Label("OpenMC Workflow Run and Settings")
ui.Button("Run Workflow", clicked_fn=lambda: self._run_workflow_button())
ui.Button("Save State", clicked_fn=lambda: self._save_state_button())
self.settings_dict['test_dropdown'] = ui.CollapsableFrame("Test", collapsed = t_f(self.previous_settings['test_dropdown']))
with self.settings_dict['test_dropdown']:
with ui.HStack():
ui.Button("Run Toy Test", clicked_fn=lambda: toy_test())
ui.Button("Run Simple CAD Test", clicked_fn=lambda: simple_CAD_test())
def _build_materials(self):
# Takes the material.txt file and reads all the material names into teh materails list
mat_file_path = f"{paths['output_omni']}{sep}materials.txt"
materials = []
if os.path.exists(mat_file_path):
with open(mat_file_path) as file:
for line in file:
materials.append(line)
# Build the widgets of the Materials
self.settings_dict['mats_dropdown'] = ui.CollapsableFrame("Materials", collapsed = t_f(self.previous_settings['mats_dropdown']))
with self.settings_dict['mats_dropdown']:
with ui.VStack(height=0, spacing=SPACING):
ui.Button("Get Materials", clicked_fn=lambda: self._save_state_button(get_mats=True))
# Uses the materials list to create a stack of materials to edit properties
self.settings_dict['materials'] = []
for i in range(len(self.previous_settings['materials'])):
self.settings_dict['materials'].append([None]*3)
self.settings_dict['materials'][i][0] = self.previous_settings['materials'][i][0]
with ui.HStack(spacing = SPACING):
ui.Label(self.previous_settings['materials'][i][0], width=self.label_width)
ui.Label("Element")
self.settings_dict['materials'][i][1] = ui.StringField().model
if str(self.previous_settings['materials'][i][1]) != 'None':
self.settings_dict['materials'][i][1].set_value(str(self.previous_settings['materials'][i][1]))
# ui.Label("Atom Percent", width=self.label_width)
# tmp_array[1] = ui.FloatField().model
ui.Label("Density (g/cm^3)")
self.settings_dict['materials'][i][2] = ui.FloatField().model
self.settings_dict['materials'][i][2].set_value(str(self.previous_settings['materials'][i][2]))
def _build_sources(self):
self.settings_dict['srcs_dropdown'] = ui.CollapsableFrame("Sources", collapsed = t_f(self.previous_settings['srcs_dropdown']))
with self.settings_dict['srcs_dropdown']:
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Source Type", width=self.label_width)
self.settings_dict['source_type'] = MinimalModel(items=self.source_type_options, value=int(np.where(self.source_type_options==str(self.previous_settings['source_type']))[0]))
ui.ComboBox(self.settings_dict['source_type'])
ui.Button("Enter", clicked_fn=lambda: self._save_state_button())
with ui.HStack():
ui.Label("Number of Sources", width=self.label_width)
self.settings_dict['num_sources'] = ui.IntField().model
self.settings_dict['num_sources'].set_value(int(self.previous_settings['num_sources']))
ui.Button("Enter", clicked_fn=lambda: self._save_state_button())
# Point source case
if self.settings_dict['source_type'].get_item_value_model(None, 1).get_value_as_int() == 0:
self.settings_dict['sources'] = []
for i in range(int(self.previous_settings['num_sources'])):
self.settings_dict['sources'].append([None]*4)
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack(spacing=SPACING):
ui.Label(f"Source {i+1}", width=self.label_width)
ui.Label("Energy:", width=self.label_width)
self.settings_dict['sources'][i][0] = ui.FloatField().model
ui.Label("Location:", width=self.label_width)
self.settings_dict['sources'][i][1] = ui.FloatField().model
self.settings_dict['sources'][i][2] = ui.FloatField().model
self.settings_dict['sources'][i][3] = ui.FloatField().model
try:
self.settings_dict['sources'][i][0].set_value(float(self.previous_settings['sources'][i][0]))
self.settings_dict['sources'][i][1].set_value(float(self.previous_settings['sources'][i][1]))
self.settings_dict['sources'][i][2].set_value(float(self.previous_settings['sources'][i][2]))
self.settings_dict['sources'][i][3].set_value(float(self.previous_settings['sources'][i][3]))
except: # Handling of sources that don't have data
print(f"No source data found for source {i+1}")
# Fusion Point Source Case
elif self.settings_dict['source_type'].get_item_value_model(None, 1).get_value_as_int() == 1:
self.settings_dict['sources'] = []
for i in range(int(self.previous_settings['num_sources'])):
self.settings_dict['sources'].append([None]*5)
with ui.HStack(spacing=SPACING):
ui.Label(f"Source {i+1}", width=self.label_width)
with ui.HStack(spacing=SPACING):
ui.Label("Fuel Type (DT, DD)", width=self.label_width)
self.settings_dict['sources'][i][4] = ui.StringField().model
ui.Label("Temoerature (eV)", width=self.label_width)
self.settings_dict['sources'][i][3] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Coordinate:")
ui.Label("x")
self.settings_dict['sources'][i][0] = ui.FloatField().model
ui.Label("y")
self.settings_dict['sources'][i][1] = ui.FloatField().model
ui.Label("z")
self.settings_dict['sources'][i][2] = ui.FloatField().model
for j in range(5):
try:
if j == 4:
self.settings_dict['sources'][i][j].set_value(str(self.previous_settings['sources'][i][j]))
else:
self.settings_dict['sources'][i][j].set_value(float(self.previous_settings['sources'][i][j]))
except: # Handling of sources that don't have data
print(f"No float data found for source {i+1}")
# Fusion Ring Source Case
elif self.settings_dict['source_type'].get_item_value_model(None, 1).get_value_as_int() == 2:
self.settings_dict['sources'] = []
for i in range(int(self.previous_settings['num_sources'])):
self.settings_dict['sources'].append([None]*6)
with ui.HStack(spacing=SPACING):
ui.Label(f"Source {i+1}", width=self.label_width)
ui.Label("Radius (inside, cm)", width=self.label_width)
self.settings_dict['sources'][i][0] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Angle (deg) start:", width=self.label_width)
self.settings_dict['sources'][i][2] = ui.FloatField().model
ui.Label("end:")
self.settings_dict['sources'][i][3] = ui.FloatField().model
ui.Label("Temp (eV)")
self.settings_dict['sources'][i][4] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Fuel Type (DT, DD)")
self.settings_dict['sources'][i][1] = ui.StringField().model
ui.Label("Vert Offset")
self.settings_dict['sources'][i][5] = ui.FloatField().model
for j in range(6):
try:
if j == 1:
self.settings_dict['sources'][i][j].set_value(str(self.previous_settings['sources'][i][j]))
else:
self.settings_dict['sources'][i][j].set_value(float(self.previous_settings['sources'][i][j]))
except: # Handling of sources that don't have data
print(f"No float data found for source {i+1}")
# Tokamak Source Case
elif self.settings_dict['source_type'].get_item_value_model(None, 1).get_value_as_int() == 3:
self.settings_dict['sources'] = []
for i in range(int(self.previous_settings['num_sources'])):
self.settings_dict['sources'].append([None]*19) # TODO: Check 18 is the correct number
with ui.HStack(spacing=SPACING):
ui.Label(f"Source {i+1}", width=self.label_width)
ui.Label("Major Radius (m)", width=self.label_width)
self.settings_dict['sources'][i][0] = ui.FloatField().model
ui.Label("Minor Radius (m)", width=self.label_width)
self.settings_dict['sources'][i][1] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Elongation", width=self.label_width)
self.settings_dict['sources'][i][2] = ui.FloatField().model
ui.Label("Triangularity")
self.settings_dict['sources'][i][3] = ui.FloatField().model
ui.Label("Confinement Mode (L,H,A)")
self.settings_dict['sources'][i][4] = ui.StringField().model
with ui.HStack(spacing=SPACING):
ui.Label("Ion Density (m^-3) at:")
ui.Label("Ion Density Peaking Factor")
self.settings_dict['sources'][i][6] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Centre", width=self.label_width)
self.settings_dict['sources'][i][5] = ui.FloatField().model
ui.Label("Pedestal")
self.settings_dict['sources'][i][7] = ui.FloatField().model
ui.Label("Seperatrix")
self.settings_dict['sources'][i][8] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Ion Temperature (KeV) at:")
ui.Label("Peaking Factor")
self.settings_dict['sources'][i][10] = ui.FloatField().model
ui.Label("Beta")
self.settings_dict['sources'][i][11] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Centre", width=self.label_width)
self.settings_dict['sources'][i][9] = ui.FloatField().model
ui.Label("Pedestal")
self.settings_dict['sources'][i][12] = ui.FloatField().model
ui.Label("Seperatrix")
self.settings_dict['sources'][i][13] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Pedestal Raduis (m)", width=self.label_width)
self.settings_dict['sources'][i][14] = ui.FloatField().model
ui.Label("Shafranov Factor")
self.settings_dict['sources'][i][15] = ui.FloatField().model
ui.Label("Sample Size")
self.settings_dict['sources'][i][18] = ui.FloatField().model
with ui.HStack(spacing=SPACING):
ui.Label("Angle (deg) start:", width=self.label_width)
self.settings_dict['sources'][i][16] = ui.FloatField().model
ui.Label("end:")
self.settings_dict['sources'][i][17] = ui.FloatField().model
for j in range(19):
try:
if j == 4:
self.settings_dict['sources'][i][j].set_value(str(self.previous_settings['sources'][i][j]))
else:
self.settings_dict['sources'][i][j].set_value(float(self.previous_settings['sources'][i][j]))
except: # Handling of sources that don't have data
print(f"No float data found for source {i+1}")
else:
print('There was an error, unknown source type detected')
def _build_settings(self):
# Build the widgets of the Settings group
self.settings_dict['sets_dropdown'] = ui.CollapsableFrame("Settings", collapsed = t_f(self.previous_settings['sets_dropdown']))
with self.settings_dict['sets_dropdown']:
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Batches", width=self.label_width)
self.settings_dict['batches'] = ui.IntField().model
self.settings_dict['batches'].set_value(int(self.previous_settings['batches']))
with ui.HStack():
ui.Label("Particles", width=self.label_width)
self.settings_dict['particles'] = ui.IntField().model
self.settings_dict['particles'].set_value(int(self.previous_settings['particles']))
with ui.HStack():
ui.Label("Run Mode", width=self.label_width)
self.settings_dict['run_mode'] = MinimalModel(items=self.run_type_options, value=int(np.where(self.run_type_options == self.previous_settings['run_mode'])[0]))
ui.ComboBox(self.settings_dict['run_mode'])
with ui.HStack():
ui.Label("Up Axis", width=self.label_width)
self.settings_dict['up_axis'] = MinimalModel(items=self.up_axis_choice, value=int(np.where(self.up_axis_choice == self.previous_settings['up_axis'])[0]))
ui.ComboBox(self.settings_dict['up_axis'])
def _build_export(self):
with ui.VStack(height=0, spacing=SPACING):
ui.Button("Export USD Stage", clicked_fn=lambda: export_stage())
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
self.load_state()
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_run()
self._build_materials()
self._build_sources()
self._build_settings()
self._build_export()
##########################
# --- BUTTONS ---
##########################
def _run_workflow_button(self):
self.generate()
run_workflow()
def _save_state_button(self, get_mats=False):
# Saves the state of the extension
self.generate(get_mats)
print('Refreshing screen')
self.frame.rebuild()
##########################
# --- EXTRA FUNCTIONS ---
##########################
def generate(self, get_mats=False):
# Converts settings and materials into a txt file for the general CAD py script to use
print("Saving Materials and Settings")
already_used_materials = []
if get_mats:
materials = get_materials()
with open(f"{paths['output_omni']}{sep}settings.txt", 'w') as file:
# Materials
file.write('MATERIALS\n')
# count = 0 # DEBUGGING
if get_mats: # Just write the materials to the settings file, no element or density
for mat in materials:
if mat in already_used_materials:
pass
else:
file.write(f"{mat}")
already_used_materials.append(mat)
else: # Write the material settings set in omni
for mat in self.settings_dict['materials']:
# count += 1
# file.write(f"mesh_{count} Fe 7.7\n")
if 'Irangon' in mat[0]:
file.write(f"{mat[0].replace(' ', '')} Fe 7.7\n")
else:
file.write(f"{mat[0].replace(' ', '')} {mat[1].get_value_as_string()} {mat[2].get_value_as_float()}\n")
# Sources
file.write('SOURCES\n')
for src in self.settings_dict['sources']:
tmp_src = []
for field in src:
try: # Basically handles any float or string coming out of the data fields and joins them with a space inbetween each
tmp_field = field.get_value_as_float()
except:
pass
try:
tmp_field = field.get_value_as_string()
except:
pass
tmp_src.append(str(tmp_field))
file.write(f"{' '.join(tmp_src)}\n")
# Settings
file.write('SETTINGS\n')
file.write(f"batches {self.settings_dict['batches'].get_value_as_int()}\n")
file.write(f"particles {self.settings_dict['particles'].get_value_as_int()}\n")
file.write(f"run_mode {self.run_type_options[self.settings_dict['run_mode'].get_item_value_model(None, 1).get_value_as_int()]}\n")
file.write('EXT_SETTINGS\n')
file.write(f"source_type {self.source_type_options[self.settings_dict['source_type'].get_item_value_model(None, 1).get_value_as_int()]}\n")
file.write(f"num_sources {self.settings_dict['num_sources'].get_value_as_int()}\n")
file.write(f"up_axis {self.up_axis_choice[self.settings_dict['up_axis'].get_item_value_model(None, 1).get_value_as_int()]}\n")
file.write(f"test_dropdown {self.settings_dict['test_dropdown'].collapsed}\n")
file.write(f"mats_dropdown {self.settings_dict['mats_dropdown'].collapsed}\n")
file.write(f"sets_dropdown {self.settings_dict['sets_dropdown'].collapsed}\n")
file.write(f"srcs_dropdown {self.settings_dict['srcs_dropdown'].collapsed}\n")
print("Finished Converting")
def load_state(self):
position = 0
self.previous_settings = {}
with open(f"{paths['output_omni']}{sep}settings.txt", 'r') as file:
for line in file:
split_line = line.split()
if position == 0:
if "MATERIALS" in line:
position = 1
self.previous_settings['materials'] = []
elif position == 1:
if "SOURCES" in line:
position = 2
self.previous_settings['sources'] = []
else:
if len(split_line) == 3:
self.previous_settings['materials'].append(split_line)
else:
self.previous_settings['materials'].append([split_line[0], None, 0.0])
elif position == 2:
if "SETTINGS" in line:
position = 3
else:
self.previous_settings['sources'].append(split_line)
elif position == 3:
if "EXT_SETTINGS" in line:
position = 4
else:
self.previous_settings[split_line[0]] = ' '.join(split_line[1:])
elif position == 4:
self.previous_settings[split_line[0]] = ' '.join(split_line[1:])
else:
print(f'I dont know what position {position} is')
| 23,792 | Python | 49.408898 | 194 | 0.49214 |
williamjsmith15/OmniFlow/ToilRunner/py_test_docker_compose.py | import docker
import os
import tempfile, pathlib, tarfile
###################################
## Set Paths & Get Temp Folders
###################################
sep = os.sep # System separator
ext_path = os.path.realpath(__file__) # File path of ext
parent_folder = ext_path.split(f"{sep}OmniFlow", 1)[0] # File path of parent folder to extension
parent_folder = f"{parent_folder}{sep}OmniFlow{sep}OpenMC"
tmp = tempfile.gettempdir()
paths = {
"workflow" : f"{parent_folder}{sep}tools",
"output_container" : f"{sep}output", # IN container
"output_omni" : f"{parent_folder}{sep}output{sep}omni",
"output_sim" : f"{parent_folder}{sep}output{sep}simulation",
"output_test" : f"{parent_folder}{sep}output{sep}test",
"tmp" : tmp,
"share" : f"{tmp}{sep}share",
"usdTmp" : f"{tmp}{sep}usd",
"outTmpOpenMC" : f"{tmp}{sep}outOpenMC",
"workflowDest" : "/" # In container
}
pathlib.Path(paths["share"]).mkdir(parents=True, exist_ok=True)
pathlib.Path(paths["usdTmp"]).mkdir(parents=True, exist_ok=True)
pathlib.Path(paths["outTmpOpenMC"]).mkdir(parents=True, exist_ok=True)
###################################
## Helper Functions
###################################
def make_tarfile(source_dir, output_filename):
with tarfile.open(output_filename, "w:gz") as tar:
print(f"{source_dir} contains: {os.listdir(source_dir)}")
tar.add(source_dir, arcname=os.path.basename(source_dir))
return tar
def send_files(container, source, temp, destination):
make_tarfile(source, temp)
with open(temp, 'rb') as bundle:
ok = container.put_archive(path=destination, data=bundle)
if not ok:
raise Exception(f'Put {source} to {destination} failed')
else:
print(f'Uploaded {source} ({os.path.getsize(temp)} B) to {destination} successfully')
def get_files(container, source, destination, fname):
f = open(f"{destination}{sep}{fname}.tar", 'wb')
bits, stat = container.get_archive(path = source)
for chunck in bits:
f.write(chunck)
f.close()
print(f"{paths['workflow']}{sep}tests{sep}toy{sep}openmc_tool_toy.cwl")
runner = 'cwltool' # Testing
# runner = 'toil-cwl-runner' # Testing
container = ' '
# container = ' --no-container '
# os.system(f"wsl.exe {runner}{container}--debug --outdir /mnt/d/PhD/OmniFlow/OpenMC/output/tests /mnt/d/PhD/OmniFlow/OpenMC/tools/tests/toy/openmc_tool_toy.cwl /mnt/d/PhD/OmniFlow/OpenMC/tools/tests/toy/script_loc_toy.yml")
os.system(f"wsl.exe {runner}{container}--debug --outdir /mnt/d/phd/omniflow/openmc/output/tests /mnt/d/PhD/OmniFlow/OpenMC/tools/tests/simple/simple_CAD_workflow.cwl /mnt/d/PhD/OmniFlow/OpenMC/tools/tests/simple/script_loc_simple_CAD.yml")
# client = docker.from_env()
# toilContainer = client.containers.get("omniflow-toil-1")
# # var = toilContainer.exec_run(["ls", "OmniFlow/OpenMC/tools/tests/toy"])
# var = toilContainer.exec_run(["toil-cwl-runner", "--debug", "--outdir", "OmniFlow/OpenMC/output/tests", "OmniFlow/OpenMC/tools/tests/toy/openmc_tool_toy.cwl", "OmniFlow/OpenMC/tools/tests/toy/script_loc_toy.yml"])
# for msg in str(var[1]).split("\\n"):
# for i in msg.split("\\x1b"):
# print(i)
# To look at:
# https://cwl.discourse.group/t/working-offline-with-singularity/246 | 3,441 | Python | 37.674157 | 239 | 0.622784 |
Road-Balance/RB_WheeledRobotExample/README.md | # Adding a wheeled robots tutorial codes for Youtube video | 58 | Markdown | 57.999942 | 58 | 0.827586 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "RBWheeledRobotExample"
EXTENSION_DESCRIPTION = ""
| 502 | Python | 37.692305 | 76 | 0.806773 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/scenario.py | # Copyright (c) 2022-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.
#
class ScenarioTemplate:
def __init__(self):
pass
def setup_scenario(self):
pass
def teardown_scenario(self):
pass
def update_scenario(self):
pass
import numpy as np
from omni.isaac.core.utils.types import ArticulationAction
"""
This scenario takes in a robot Articulation and makes it move through its joint DOFs.
Additionally, it adds a cuboid prim to the stage that moves in a circle around the robot.
The particular framework under which this scenario operates should not be taken as a direct
recomendation to the user about how to structure their code. In the simple example put together
in this template, this particular structure served to improve code readability and separate
the logic that runs the example from the UI design.
"""
class ExampleScenario(ScenarioTemplate):
def __init__(self):
self._object = None
self._articulation = None
self._running_scenario = False
self._time = 0.0 # s
self._object_radius = 0.5 # m
self._object_height = 0.5 # m
self._object_frequency = 0.25 # Hz
self._joint_index = 0
self._max_joint_speed = 4 # rad/sec
self._lower_joint_limits = None
self._upper_joint_limits = None
self._joint_time = 0
self._path_duration = 0
self._calculate_position = lambda t, x: 0
self._calculate_velocity = lambda t, x: 0
def setup_scenario(self, articulation, object_prim):
self._articulation = articulation
self._object = object_prim
self._initial_object_position = self._object.get_world_pose()[0]
self._initial_object_phase = np.arctan2(self._initial_object_position[1], self._initial_object_position[0])
self._object_radius = np.linalg.norm(self._initial_object_position[:2])
self._running_scenario = True
self._joint_index = 0
self._lower_joint_limits = articulation.dof_properties["lower"]
self._upper_joint_limits = articulation.dof_properties["upper"]
# teleport robot to lower joint range
epsilon = 0.001
articulation.set_joint_positions(self._lower_joint_limits + epsilon)
self._derive_sinusoid_params(0)
def teardown_scenario(self):
self._time = 0.0
self._object = None
self._articulation = None
self._running_scenario = False
self._joint_index = 0
self._lower_joint_limits = None
self._upper_joint_limits = None
self._joint_time = 0
self._path_duration = 0
self._calculate_position = lambda t, x: 0
self._calculate_velocity = lambda t, x: 0
def update_scenario(self, step: float):
if not self._running_scenario:
return
self._time += step
x = self._object_radius * np.cos(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi)
y = self._object_radius * np.sin(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi)
z = self._initial_object_position[2]
self._object.set_world_pose(np.array([x, y, z]))
self._update_sinusoidal_joint_path(step)
def _derive_sinusoid_params(self, joint_index: int):
# Derive the parameters of the joint target sinusoids for joint {joint_index}
start_position = self._lower_joint_limits[joint_index]
P_max = self._upper_joint_limits[joint_index] - start_position
V_max = self._max_joint_speed
T = P_max * np.pi / V_max
# T is the expected time of the joint path
self._path_duration = T
self._calculate_position = (
lambda time, path_duration: start_position
+ -P_max / 2 * np.cos(time * 2 * np.pi / path_duration)
+ P_max / 2
)
self._calculate_velocity = lambda time, path_duration: V_max * np.sin(2 * np.pi * time / path_duration)
def _update_sinusoidal_joint_path(self, step):
# Update the target for the robot joints
self._joint_time += step
if self._joint_time > self._path_duration:
self._joint_time = 0
self._joint_index = (self._joint_index + 1) % self._articulation.num_dof
self._derive_sinusoid_params(self._joint_index)
joint_position_target = self._calculate_position(self._joint_time, self._path_duration)
joint_velocity_target = self._calculate_velocity(self._joint_time, self._path_duration)
action = ArticulationAction(
np.array([joint_position_target]),
np.array([joint_velocity_target]),
joint_indices=np.array([self._joint_index]),
)
self._articulation.apply_action(action)
| 5,180 | Python | 34.244898 | 118 | 0.643822 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/extension.py | # Copyright (c) 2022-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
import gc
import omni
import omni.kit.commands
import omni.physx as _physx
import omni.timeline
import omni.ui as ui
import omni.usd
from omni.isaac.ui.element_wrappers import ScrollingWindow
from omni.isaac.ui.menu import MenuItemDescription
from omni.kit.menu.utils import add_menu_items, remove_menu_items
from omni.usd import StageEventType
from .global_variables import EXTENSION_DESCRIPTION, EXTENSION_TITLE
from .ui_builder import UIBuilder
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self.ext_id = ext_id
self._usd_context = omni.usd.get_context()
# Build Window
self._window = ScrollingWindow(
title=EXTENSION_TITLE, width=600, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.register_action(
ext_id,
f"CreateUIExtension:{EXTENSION_TITLE}",
self._menu_callback,
description=f"Add {EXTENSION_TITLE} Extension to UI toolbar",
)
self._menu_items = [
MenuItemDescription(name=EXTENSION_TITLE, onclick_action=(ext_id, f"CreateUIExtension:{EXTENSION_TITLE}"))
]
add_menu_items(self._menu_items, EXTENSION_TITLE)
# Filled in with User Functions
self.ui_builder = UIBuilder()
# Events
self._usd_context = omni.usd.get_context()
self._physxIFace = _physx.acquire_physx_interface()
self._physx_subscription = None
self._stage_event_sub = None
self._timeline = omni.timeline.get_timeline_interface()
def on_shutdown(self):
self._models = {}
remove_menu_items(self._menu_items, EXTENSION_TITLE)
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_action(self.ext_id, f"CreateUIExtension:{EXTENSION_TITLE}")
if self._window:
self._window = None
self.ui_builder.cleanup()
gc.collect()
def _on_window(self, visible):
if self._window.visible:
# Subscribe to Stage and Timeline Events
self._usd_context = omni.usd.get_context()
events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = events.create_subscription_to_pop(self._on_stage_event)
stream = self._timeline.get_timeline_event_stream()
self._timeline_event_sub = stream.create_subscription_to_pop(self._on_timeline_event)
self._build_ui()
else:
self._usd_context = None
self._stage_event_sub = None
self._timeline_event_sub = None
self.ui_builder.cleanup()
def _build_ui(self):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_extension_ui()
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_TITLE, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
#################################################################
# Functions below this point call user functions
#################################################################
def _menu_callback(self):
self._window.visible = not self._window.visible
self.ui_builder.on_menu_callback()
def _on_timeline_event(self, event):
if event.type == int(omni.timeline.TimelineEventType.PLAY):
if not self._physx_subscription:
self._physx_subscription = self._physxIFace.subscribe_physics_step_events(self._on_physics_step)
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self._physx_subscription = None
self.ui_builder.on_timeline_event(event)
def _on_physics_step(self, step):
self.ui_builder.on_physics_step(step)
def _on_stage_event(self, event):
if event.type == int(StageEventType.OPENED) or event.type == int(StageEventType.CLOSED):
# stage was opened or closed, cleanup
self._physx_subscription = None
self.ui_builder.cleanup()
self.ui_builder.on_stage_event(event)
def _build_extension_ui(self):
# Call user function for building UI
self.ui_builder.build_ui()
| 6,165 | Python | 37.298136 | 118 | 0.651095 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/__init__.py | # Copyright (c) 2022-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.
#
from .extension import *
| 456 | Python | 44.699996 | 76 | 0.809211 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/ui_builder.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-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 numpy as np
import omni.timeline
import omni.ui as ui
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.objects.cuboid import FixedCuboid
from omni.isaac.core.prims import XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import is_prim_path_valid
from omni.isaac.core.utils.stage import add_reference_to_stage, create_new_stage, get_current_stage
from omni.isaac.core.world import World
from omni.isaac.ui.element_wrappers import CollapsableFrame, StateButton
from omni.isaac.ui.element_wrappers.core_connectors import LoadButton, ResetButton
from omni.isaac.ui.ui_utils import get_style
from omni.usd import StageEventType
from pxr import Sdf, UsdLux
from .scenario import ExampleScenario
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper instance
self.wrapped_ui_elements = []
# Get access to the timeline to control stop/pause/play programmatically
self._timeline = omni.timeline.get_timeline_interface()
# Run initialization for the provided example
self._on_init()
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
if event.type == int(omni.timeline.TimelineEventType.STOP):
# When the user hits the stop button through the UI, they will inevitably discover edge cases where things break
# For complete robustness, the user should resolve those edge cases here
# In general, for extensions based off this template, there is no value to having the user click the play/stop
# button instead of using the Load/Reset/Run buttons provided.
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = False
def on_physics_step(self, step: float):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
if event.type == int(StageEventType.OPENED):
# If the user opens a new stage, the extension should completely reset
self._reset_extension()
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
world_controls_frame = CollapsableFrame("World Controls", collapsed=False)
with world_controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._load_btn = LoadButton(
"Load Button", "LOAD", setup_scene_fn=self._setup_scene, setup_post_load_fn=self._setup_scenario
)
self._load_btn.set_world_settings(physics_dt=1 / 60.0, rendering_dt=1 / 60.0)
self.wrapped_ui_elements.append(self._load_btn)
self._reset_btn = ResetButton(
"Reset Button", "RESET", pre_reset_fn=None, post_reset_fn=self._on_post_reset_btn
)
self._reset_btn.enabled = False
self.wrapped_ui_elements.append(self._reset_btn)
run_scenario_frame = CollapsableFrame("Run Scenario")
with run_scenario_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._scenario_state_btn = StateButton(
"Run Scenario",
"RUN",
"STOP",
on_a_click_fn=self._on_run_scenario_a_text,
on_b_click_fn=self._on_run_scenario_b_text,
physics_callback_fn=self._update_scenario,
)
self._scenario_state_btn.enabled = False
self.wrapped_ui_elements.append(self._scenario_state_btn)
######################################################################################
# Functions Below This Point Support The Provided Example And Can Be Deleted/Replaced
######################################################################################
def _on_init(self):
self._articulation = None
self._cuboid = None
self._scenario = ExampleScenario()
def _add_light_to_stage(self):
"""
A new stage does not have a light by default. This function creates a spherical light
"""
sphereLight = UsdLux.SphereLight.Define(get_current_stage(), Sdf.Path("/World/SphereLight"))
sphereLight.CreateRadiusAttr(2)
sphereLight.CreateIntensityAttr(100000)
XFormPrim(str(sphereLight.GetPath())).set_world_pose([6.5, 0, 12])
def _setup_scene(self):
"""
This function is attached to the Load Button as the setup_scene_fn callback.
On pressing the Load Button, a new instance of World() is created and then this function is called.
The user should now load their assets onto the stage and add them to the World Scene.
In this example, a new stage is loaded explicitly, and all assets are reloaded.
If the user is relying on hot-reloading and does not want to reload assets every time,
they may perform a check here to see if their desired assets are already on the stage,
and avoid loading anything if they are. In this case, the user would still need to add
their assets to the World (which has low overhead). See commented code section in this function.
"""
# Load the UR10e
robot_prim_path = "/ur10e"
path_to_robot_usd = get_assets_root_path() + "/Isaac/Robots/UniversalRobots/ur10e/ur10e.usd"
# Do not reload assets when hot reloading. This should only be done while extension is under development.
# if not is_prim_path_valid(robot_prim_path):
# create_new_stage()
# add_reference_to_stage(path_to_robot_usd, robot_prim_path)
# else:
# print("Robot already on Stage")
create_new_stage()
self._add_light_to_stage()
add_reference_to_stage(path_to_robot_usd, robot_prim_path)
# Create a cuboid
self._cuboid = FixedCuboid(
"/Scenario/cuboid", position=np.array([0.3, 0.3, 0.5]), size=0.05, color=np.array([255, 0, 0])
)
self._articulation = Articulation(robot_prim_path)
# Add user-loaded objects to the World
world = World.instance()
world.scene.add(self._articulation)
world.scene.add(self._cuboid)
def _setup_scenario(self):
"""
This function is attached to the Load Button as the setup_post_load_fn callback.
The user may assume that their assets have been loaded by their setup_scene_fn callback, that
their objects are properly initialized, and that the timeline is paused on timestep 0.
In this example, a scenario is initialized which will move each robot joint one at a time in a loop while moving the
provided prim in a circle around the robot.
"""
self._reset_scenario()
# UI management
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = True
self._reset_btn.enabled = True
def _reset_scenario(self):
self._scenario.teardown_scenario()
self._scenario.setup_scenario(self._articulation, self._cuboid)
def _on_post_reset_btn(self):
"""
This function is attached to the Reset Button as the post_reset_fn callback.
The user may assume that their objects are properly initialized, and that the timeline is paused on timestep 0.
They may also assume that objects that were added to the World.Scene have been moved to their default positions.
I.e. the cube prim will move back to the position it was in when it was created in self._setup_scene().
"""
self._reset_scenario()
# UI management
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = True
def _update_scenario(self, step: float):
"""This function is attached to the Run Scenario StateButton.
This function was passed in as the physics_callback_fn argument.
This means that when the a_text "RUN" is pressed, a subscription is made to call this function on every physics step.
When the b_text "STOP" is pressed, the physics callback is removed.
Args:
step (float): The dt of the current physics step
"""
self._scenario.update_scenario(step)
def _on_run_scenario_a_text(self):
"""
This function is attached to the Run Scenario StateButton.
This function was passed in as the on_a_click_fn argument.
It is called when the StateButton is clicked while saying a_text "RUN".
This function simply plays the timeline, which means that physics steps will start happening. After the world is loaded or reset,
the timeline is paused, which means that no physics steps will occur until the user makes it play either programmatically or
through the left-hand UI toolbar.
"""
self._timeline.play()
def _on_run_scenario_b_text(self):
"""
This function is attached to the Run Scenario StateButton.
This function was passed in as the on_b_click_fn argument.
It is called when the StateButton is clicked while saying a_text "STOP"
Pausing the timeline on b_text is not strictly necessary for this example to run.
Clicking "STOP" will cancel the physics subscription that updates the scenario, which means that
the robot will stop getting new commands and the cube will stop updating without needing to
pause at all. The reason that the timeline is paused here is to prevent the robot being carried
forward by momentum for a few frames after the physics subscription is canceled. Pausing here makes
this example prettier, but if curious, the user should observe what happens when this line is removed.
"""
self._timeline.pause()
def _reset_extension(self):
"""This is called when the user opens a new stage from self.on_stage_event().
All state should be reset.
"""
self._on_init()
self._reset_ui()
def _reset_ui(self):
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = False
self._reset_btn.enabled = False
| 12,160 | Python | 43.874539 | 138 | 0.6375 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template extension creates a Load, Reset, and Run button in a simple UI.
The Load and Reset buttons interact with the omni.isaac.core World() in order
to simplify user interaction with the simulator and provide certain gurantees to the user
at the times their callback functions are called.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
scenario.py:
This file contains an implementation of an example "Scenario" that implements a "teardown", "setup", and "update" function.
This particular structure was chosen to make a clear code separation between UI management and the scenario logic. In this way, the
ExampleScenario() class serves as a simple backend to the UI. The user should feel encouraged to implement the backend to their UI
that best suits their needs.
| 2,078 | Markdown | 58.399998 | 137 | 0.783927 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .limo_diff_drive import LimoDiffDrive
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="LimoDiffDrive",
title="LimoDiffDrive",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LimoDiffDrive(),
)
return
| 2,055 | Python | 41.833332 | 135 | 0.740633 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/limo_diff_drive.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.wheeled_robots.controllers import WheelBasePoseController
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController
import numpy as np
import carb
class LimoDiffDrive(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
# self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_base.usd"
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_diff_thin.usd"
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
# Reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html?highlight=wheeledrobot#omni.isaac.wheeled_robots.robots.WheeledRobot
self._wheeled_robot = world.scene.add(
WheeledRobot(
prim_path="/World/Limo/base_link",
name="my_limo",
# Caution. Those are DOF "Joints", Not "Links"
wheel_dof_names=[
"front_left_wheel",
"front_right_wheel",
"rear_left_wheel",
"rear_right_wheel",
],
create_robot=False,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
return
async def setup_post_load(self):
self._world = self.get_world()
# Reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html?highlight=differentialcontroller
self._diff_controller = DifferentialController(
name="simple_control",
wheel_radius=0.045,
# Caution. This will not be the same with a real wheelbase for 4WD cases.
# Reference : https://forums.developer.nvidia.com/t/how-to-drive-clearpath-jackal-via-ros2-messages-in-isaac-sim/275907/4
wheel_base=0.43
)
self._diff_controller.reset()
self._wheeled_robot.initialize()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
wheel_action = None
# linear X, angular Z commands
if self._save_count >= 0 and self._save_count < 150:
wheel_action = self._diff_controller.forward(command=[0.3, 0.0])
elif self._save_count >= 150 and self._save_count < 300:
wheel_action = self._diff_controller.forward(command=[-0.3, 0.0])
elif self._save_count >= 300 and self._save_count < 450:
wheel_action = self._diff_controller.forward(command=[0.0, 0.3])
elif self._save_count >= 450 and self._save_count < 600:
wheel_action = self._diff_controller.forward(command=[0.0, -0.3])
else:
self._save_count = 0
wheel_action.joint_velocities = np.hstack((wheel_action.joint_velocities, wheel_action.joint_velocities))
self._wheeled_robot.apply_wheel_actions(wheel_action)
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._save_count = 0
self._world.pause()
return
async def setup_post_reset(self):
self._diff_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 5,079 | Python | 39.64 | 196 | 0.6456 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiff/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .robotnik_summit import RobotnikSummit
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="RobotnikSummitO3Wheel_ROS2",
title="RobotnikSummitO3Wheel_ROS2",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=RobotnikSummit(),
)
return
| 2,083 | Python | 42.416666 | 135 | 0.743639 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/robotnik_summit.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
import carb
class RobotnikSummit(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
# wheel models referenced from : https://git.openlogisticsfoundation.org/silicon-economy/simulation-model/o3dynsimmodel
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/Collected_summit_xl_omni_four/summit_xl_omni_four.usd"
self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ])
self._wheel_positions = np.array([
[0.229, 0.235, 0.11],
[0.229, -0.235, 0.11],
[-0.229, 0.235, 0.11],
[-0.229, -0.235, 0.11],
])
self._wheel_orientations = np.array([
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
])
self._mecanum_angles = np.array([
-135.0,
-45.0,
-45.0,
-135.0,
])
self._wheel_axis = np.array([1, 0, 0])
self._up_axis = np.array([0, 0, 1])
self._targetPrim = "/World/Summit/summit_xl_base_link"
self._domain_id = 30
return
def og_setup(self):
try:
og.Controller.edit(
{"graph_path": "/ROS2HolonomicTwist", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"),
("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"),
("breakAngVel", "omni.graph.nodes.BreakVector3"),
("breakLinVel", "omni.graph.nodes.BreakVector3"),
("angvelGain", "omni.graph.nodes.ConstantDouble"),
("angvelMult", "omni.graph.nodes.Multiply"),
("linXGain", "omni.graph.nodes.ConstantDouble"),
("linXMult", "omni.graph.nodes.Multiply"),
("linYGain", "omni.graph.nodes.ConstantDouble"),
("linYMult", "omni.graph.nodes.Multiply"),
("velVec3", "omni.graph.nodes.MakeVector3"),
("mecanumAng", "omni.graph.nodes.ConstructArray"),
("holonomicCtrl", "omni.isaac.wheeled_robots.HolonomicController"),
("upAxis", "omni.graph.nodes.ConstantDouble3"),
("wheelAxis", "omni.graph.nodes.ConstantDouble3"),
("wheelOrientation", "omni.graph.nodes.ConstructArray"),
("wheelPosition", "omni.graph.nodes.ConstructArray"),
("wheelRadius", "omni.graph.nodes.ConstructArray"),
("jointNames", "omni.graph.nodes.ConstructArray"),
("articulation", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("subscribeTwist.inputs:topicName", "cmd_vel"),
("angvelGain.inputs:value", -0.514),
("linXGain.inputs:value", 2.325),
("linYGain.inputs:value", 3.0),
("mecanumAng.inputs:arraySize", 4),
("mecanumAng.inputs:arrayType", "double[]"),
("mecanumAng.inputs:input0", self._mecanum_angles[0]),
("mecanumAng.inputs:input1", self._mecanum_angles[1]),
("mecanumAng.inputs:input2", self._mecanum_angles[2]),
("mecanumAng.inputs:input3", self._mecanum_angles[3]),
("holonomicCtrl.inputs:angularGain", 1.0),
("holonomicCtrl.inputs:linearGain", 1.0),
("holonomicCtrl.inputs:maxWheelSpeed", 1200.0),
("upAxis.inputs:value", self._up_axis),
("wheelAxis.inputs:value", self._wheel_axis),
("wheelOrientation.inputs:arraySize", 4),
("wheelOrientation.inputs:arrayType", "double[4][]"),
("wheelOrientation.inputs:input0", self._wheel_orientations[0]),
("wheelOrientation.inputs:input1", self._wheel_orientations[1]),
("wheelOrientation.inputs:input2", self._wheel_orientations[2]),
("wheelOrientation.inputs:input3", self._wheel_orientations[3]),
("wheelPosition.inputs:arraySize", 4),
("wheelPosition.inputs:arrayType", "double[3][]"),
("wheelPosition.inputs:input0", self._wheel_positions[0]),
("wheelPosition.inputs:input1", self._wheel_positions[1]),
("wheelPosition.inputs:input2", self._wheel_positions[2]),
("wheelPosition.inputs:input3", self._wheel_positions[3]),
("wheelRadius.inputs:arraySize", 4),
("wheelRadius.inputs:arrayType", "double[]"),
("wheelRadius.inputs:input0", self._wheel_radius[0]),
("wheelRadius.inputs:input1", self._wheel_radius[1]),
("wheelRadius.inputs:input2", self._wheel_radius[2]),
("wheelRadius.inputs:input3", self._wheel_radius[3]),
("jointNames.inputs:arraySize", 4),
("jointNames.inputs:arrayType", "token[]"),
("jointNames.inputs:input0", "fl_joint"),
("jointNames.inputs:input1", "fr_joint"),
("jointNames.inputs:input2", "rl_joint"),
("jointNames.inputs:input3", "rr_joint"),
("articulation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulation.inputs:robotPath", self._targetPrim),
("articulation.inputs:usePath", False),
],
og.Controller.Keys.CREATE_ATTRIBUTES: [
("mecanumAng.inputs:input1", "double"),
("mecanumAng.inputs:input2", "double"),
("mecanumAng.inputs:input3", "double"),
("wheelOrientation.inputs:input1", "double[4]"),
("wheelOrientation.inputs:input2", "double[4]"),
("wheelOrientation.inputs:input3", "double[4]"),
("wheelPosition.inputs:input1", "double[3]"),
("wheelPosition.inputs:input2", "double[3]"),
("wheelPosition.inputs:input3", "double[3]"),
("wheelRadius.inputs:input1", "double"),
("wheelRadius.inputs:input2", "double"),
("wheelRadius.inputs:input3", "double"),
("jointNames.inputs:input1", "token"),
("jointNames.inputs:input2", "token"),
("jointNames.inputs:input3", "token"),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"),
("context.outputs:context", "subscribeTwist.inputs:context"),
("subscribeTwist.outputs:angularVelocity", "breakAngVel.inputs:tuple"),
("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"),
("scaleToFromStage.outputs:result", "breakLinVel.inputs:tuple"),
("breakAngVel.outputs:z", "angvelMult.inputs:a"),
("angvelGain.inputs:value", "angvelMult.inputs:b"),
("breakLinVel.outputs:x", "linXMult.inputs:a"),
("linXGain.inputs:value", "linXMult.inputs:b"),
("breakLinVel.outputs:y", "linYMult.inputs:a"),
("linYGain.inputs:value", "linYMult.inputs:b"),
("angvelMult.outputs:product", "velVec3.inputs:z"),
("linXMult.outputs:product", "velVec3.inputs:x"),
("linYMult.outputs:product", "velVec3.inputs:y"),
("onPlaybackTick.outputs:tick", "holonomicCtrl.inputs:execIn"),
("velVec3.outputs:tuple", "holonomicCtrl.inputs:velocityCommands"),
("mecanumAng.outputs:array", "holonomicCtrl.inputs:mecanumAngles"),
("onPlaybackTick.outputs:tick", "holonomicCtrl.inputs:execIn"),
("upAxis.inputs:value", "holonomicCtrl.inputs:upAxis"),
("wheelAxis.inputs:value", "holonomicCtrl.inputs:wheelAxis"),
("wheelOrientation.outputs:array", "holonomicCtrl.inputs:wheelOrientations"),
("wheelPosition.outputs:array", "holonomicCtrl.inputs:wheelPositions"),
("wheelRadius.outputs:array", "holonomicCtrl.inputs:wheelRadius"),
("onPlaybackTick.outputs:tick", "articulation.inputs:execIn"),
("holonomicCtrl.outputs:jointVelocityCommand", "articulation.inputs:velocityCommand"),
("jointNames.outputs:array", "articulation.inputs:jointNames"),
],
},
)
og.Controller.edit(
{"graph_path": "/ROS2Odom", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._targetPrim)]),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"),
("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"),
("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"),
("context.outputs:context", "publishOdom.inputs:context"),
("context.outputs:context", "publishRawTF.inputs:context"),
("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"),
("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"),
("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"),
("computeOdom.outputs:position", "publishOdom.inputs:position"),
("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"),
("computeOdom.outputs:position", "publishRawTF.inputs:translation"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit")
self._wheeled_robot = WheeledRobot(
prim_path=self._targetPrim,
name="my_summit",
wheel_dof_names=[
"fl_joint",
"fr_joint",
"rl_joint",
"rr_joint",
],
create_robot=True,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._wheeled_robot.initialize()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 14,872 | Python | 50.642361 | 132 | 0.53315 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3WheelROS2/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .limo_diff_drive import LimoDiffDrive
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="LimoDiffDrive_ROS2",
title="LimoDiffDrive_ROS2",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LimoDiffDrive(),
)
return
| 2,065 | Python | 42.041666 | 135 | 0.74092 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/limo_diff_drive.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
import carb
class LimoDiffDrive(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
# self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_base.usd"
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_diff_thin.usd"
self._domain_id = 30
self._maxLinearSpeed = 1e6
self._wheelDistance = 0.43
self._wheelRadius = 0.045
self._front_jointNames = ["rear_left_wheel", "rear_right_wheel"]
self._rear_jointNames = ["front_left_wheel", "front_right_wheel"]
self._contorl_targetPrim = "/World/Limo/base_link"
self._odom_targetPrim = "/World/Limo/base_footprint"
return
def og_setup(self):
try:
# OG reference : https://docs.omniverse.nvidia.com/isaacsim/latest/ros2_tutorials/tutorial_ros2_drive_turtlebot.html
og.Controller.edit(
{"graph_path": "/ROS2DiffDrive", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"),
("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"),
("breakLinVel", "omni.graph.nodes.BreakVector3"),
("breakAngVel", "omni.graph.nodes.BreakVector3"),
("diffController", "omni.isaac.wheeled_robots.DifferentialController"),
("artControllerRear", "omni.isaac.core_nodes.IsaacArticulationController"),
("artControllerFront", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("diffController.inputs:maxLinearSpeed", self._maxLinearSpeed),
("diffController.inputs:wheelDistance", self._wheelDistance),
("diffController.inputs:wheelRadius", self._wheelRadius),
("artControllerRear.inputs:jointNames", self._front_jointNames),
("artControllerRear.inputs:targetPrim", [usdrt.Sdf.Path(self._contorl_targetPrim)]),
("artControllerRear.inputs:usePath", False),
("artControllerFront.inputs:jointNames", self._rear_jointNames),
("artControllerFront.inputs:targetPrim", [usdrt.Sdf.Path(self._contorl_targetPrim)]),
("artControllerFront.inputs:usePath", False),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"),
("onPlaybackTick.outputs:tick", "artControllerRear.inputs:execIn"),
("onPlaybackTick.outputs:tick", "artControllerFront.inputs:execIn"),
("context.outputs:context", "subscribeTwist.inputs:context"),
("subscribeTwist.outputs:execOut", "diffController.inputs:execIn"),
("subscribeTwist.outputs:angularVelocity", "breakAngVel.inputs:tuple"),
("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"),
("scaleToFromStage.outputs:result", "breakLinVel.inputs:tuple"),
("breakAngVel.outputs:z", "diffController.inputs:angularVelocity"),
("breakLinVel.outputs:x", "diffController.inputs:linearVelocity"),
("diffController.outputs:velocityCommand", "artControllerRear.inputs:velocityCommand"),
("diffController.outputs:velocityCommand", "artControllerFront.inputs:velocityCommand"),
],
},
)
# OG reference : https://docs.omniverse.nvidia.com/isaacsim/latest/ros2_tutorials/tutorial_ros2_tf.html
og.Controller.edit(
{"graph_path": "/ROS2Odom", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._odom_targetPrim)]),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"),
("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"),
("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"),
("context.outputs:context", "publishOdom.inputs:context"),
("context.outputs:context", "publishRawTF.inputs:context"),
("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"),
("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"),
("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"),
("computeOdom.outputs:position", "publishOdom.inputs:position"),
("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"),
("computeOdom.outputs:position", "publishRawTF.inputs:translation"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
self._save_count = 0
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 8,504 | Python | 52.15625 | 128 | 0.589135 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoDiffROS2/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .kaya_robot import KayaRobot
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="KayaRobot",
title="KayaRobot",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=KayaRobot(),
)
return
| 2,034 | Python | 41.395832 | 135 | 0.738446 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/kaya_robot.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
from omni.isaac.wheeled_robots.robots.holonomic_robot_usd_setup import HolonomicRobotUsdSetup
import numpy as np
class KayaRobot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
assets_root_path = get_assets_root_path()
kaya_asset_path = assets_root_path + "/Isaac/Robots/Kaya/kaya.usd"
self._wheeled_robot = world.scene.add(
WheeledRobot(
prim_path="/World/Kaya",
name="my_kaya",
wheel_dof_names=["axle_0_joint", "axle_1_joint", "axle_2_joint"],
create_robot=True,
usd_path=kaya_asset_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
self._save_count = 0
return
async def setup_post_load(self):
self._world = self.get_world()
kaya_setup = HolonomicRobotUsdSetup(
robot_prim_path=self._wheeled_robot.prim_path, com_prim_path="/World/Kaya/base_link/control_offset"
)
(
wheel_radius,
wheel_positions,
wheel_orientations,
mecanum_angles,
wheel_axis,
up_axis,
) = kaya_setup.get_holonomic_controller_params()
self._holonomic_controller = HolonomicController(
name="holonomic_controller",
wheel_radius=wheel_radius,
wheel_positions=wheel_positions,
wheel_orientations=wheel_orientations,
mecanum_angles=mecanum_angles,
wheel_axis=wheel_axis,
up_axis=up_axis,
)
print("wheel_radius : ", wheel_radius)
print("wheel_positions : ", wheel_positions)
print("wheel_orientations : ", wheel_orientations)
print("mecanum_angles : ", mecanum_angles)
print("wheel_axis : ", wheel_axis)
print("up_axis : ", up_axis)
self._holonomic_controller.reset()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
wheel_action = None
if self._save_count >= 0 and self._save_count < 300:
wheel_action = self._holonomic_controller.forward(command=[0.5, 0.0, 0.0])
elif self._save_count >= 300 and self._save_count < 600:
wheel_action = self._holonomic_controller.forward(command=[-0.5, 0.0, 0.0])
elif self._save_count >= 600 and self._save_count < 900:
wheel_action = self._holonomic_controller.forward(command=[0.0, 0.5, 0.0])
elif self._save_count >= 900 and self._save_count < 1200:
wheel_action = self._holonomic_controller.forward(command=[0.0, -0.5, 0.0])
elif self._save_count >= 1200 and self._save_count < 1500:
wheel_action = self._holonomic_controller.forward(command=[0.0, 0.0, 0.2])
elif self._save_count >= 1500 and self._save_count < 1800:
wheel_action = self._holonomic_controller.forward(command=[0.0, 0.0, -0.2])
else:
self._save_count = 0
self._wheeled_robot.apply_wheel_actions(wheel_action)
return | 4,150 | Python | 37.435185 | 111 | 0.62241 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotsKaya/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .limo_ackermann import LimoAckermann
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="LimoAckermann_ROS2_Twist",
title="LimoAckermann_ROS2_Twist",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LimoAckermann(),
)
return
| 2,076 | Python | 42.270832 | 135 | 0.741811 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/limo_ackermann.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
import carb
class LimoAckermann(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_ackermann.usd"
self._domain_id = 30
self._maxWheelRotation = 1e6
self._maxWheelVelocity = 1e6
self._trackWidth = 0.13
self._turningWheelRadius = 0.045
self._wheelBase = 0.2
self._targetPrim = "/World/Limo/base_link"
self._robotPath = "/World/Limo/base_link"
return
def og_setup(self):
try:
# reference for message conversion : https://dingyan89.medium.com/simple-understanding-of-kinematic-bicycle-model-81cac6420357
og.Controller.edit(
{"graph_path": "/ROS2Ackermann", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"),
("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"),
("angVelBreak", "omni.graph.nodes.BreakVector3"),
("linVelBreak", "omni.graph.nodes.BreakVector3"),
("wheelbase", "omni.graph.nodes.ConstantDouble"),
("multiply", "omni.graph.nodes.Multiply"),
("atan2", "omni.graph.nodes.ATan2"),
("toRad", "omni.graph.nodes.ToRad"),
("ackermannCtrl", "omni.isaac.wheeled_robots.AckermannSteering"),
("wheelJointNames", "omni.graph.nodes.ConstructArray"),
("wheelRotationVel", "omni.graph.nodes.ConstructArray"),
("hingeJointNames", "omni.graph.nodes.ConstructArray"),
("hingePosVel", "omni.graph.nodes.ConstructArray"),
("articulationRotation", "omni.isaac.core_nodes.IsaacArticulationController"),
("articulationPosition", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("subscribeTwist.inputs:topicName", "cmd_vel"),
("wheelbase.inputs:value", self._wheelBase),
("ackermannCtrl.inputs:maxWheelRotation", self._maxWheelRotation),
("ackermannCtrl.inputs:maxWheelVelocity", self._maxWheelVelocity),
("ackermannCtrl.inputs:trackWidth", self._trackWidth),
("ackermannCtrl.inputs:turningWheelRadius", self._turningWheelRadius),
("ackermannCtrl.inputs:useAcceleration", False),
("wheelJointNames.inputs:arraySize", 4),
("wheelJointNames.inputs:arrayType", "token[]"),
("wheelJointNames.inputs:input0", "rear_left_wheel"),
("wheelJointNames.inputs:input1", "rear_right_wheel"),
("wheelJointNames.inputs:input2", "front_left_wheel"),
("wheelJointNames.inputs:input3", "front_right_wheel"),
("hingeJointNames.inputs:arraySize", 2),
("hingeJointNames.inputs:arrayType", "token[]"),
("hingeJointNames.inputs:input0", "left_steering_hinge_wheel"),
("hingeJointNames.inputs:input1", "right_steering_hinge_wheel"),
("wheelRotationVel.inputs:arraySize", 4),
("wheelRotationVel.inputs:arrayType", "double[]"),
("hingePosVel.inputs:arraySize", 2),
("hingePosVel.inputs:arrayType", "double[]"),
("articulationRotation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulationRotation.inputs:robotPath", self._targetPrim),
("articulationRotation.inputs:usePath", False),
("articulationPosition.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulationPosition.inputs:robotPath", self._targetPrim),
("articulationPosition.inputs:usePath", False),
],
og.Controller.Keys.CREATE_ATTRIBUTES: [
("wheelJointNames.inputs:input1", "token"),
("wheelJointNames.inputs:input2", "token"),
("wheelJointNames.inputs:input3", "token"),
("hingeJointNames.inputs:input1", "token"),
("wheelRotationVel.inputs:input1", "double"),
("wheelRotationVel.inputs:input2", "double"),
("wheelRotationVel.inputs:input3", "double"),
("hingePosVel.inputs:input1", "double"),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"),
("context.outputs:context", "subscribeTwist.inputs:context"),
("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"),
("scaleToFromStage.outputs:result", "linVelBreak.inputs:tuple"),
("subscribeTwist.outputs:angularVelocity", "angVelBreak.inputs:tuple"),
("subscribeTwist.outputs:execOut", "ackermannCtrl.inputs:execIn"),
("angVelBreak.outputs:z", "multiply.inputs:a"),
("linVelBreak.outputs:x", "ackermannCtrl.inputs:speed"),
("wheelbase.inputs:value", "multiply.inputs:b"),
("wheelbase.inputs:value", "ackermannCtrl.inputs:wheelBase"),
("multiply.outputs:product", "atan2.inputs:a"),
("linVelBreak.outputs:x", "atan2.inputs:b"),
("atan2.outputs:result", "toRad.inputs:degrees"),
("toRad.outputs:radians", "ackermannCtrl.inputs:steeringAngle"),
("ackermannCtrl.outputs:leftWheelAngle", "hingePosVel.inputs:input0"),
("ackermannCtrl.outputs:rightWheelAngle", "hingePosVel.inputs:input1"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input0"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input1"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input2"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input3"),
("ackermannCtrl.outputs:execOut", "articulationRotation.inputs:execIn"),
("wheelJointNames.outputs:array", "articulationRotation.inputs:jointNames"),
("wheelRotationVel.outputs:array", "articulationRotation.inputs:velocityCommand"),
("ackermannCtrl.outputs:execOut", "articulationPosition.inputs:execIn"),
("hingeJointNames.outputs:array", "articulationPosition.inputs:jointNames"),
("hingePosVel.outputs:array", "articulationPosition.inputs:positionCommand"),
],
},
)
og.Controller.edit(
{"graph_path": "/ROS2Odom", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._targetPrim)]),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"),
("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"),
("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"),
("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"),
("context.outputs:context", "publishOdom.inputs:context"),
("context.outputs:context", "publishRawTF.inputs:context"),
("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"),
("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"),
("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"),
("computeOdom.outputs:position", "publishOdom.inputs:position"),
("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"),
("computeOdom.outputs:position", "publishRawTF.inputs:translation"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
self._save_count = 0
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 12,210 | Python | 56.599056 | 138 | 0.569943 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannTwistROS2/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .robotnik_summit import RobotnikSummit
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="RobotnikSummitO3Wheel",
title="RobotnikSummitO3Wheel",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=RobotnikSummit(),
)
return
| 2,073 | Python | 42.208332 | 135 | 0.743367 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/robotnik_summit.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import numpy as np
import carb
class RobotnikSummit(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
# wheel models referenced from : https://git.openlogisticsfoundation.org/silicon-economy/simulation-model/o3dynsimmodel
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/Collected_summit_xl_omni_four/summit_xl_omni_four.usd"
self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ])
self._wheel_positions = np.array([
[0.229, 0.235, 0.11],
[0.229, -0.235, 0.11],
[-0.229, 0.235, 0.11],
[-0.229, -0.235, 0.11],
])
self._wheel_orientations = np.array([
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
])
self._mecanum_angles = np.array([
-135.0,
-45.0,
-45.0,
-135.0,
])
self._wheel_axis = np.array([1, 0, 0])
self._up_axis = np.array([0, 0, 1])
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit")
self._wheeled_robot = WheeledRobot(
prim_path="/World/Summit/summit_xl_base_link",
name="my_summit",
wheel_dof_names=[
"fl_joint",
"fr_joint",
"rl_joint",
"rr_joint",
],
create_robot=True,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
return
async def setup_post_load(self):
self._world = self.get_world()
self._summit_controller = HolonomicController(
name="holonomic_controller",
wheel_radius=self._wheel_radius,
wheel_positions=self._wheel_positions,
wheel_orientations=self._wheel_orientations,
mecanum_angles=self._mecanum_angles,
wheel_axis=self._wheel_axis,
up_axis=self._up_axis,
)
self._summit_controller.reset()
self._wheeled_robot.initialize()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
wheel_action = None
if self._save_count >= 0 and self._save_count < 150:
wheel_action = self._summit_controller.forward(command=[0.5, 0.0, 0.0])
elif self._save_count >= 150 and self._save_count < 300:
wheel_action = self._summit_controller.forward(command=[-0.5, 0.0, 0.0])
elif self._save_count >= 300 and self._save_count < 450:
wheel_action = self._summit_controller.forward(command=[0.0, 0.5, 0.0])
elif self._save_count >= 450 and self._save_count < 600:
wheel_action = self._summit_controller.forward(command=[0.0, -0.5, 0.0])
elif self._save_count >= 600 and self._save_count < 750:
wheel_action = self._summit_controller.forward(command=[0.0, 0.0, 0.3])
elif self._save_count >= 750 and self._save_count < 900:
wheel_action = self._summit_controller.forward(command=[0.0, 0.0, -0.3])
else:
self._save_count = 0
self._wheeled_robot.apply_wheel_actions(wheel_action)
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 5,294 | Python | 36.821428 | 132 | 0.604836 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummitO3Wheel/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .limo_ackermann import LimoAckermann
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="LimoAckermann_ROS2_Ackermann",
title="LimoAckermann_ROS2_Ackermann",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LimoAckermann(),
)
return
| 2,084 | Python | 42.437499 | 135 | 0.742802 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/limo_ackermann.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
import carb
class LimoAckermann(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_ackermann.usd"
self._domain_id = 30
self._maxWheelRotation = 1e6
self._maxWheelVelocity = 1e6
self._trackWidth = 0.13
self._turningWheelRadius = 0.045
self._wheelBase = 0.2
self._targetPrim = "/World/Limo/base_footprint"
self._robotPath = "/World/Limo/base_footprint"
return
def og_setup(self):
try:
# AckermannSteering reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html#ackermannsteering
og.Controller.edit(
{"graph_path": "/ROS2Ackermann", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("subscribeAckermann", "omni.isaac.ros2_bridge.ROS2SubscribeAckermannDrive"),
("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"),
("ackermannCtrl", "omni.isaac.wheeled_robots.AckermannSteering"),
("wheelJointNames", "omni.graph.nodes.ConstructArray"),
("wheelRotationVel", "omni.graph.nodes.ConstructArray"),
("hingeJointNames", "omni.graph.nodes.ConstructArray"),
("hingePosVel", "omni.graph.nodes.ConstructArray"),
("articulationRotation", "omni.isaac.core_nodes.IsaacArticulationController"),
("articulationPosition", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("subscribeAckermann.inputs:topicName", "ackermann_cmd"),
("ackermannCtrl.inputs:maxWheelRotation", self._maxWheelRotation),
("ackermannCtrl.inputs:maxWheelVelocity", self._maxWheelVelocity),
("ackermannCtrl.inputs:trackWidth", self._trackWidth),
("ackermannCtrl.inputs:turningWheelRadius", self._turningWheelRadius),
("ackermannCtrl.inputs:useAcceleration", False),
("ackermannCtrl.inputs:wheelBase", self._wheelBase),
("wheelJointNames.inputs:arraySize", 4),
("wheelJointNames.inputs:arrayType", "token[]"),
("wheelJointNames.inputs:input0", "rear_left_wheel"),
("wheelJointNames.inputs:input1", "rear_right_wheel"),
("wheelJointNames.inputs:input2", "front_left_wheel"),
("wheelJointNames.inputs:input3", "front_right_wheel"),
("hingeJointNames.inputs:arraySize", 2),
("hingeJointNames.inputs:arrayType", "token[]"),
("hingeJointNames.inputs:input0", "left_steering_hinge_wheel"),
("hingeJointNames.inputs:input1", "right_steering_hinge_wheel"),
("wheelRotationVel.inputs:arraySize", 4),
("wheelRotationVel.inputs:arrayType", "double[]"),
("hingePosVel.inputs:arraySize", 2),
("hingePosVel.inputs:arrayType", "double[]"),
("articulationRotation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulationRotation.inputs:robotPath", self._robotPath),
("articulationRotation.inputs:usePath", False),
("articulationPosition.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulationPosition.inputs:robotPath", self._robotPath),
("articulationPosition.inputs:usePath", False),
],
og.Controller.Keys.CREATE_ATTRIBUTES: [
("wheelJointNames.inputs:input1", "token"),
("wheelJointNames.inputs:input2", "token"),
("wheelJointNames.inputs:input3", "token"),
("hingeJointNames.inputs:input1", "token"),
("wheelRotationVel.inputs:input1", "double"),
("wheelRotationVel.inputs:input2", "double"),
("wheelRotationVel.inputs:input3", "double"),
("hingePosVel.inputs:input1", "double"),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "subscribeAckermann.inputs:execIn"),
("context.outputs:context", "subscribeAckermann.inputs:context"),
("subscribeAckermann.outputs:speed", "scaleToFromStage.inputs:value"),
("subscribeAckermann.outputs:execOut", "ackermannCtrl.inputs:execIn"),
("scaleToFromStage.outputs:result", "ackermannCtrl.inputs:speed"),
("subscribeAckermann.outputs:steeringAngle", "ackermannCtrl.inputs:steeringAngle"),
("ackermannCtrl.outputs:leftWheelAngle", "hingePosVel.inputs:input0"),
("ackermannCtrl.outputs:rightWheelAngle", "hingePosVel.inputs:input1"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input0"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input1"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input2"),
("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input3"),
("ackermannCtrl.outputs:execOut", "articulationRotation.inputs:execIn"),
("wheelJointNames.outputs:array", "articulationRotation.inputs:jointNames"),
("wheelRotationVel.outputs:array", "articulationRotation.inputs:velocityCommand"),
("ackermannCtrl.outputs:execOut", "articulationPosition.inputs:execIn"),
("hingeJointNames.outputs:array", "articulationPosition.inputs:jointNames"),
("hingePosVel.outputs:array", "articulationPosition.inputs:positionCommand"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
self._save_count = 0
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 9,065 | Python | 51.709302 | 167 | 0.588969 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotLimoAckermannROS2/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/global_variables.py | # Copyright (c) 2022-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.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 | Python | 36.923074 | 76 | 0.802846 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/extension.py | # Copyright (c) 2022-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 os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .robotnik_summit import RobotnikSummit
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RBWheeledRobotExample",
submenu_name="",
name="RobotnikSummit",
title="RobotnikSummit",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=RobotnikSummit(),
)
return
| 2,059 | Python | 41.916666 | 135 | 0.741622 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/__init__.py | # Copyright (c) 2022-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.
#
from .extension import Extension
| 464 | Python | 45.499995 | 76 | 0.814655 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/ui_builder.py | # Copyright (c) 2022-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 os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 | Python | 38.888889 | 112 | 0.542178 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/robotnik_summit.py | # Copyright (c) 2020-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.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import numpy as np
import carb
class RobotnikSummit(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/summit_xl_original.usd"
self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ])
self._wheel_positions = np.array([
[0.229, 0.235, 0.11],
[0.229, -0.235, 0.11],
[-0.229, 0.235, 0.11],
[-0.229, -0.235, 0.11],
])
self._wheel_orientations = np.array([
# w, x, y, z
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, 0.7071068],
])
self._mecanum_angles = np.array([
-135.0,
-45.0,
-45.0,
-135.0,
])
self._wheel_axis = np.array([1, 0, 0])
self._up_axis = np.array([0, 0, 1])
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit")
self._wheeled_robot = WheeledRobot(
prim_path="/World/Summit/summit_xl_base_link",
name="my_summit",
wheel_dof_names=[
"summit_xl_front_left_wheel_joint",
"summit_xl_front_right_wheel_joint",
"summit_xl_back_left_wheel_joint",
"summit_xl_back_right_wheel_joint",
],
create_robot=True,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
return
async def setup_post_load(self):
self._world = self.get_world()
self._summit_controller = HolonomicController(
name="holonomic_controller",
wheel_radius=self._wheel_radius,
wheel_positions=self._wheel_positions,
wheel_orientations=self._wheel_orientations,
mecanum_angles=self._mecanum_angles,
wheel_axis=self._wheel_axis,
up_axis=self._up_axis,
)
self._summit_controller.reset()
self._wheeled_robot.initialize()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
wheel_action = None
if self._save_count >= 0 and self._save_count < 150:
wheel_action = self._summit_controller.forward(command=[0.5, 0.0, 0.0])
elif self._save_count >= 150 and self._save_count < 300:
wheel_action = self._summit_controller.forward(command=[-0.5, 0.0, 0.0])
elif self._save_count >= 300 and self._save_count < 450:
wheel_action = self._summit_controller.forward(command=[0.0, 0.5, 0.0])
elif self._save_count >= 450 and self._save_count < 600:
wheel_action = self._summit_controller.forward(command=[0.0, -0.5, 0.0])
elif self._save_count >= 600 and self._save_count < 750:
wheel_action = self._summit_controller.forward(command=[0.0, 0.0, 0.5])
elif self._save_count >= 750 and self._save_count < 900:
wheel_action = self._summit_controller.forward(command=[0.0, 0.0, -0.5])
else:
self._save_count = 0
self._wheeled_robot.apply_wheel_actions(wheel_action)
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._world.pause()
return
async def setup_post_reset(self):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return | 5,254 | Python | 36.535714 | 101 | 0.601447 |
Road-Balance/RB_WheeledRobotExample/RBWheeledRobotExample_python/WheeledRobotSummit/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification. | 1,488 | Markdown | 58.559998 | 132 | 0.793011 |
Road-Balance/RB_WheeledRobotExample/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
title = "RBWheeledRobotExample"
description = ""
authors = ["NVIDIA"]
repository = ""
keywords = []
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.uiapp" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotLimoDiff"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotLimoDiffROS2"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotLimoAckermannROS2"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotLimoAckermannTwistROS2"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotsKaya"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotSummit"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotSummitO3Wheel"
[[python.module]]
name = "RBWheeledRobotExample_python.WheeledRobotSummitO3WheelROS2"
| 1,047 | TOML | 21.297872 | 72 | 0.762178 |
Road-Balance/RB_WheeledRobotExample/docs/CHANGELOG.md | # Changelog
## [0.1.0] - 2024-05-14
### Added
- Initial version of RBWheeledRobotExample Extension
| 102 | Markdown | 11.874999 | 52 | 0.696078 |
Road-Balance/RB_WheeledRobotExample/docs/README.md | # Usage
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
| 129 | Markdown | 24.999995 | 118 | 0.736434 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/README.md | # Isaac ROS cuMotion
NVIDIA accelerated packages for arm motion planning and control
<div align="center"><a class="reference internal image-reference" href="https://media.githubusercontent.com/media/NVIDIA-ISAAC-ROS/.github/main/resources/isaac_ros_docs/repositories_and_packages/isaac_ros_cumotion/cumotion_ur10_demo.gif/"><img alt="image" src="https://media.githubusercontent.com/media/NVIDIA-ISAAC-ROS/.github/main/resources/isaac_ros_docs/repositories_and_packages/isaac_ros_cumotion/cumotion_ur10_demo.gif/" width="600px"/></a></div>
## Overview
[Isaac ROS cuMotion](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_cumotion) provides CUDA-accelerated manipulation
capabilities for robots in ROS 2, enabling faster processing speeds and real-time performance
that are crucial to complex robotics tasks such as motion planning.
It provides two main capabilities, motion generation for robot
arms via an integration of cuMotion into MoveIt 2 and segmentation of robot from depth streams
using cuMotion’s kinematics and geometry processing functions to accurately identify and filter robot parts.
This allows one to reconstruct obstacles in the environment without spurious contributions from the robot itself.
The key advantages of using Isaac ROS cuMotion are:
* Increased Efficiency: CUDA acceleration significantly speeds up processing times,
allowing for complex computation, such as collision avoidance, occurring at real-time.
* Enhanced Precision: Accurate motion planning and segmentation allow for better
performance in tasks requiring fine manipulation and detailed environmental interaction.
* Improved Flexibility: Modular design allows easy integration with existing ROS 2 setups,
such as configurations using MoveIt 2, enabling customization and scalability using familiar
tooling.
The Isaac ROS cuMotion repository currently contains the following packages:
`isaac_ros_cumotion`:
: This package contains the cuMotion planner node and the robot segmentation node.
`isaac_ros_cumotion_examples`:
: This package contains various examples demonstrating use of cuMotion with MoveIt.
`isaac_ros_cumotion_moveit`:
: This package provides a plugin for MoveIt 2 that exposes cuMotion as an external planner, leveraging `isaac_ros_cumotion`.
Isaac ROS cuMotion is also featured as part of [Isaac Manipulator](https://nvidia-isaac-ros.github.io/reference_workflows/isaac_manipulator/index.html).
---
## Documentation
Please visit the [Isaac ROS Documentation](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/index.html) to learn how to use this repository.
---
## Packages
* [`isaac_ros_cumotion`](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion/index.html)
* [Motion Generation](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion/index.html#motion-generation)
* [Robot Segmentation](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion/index.html#robot-segmentation)
* [`isaac_ros_cumotion_moveit`](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion_moveit/index.html)
* [Quickstart](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion_moveit/index.html#quickstart)
* [Try More Examples](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion_moveit/index.html#try-more-examples)
* [Troubleshooting](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_cumotion_moveit/index.html#troubleshooting)
* [`isaac_ros_esdf_visualizer`](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_esdf_visualizer/index.html)
* [Overview](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_esdf_visualizer/index.html#overview)
* [API](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_esdf_visualizer/index.html#api)
* [`isaac_ros_moveit_goal_setter`](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/index.html)
* [Overview](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/index.html#overview)
* [API](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/index.html#api)
* [`isaac_ros_moveit_goal_setter_interfaces`](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_cumotion/isaac_ros_moveit_goal_setter_interfaces/index.html)
## Latest
Update 2024-05-30: Initial release
| 4,775 | Markdown | 69.235293 | 453 | 0.802723 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_robot_description/setup.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
from glob import glob
import os
from setuptools import find_packages, setup
package_name = 'isaac_ros_cumotion_robot_description'
setup(
name=package_name,
version='3.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(
os.path.join('share', package_name, 'xrdf'),
glob(os.path.join('xrdf', '*.xrdf')),
),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Isaac ROS Maintainers',
maintainer_email='[email protected]',
description='Package containing XRDF (extended robot description format) files for '
'various robots',
license='Apache-2.0',
tests_require=['pytest'],
)
| 1,569 | Python | 33.130434 | 88 | 0.690886 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_robot_description/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
| 884 | Python | 33.03846 | 74 | 0.725113 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_robot_description/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
| 803 | Python | 32.499999 | 74 | 0.743462 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_robot_description/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_copyright.main import main
import pytest
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 790 | Python | 31.958332 | 74 | 0.74557 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/curobo_core/setup.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
from setuptools import find_namespace_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
package_name = 'curobo_core'
extra_cuda_args = {
'nvcc': [
'--threads=8',
'-O3',
'--ftz=true',
'--fmad=true',
'--prec-div=false',
'--prec-sqrt=false',
]
}
# create a list of modules to be compiled:
ext_modules = [
CUDAExtension(
'curobo.curobolib.lbfgs_step_cu',
[
'curobo/src/curobo/curobolib/cpp/lbfgs_step_cuda.cpp',
'curobo/src/curobo/curobolib/cpp/lbfgs_step_kernel.cu',
],
extra_compile_args=extra_cuda_args,
),
CUDAExtension(
'curobo.curobolib.kinematics_fused_cu',
[
'curobo/src/curobo/curobolib/cpp/kinematics_fused_cuda.cpp',
'curobo/src/curobo/curobolib/cpp/kinematics_fused_kernel.cu',
],
extra_compile_args=extra_cuda_args,
),
CUDAExtension(
'curobo.curobolib.geom_cu',
[
'curobo/src/curobo/curobolib/cpp/geom_cuda.cpp',
'curobo/src/curobo/curobolib/cpp/sphere_obb_kernel.cu',
'curobo/src/curobo/curobolib/cpp/pose_distance_kernel.cu',
'curobo/src/curobo/curobolib/cpp/self_collision_kernel.cu',
],
extra_compile_args=extra_cuda_args,
),
CUDAExtension(
'curobo.curobolib.line_search_cu',
[
'curobo/src/curobo/curobolib/cpp/line_search_cuda.cpp',
'curobo/src/curobo/curobolib/cpp/line_search_kernel.cu',
'curobo/src/curobo/curobolib/cpp/update_best_kernel.cu',
],
extra_compile_args=extra_cuda_args,
),
CUDAExtension(
'curobo.curobolib.tensor_step_cu',
[
'curobo/src/curobo/curobolib/cpp/tensor_step_cuda.cpp',
'curobo/src/curobo/curobolib/cpp/tensor_step_kernel.cu',
],
extra_compile_args=extra_cuda_args,
),
]
setup(
name=package_name,
version='3.0.0',
packages=find_namespace_packages(where='curobo/src'),
package_dir={'': 'curobo/src'},
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Isaac ROS Maintainers',
maintainer_email='[email protected]',
description='This package wraps the cuRobo library as a ROS 2 package. cuRobo serves as the current backend for cuMotion.',
license='NVIDIA Isaac ROS Software License',
tests_require=['pytest'],
entry_points={
'console_scripts': [
],
},
ext_modules=ext_modules,
cmdclass={'build_ext': BuildExtension},
package_data={
'curobo': ['**/*.*'],
},
include_package_data=True,
)
| 3,583 | Python | 32.185185 | 127 | 0.634105 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/curobo_core/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_copyright.main import main
import pytest
@pytest.mark.skip(reason='This package has a proprietary license')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 857 | Python | 33.319999 | 74 | 0.749125 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/launch/isaac_ros_goal_setter.launch.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES',
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
import launch
from launch.actions import DeclareLaunchArgument
from launch.substitutions import Command, FindExecutable, LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def get_robot_description():
ur_type = LaunchConfiguration('ur_type')
robot_ip = LaunchConfiguration('robot_ip')
joint_limit_params = PathJoinSubstitution(
[FindPackageShare('ur_description'), 'config', ur_type, 'joint_limits.yaml']
)
kinematics_params = PathJoinSubstitution(
[FindPackageShare('ur_description'), 'config', ur_type, 'default_kinematics.yaml']
)
physical_params = PathJoinSubstitution(
[FindPackageShare('ur_description'), 'config', ur_type, 'physical_parameters.yaml']
)
visual_params = PathJoinSubstitution(
[FindPackageShare('ur_description'), 'config', ur_type, 'visual_parameters.yaml']
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name='xacro')]), ' ',
PathJoinSubstitution([FindPackageShare('ur_description'), 'urdf', 'ur.urdf.xacro']),
' ', 'robot_ip:=', robot_ip,
' ', 'joint_limit_params:=', joint_limit_params,
' ', 'kinematics_params:=', kinematics_params,
' ', 'physical_params:=', physical_params,
' ', 'visual_params:=', visual_params,
' ', 'safety_limits:=true',
' ', 'safety_pos_margin:=0.15',
' ', 'safety_k_position:=20',
' ', 'name:=ur', ' ', 'ur_type:=', ur_type, ' ', 'prefix:=''',
]
)
robot_description = {'robot_description': robot_description_content}
return robot_description
def get_robot_description_semantic():
# MoveIt Configuration
robot_description_semantic_content = Command(
[
PathJoinSubstitution([FindExecutable(name='xacro')]), ' ',
PathJoinSubstitution([FindPackageShare('ur_moveit_config'), 'srdf', 'ur.srdf.xacro']),
' ', 'name:=ur', ' ', 'prefix:=""',
]
)
robot_description_semantic = {
'robot_description_semantic': robot_description_semantic_content
}
return robot_description_semantic
def generate_launch_description():
launch_args = [
DeclareLaunchArgument(
'ur_type',
description='Type/series of used UR robot.',
choices=['ur3', 'ur3e', 'ur5', 'ur5e', 'ur10', 'ur10e', 'ur16e', 'ur20'],
default_value='ur5e',
),
DeclareLaunchArgument(
'robot_ip',
description='IP address of the robot',
default_value='192.56.1.2',
),
]
moveit_kinematics_params = PathJoinSubstitution(
[FindPackageShare('ur_moveit_config'), 'config', 'default_kinematics.yaml']
)
robot_description = get_robot_description()
robot_description_semantic = get_robot_description_semantic()
isaac_ros_moveit_goal_setter = Node(
package='isaac_ros_moveit_goal_setter',
executable='isaac_ros_moveit_goal_setter',
name='isaac_ros_moveit_goal_setter',
output='screen',
parameters=[
robot_description,
robot_description_semantic,
moveit_kinematics_params
],
)
return launch.LaunchDescription(launch_args + [isaac_ros_moveit_goal_setter])
| 4,135 | Python | 36.6 | 99 | 0.643047 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/src/goal_setter_node.cpp | // SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
// Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "geometry_msgs/msg/pose_stamped.hpp"
#include "isaac_ros_moveit_goal_setter/goal_setter_node.hpp"
namespace nvidia
{
namespace isaac_ros
{
namespace manipulation
{
GoalSetterNode::GoalSetterNode(std::string name, const rclcpp::NodeOptions & options)
: node_{std::make_shared<rclcpp::Node>(name, options)},
planner_group_name_(node_->declare_parameter<std::string>(
"planner_group_name", "ur_manipulator")),
planner_id_(node_->declare_parameter<std::string>("planner_id", "cuMotion")),
end_effector_link_(node_->declare_parameter<std::string>("end_effector_link", "wrist_3_link")),
move_group_interface_{moveit::planning_interface::MoveGroupInterface(node_, planner_group_name_)}
{
set_target_pose_service_ =
node_->create_service<isaac_ros_goal_setter_interfaces::srv::SetTargetPose>(
"set_target_pose", std::bind(
&GoalSetterNode::SetTargetPoseCallback, this, std::placeholders::_1, std::placeholders::_2));
ConfigureMoveit();
}
void GoalSetterNode::ConfigureMoveit()
{
// Initialize the move group interface
move_group_interface_.setPlannerId(planner_id_);
RCLCPP_INFO(node_->get_logger(), "Planner ID : %s", move_group_interface_.getPlannerId().c_str());
move_group_interface_.setEndEffectorLink(end_effector_link_);
RCLCPP_INFO(node_->get_logger(), "End Effector Link : %s", end_effector_link_.c_str());
}
void GoalSetterNode::SetTargetPoseCallback(
const std::shared_ptr<isaac_ros_goal_setter_interfaces::srv::SetTargetPose_Request> req,
std::shared_ptr<isaac_ros_goal_setter_interfaces::srv::SetTargetPose_Response> res)
{
res->success = false;
RCLCPP_DEBUG(node_->get_logger(), "Triggered SetTargetPoseCallback");
RCLCPP_DEBUG(
node_->get_logger(), "Pose : x=%f, y=%f, z=%f, qx=%f, qy=%f, qz=%f, qw=%f",
req->pose.pose.position.x, req->pose.pose.position.y, req->pose.pose.position.z,
req->pose.pose.orientation.x, req->pose.pose.orientation.y, req->pose.pose.orientation.z,
req->pose.pose.orientation.w);
auto success = move_group_interface_.setPoseTarget(req->pose, end_effector_link_);
if (!success) {
RCLCPP_ERROR(node_->get_logger(), "Failed to set target pose!");
return;
}
auto const [status, plan] = [this] {
moveit::planning_interface::MoveGroupInterface::Plan msg;
auto const ok = static_cast<bool>(move_group_interface_.plan(msg));
return std::make_pair(ok, msg);
}();
// Execute the plan
if (status) {
RCLCPP_ERROR(node_->get_logger(), "Executing!");
move_group_interface_.execute(plan);
res->success = true;
} else {
RCLCPP_ERROR(node_->get_logger(), "Planning failed!");
}
}
} // namespace manipulation
} // namespace isaac_ros
} // namespace nvidia
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto goal_setter_node = std::make_shared<nvidia::isaac_ros::manipulation::GoalSetterNode>(
"moveit_goal_setter",
rclcpp::NodeOptions().automatically_declare_parameters_from_overrides(true));
rclcpp::executors::MultiThreadedExecutor executor;
executor.add_node(goal_setter_node->GetNode());
executor.spin();
rclcpp::shutdown();
return 0;
}
| 3,877 | C++ | 35.933333 | 100 | 0.708538 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/scripts/pose_to_pose.py | #!/usr/bin/env python3
# SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES',
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
import time
from geometry_msgs.msg import Pose, PoseStamped
from isaac_ros_goal_setter_interfaces.srv import SetTargetPose
import rclpy
from rclpy.callback_groups import MutuallyExclusiveCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from tf2_ros import TransformException
from tf2_ros.buffer import Buffer
from tf2_ros.transform_listener import TransformListener
class PoseToPoseNode(Node):
def __init__(self):
super().__init__('pose_to_pose_node')
self._world_frame = self.declare_parameter(
'world_frame', 'base_link').get_parameter_value().string_value
self._target_frames = self.declare_parameter(
'target_frames', ['target1_frame']).get_parameter_value().string_array_value
self._target_frame_idx = 0
self._plan_timer_period = self.declare_parameter(
'plan_timer_period', 0.01).get_parameter_value().double_value
self._tf_buffer = Buffer(cache_time=rclpy.duration.Duration(seconds=60.0))
self._tf_listener = TransformListener(self._tf_buffer, self)
self._goal_service_cb_group = MutuallyExclusiveCallbackGroup()
self._goal_client = self.create_client(
SetTargetPose, 'set_target_pose', callback_group=self._goal_service_cb_group)
while not self._goal_client.wait_for_service(timeout_sec=1.0):
self.get_logger().info('Service set_target_pose not available! Waiting...')
self._goal_req = SetTargetPose.Request()
self.timer = self.create_timer(self._plan_timer_period, self.on_timer)
def _transform_msg_to_pose_msg(self, tf_msg):
pose = Pose()
pose.position.x = tf_msg.translation.x
pose.position.y = tf_msg.translation.y
pose.position.z = tf_msg.translation.z
pose.orientation.x = tf_msg.rotation.x
pose.orientation.y = tf_msg.rotation.y
pose.orientation.z = tf_msg.rotation.z
pose.orientation.w = tf_msg.rotation.w
return pose
def send_goal(self, pose):
self.get_logger().debug('Sending pose target to planner.')
self._goal_req.pose = pose
self.future = self._goal_client.call_async(self._goal_req)
while not self.future.done():
time.sleep(0.001)
return self.future.result()
def on_timer(self):
# Check if there is a valid transform between world and target frame
try:
world_frame_pose_target_frame = self._tf_buffer.lookup_transform(
self._world_frame, self._target_frames[self._target_frame_idx],
self.get_clock().now(), rclpy.duration.Duration(seconds=10.0)
)
except TransformException as ex:
self.get_logger().warning(f'Waiting for target_frame pose transform to be available \
in TF, between {self._world_frame} and \
{self._target_frames[self._target_frame_idx]}. if \
warning persists, check if the transform is \
published to tf. Message from TF: {ex}')
return
output_msg = PoseStamped()
output_msg.header.stamp = self.get_clock().now().to_msg()
output_msg.header.frame_id = self._world_frame
output_msg.pose = self._transform_msg_to_pose_msg(world_frame_pose_target_frame.transform)
response = self.send_goal(output_msg)
self.get_logger().debug(f'Goal set with response: {response}')
if response.success:
self._target_frame_idx = (self._target_frame_idx + 1) % len(self._target_frames)
else:
self.get_logger().warning('target pose was not reachable by planner, trying again \
on the next iteration')
def main(args=None):
rclpy.init(args=args)
pose_to_pose_node = PoseToPoseNode()
executor = MultiThreadedExecutor()
executor.add_node(pose_to_pose_node)
try:
executor.spin()
except KeyboardInterrupt:
pose_to_pose_node.get_logger().info(
'KeyboardInterrupt, shutting down.\n'
)
pose_to_pose_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| 5,036 | Python | 37.450381 | 98 | 0.645751 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_moveit_goal_setter/include/isaac_ros_moveit_goal_setter/goal_setter_node.hpp | // SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
// Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef ISAAC_ROS_MOVEIT_GOAL_SETTER__GOAL_SETTER_NODE_HPP_
#define ISAAC_ROS_MOVEIT_GOAL_SETTER__GOAL_SETTER_NODE_HPP_
#include <memory>
#include "isaac_ros_common/qos.hpp"
#include "isaac_ros_goal_setter_interfaces/srv/set_target_pose.hpp"
#include <moveit/move_group_interface/move_group_interface.h>
#include <rclcpp/rclcpp.hpp>
namespace nvidia
{
namespace isaac_ros
{
namespace manipulation
{
class GoalSetterNode
{
public:
GoalSetterNode(std::string name, const rclcpp::NodeOptions & options);
~GoalSetterNode() = default;
std::shared_ptr<rclcpp::Node> GetNode() const {return node_;}
void ConfigureMoveit();
private:
void SetTargetPoseCallback(
const std::shared_ptr<isaac_ros_goal_setter_interfaces::srv::SetTargetPose_Request> req,
std::shared_ptr<isaac_ros_goal_setter_interfaces::srv::SetTargetPose_Response> res);
const std::shared_ptr<rclcpp::Node> node_;
std::string planner_group_name_;
std::string planner_id_;
std::string end_effector_link_;
moveit::planning_interface::MoveGroupInterface move_group_interface_;
rclcpp::Service<isaac_ros_goal_setter_interfaces::srv::SetTargetPose>::SharedPtr
set_target_pose_service_;
};
} // namespace manipulation
} // namespace isaac_ros
} // namespace nvidia
#endif // ISAAC_ROS_MOVEIT_GOAL_SETTER__GOAL_SETTER_NODE_HPP_
| 2,060 | C++ | 29.761194 | 92 | 0.748058 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/setup.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
from glob import glob
import os
from setuptools import find_packages, setup
package_name = 'isaac_ros_cumotion'
setup(
name=package_name,
version='3.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(
os.path.join('share', package_name, 'launch'),
glob(os.path.join('launch', '*launch.[pxy][yma]*')),
),
(
os.path.join('share', package_name, 'params'),
glob(os.path.join('params', '*.[yma]*')),
),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Isaac ROS Maintainers',
maintainer_email='[email protected]',
author='Balakumar Sundaralingam',
description='Package adds a cuMotion planner node',
license='NVIDIA Isaac ROS Software License',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'cumotion_planner_node = isaac_ros_cumotion.cumotion_planner:main',
'robot_segmenter_node = isaac_ros_cumotion.robot_segmenter:main',
],
},
)
| 1,920 | Python | 33.303571 | 84 | 0.663542 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
| 884 | Python | 33.03846 | 74 | 0.725113 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
| 803 | Python | 32.499999 | 74 | 0.743462 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_copyright.main import main
import pytest
@pytest.mark.skip(reason='This package has a proprietary license')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 857 | Python | 33.319999 | 74 | 0.749125 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/launch/isaac_ros_cumotion.launch.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES',
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
import os
from ament_index_python.packages import get_package_share_directory
import launch
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
import yaml
def read_params(pkg_name, params_dir, params_file_name):
params_file = os.path.join(
get_package_share_directory(pkg_name), params_dir, params_file_name)
return yaml.safe_load(open(params_file, 'r'))
def launch_args_from_params(pkg_name, params_dir, params_file_name, prefix: str = None):
launch_args = []
launch_configs = {}
params = read_params(pkg_name, params_dir, params_file_name)
for param, value in params['/**']['ros__parameters'].items():
if value is not None:
arg_name = param if prefix is None else f'{prefix}.{param}'
launch_args.append(DeclareLaunchArgument(name=arg_name, default_value=str(value)))
launch_configs[param] = LaunchConfiguration(arg_name)
return launch_args, launch_configs
def generate_launch_description():
"""Launch file to bring up cumotion planner node."""
launch_args, launch_configs = launch_args_from_params(
'isaac_ros_cumotion', 'params', 'isaac_ros_cumotion_params.yaml', 'cumotion_planner')
cumotion_planner_node = Node(
name='cumotion_planner',
package='isaac_ros_cumotion',
namespace='',
executable='cumotion_planner_node',
parameters=[
launch_configs
],
output='screen',
)
return launch.LaunchDescription(launch_args + [cumotion_planner_node])
| 2,336 | Python | 34.953846 | 94 | 0.707192 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/launch/robot_segmentation.launch.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES',
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
import yaml
def read_params(pkg_name, params_dir, params_file_name):
params_file = os.path.join(
get_package_share_directory(pkg_name), params_dir, params_file_name)
return yaml.safe_load(open(params_file, 'r'))
def launch_args_from_params(pkg_name, params_dir, params_file_name, prefix: str = None):
launch_args = []
launch_configs = {}
params = read_params(pkg_name, params_dir, params_file_name)
for param, value in params['/**']['ros__parameters'].items():
if value is not None:
arg_name = param if prefix is None else f'{prefix}.{param}'
launch_args.append(DeclareLaunchArgument(name=arg_name, default_value=str(value)))
launch_configs[param] = LaunchConfiguration(arg_name)
return launch_args, launch_configs
def generate_launch_description():
"""Launch file to bring up robot segmenter node."""
launch_args, launch_configs = launch_args_from_params(
'isaac_ros_cumotion', 'params', 'robot_segmentation_params.yaml', 'robot_segmenter')
robot_segmenter_node = Node(
package='isaac_ros_cumotion',
namespace='',
executable='robot_segmenter_node',
name='robot_segmenter',
parameters=[launch_configs],
output='screen',
)
return LaunchDescription(launch_args + [robot_segmenter_node])
| 2,324 | Python | 35.904761 | 94 | 0.715146 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/isaac_ros_cumotion/util.py | # Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction,
# disclosure or distribution of this material and related documentation
# without an express license agreement from NVIDIA CORPORATION or
# its affiliates is strictly prohibited.
from curobo.geom.types import Sphere
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
def get_spheres_marker(
robot_spheres, base_frame: str, time, rgb=[0.1, 0.1, 0.1, 0.5], start_idx: int = 0):
m_arr = MarkerArray()
for i in range(len(robot_spheres)):
r_s = Sphere(
name='sphere',
radius=robot_spheres[i, -1],
pose=robot_spheres[i, :3].tolist() + [1, 0, 0, 0],
)
# print(rgb[i])
m = get_marker_sphere(r_s, base_frame, time, start_idx + i, rgb)
m_arr.markers.append(m)
return m_arr
def get_marker_sphere(sphere: Sphere, base_frame: str, time, idx=0, rgb=[0.4, 0.4, 0.8, 1.0]):
marker = Marker()
marker.header.frame_id = base_frame
marker.header.stamp = time
marker.id = idx
marker.type = Marker.SPHERE
marker.action = Marker.ADD
marker.scale.x = sphere.radius * 2
marker.scale.y = sphere.radius * 2
marker.scale.z = sphere.radius * 2
marker.color.r = rgb[0]
marker.color.g = rgb[1]
marker.color.b = rgb[2]
marker.color.a = rgb[3]
# pose:
marker.pose.position.x = sphere.position[0]
marker.pose.position.y = sphere.position[1]
marker.pose.position.z = sphere.position[2]
marker.pose.orientation.w = 1.0
return marker
| 1,803 | Python | 33.692307 | 94 | 0.667221 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/isaac_ros_cumotion/cumotion_planner.py | # Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction,
# disclosure or distribution of this material and related documentation
# without an express license agreement from NVIDIA CORPORATION or
# its affiliates is strictly prohibited.
from os import path
import time
from ament_index_python.packages import get_package_share_directory
from curobo.geom.sdf.world import CollisionCheckerType
from curobo.geom.types import Cuboid
from curobo.geom.types import Cylinder
from curobo.geom.types import Mesh
from curobo.geom.types import Sphere
from curobo.geom.types import VoxelGrid as CuVoxelGrid
from curobo.geom.types import WorldConfig
from curobo.types.base import TensorDeviceType
from curobo.types.math import Pose
from curobo.types.state import JointState as CuJointState
from curobo.util.logger import setup_curobo_logger
from curobo.util_file import get_robot_configs_path
from curobo.util_file import join_path
from curobo.util_file import load_yaml
from curobo.wrap.reacher.motion_gen import MotionGen
from curobo.wrap.reacher.motion_gen import MotionGenConfig
from curobo.wrap.reacher.motion_gen import MotionGenPlanConfig
from curobo.wrap.reacher.motion_gen import MotionGenStatus
from geometry_msgs.msg import Point
from geometry_msgs.msg import Vector3
from isaac_ros_cumotion.xrdf_utils import convert_xrdf_to_curobo
from moveit_msgs.action import MoveGroup
from moveit_msgs.msg import CollisionObject
from moveit_msgs.msg import MoveItErrorCodes
from moveit_msgs.msg import RobotTrajectory
import numpy as np
from nvblox_msgs.srv import EsdfAndGradients
import rclpy
from rclpy.action import ActionServer
from rclpy.callback_groups import MutuallyExclusiveCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from sensor_msgs.msg import JointState
from shape_msgs.msg import SolidPrimitive
from std_msgs.msg import ColorRGBA
import torch
from trajectory_msgs.msg import JointTrajectory
from trajectory_msgs.msg import JointTrajectoryPoint
from visualization_msgs.msg import Marker
class CumotionActionServer(Node):
def __init__(self):
super().__init__('cumotion_action_server')
self.tensor_args = TensorDeviceType()
self.declare_parameter('robot', 'ur5e.yml')
self.declare_parameter('time_dilation_factor', 0.5)
self.declare_parameter('collision_cache_mesh', 20)
self.declare_parameter('collision_cache_cuboid', 20)
self.declare_parameter('interpolation_dt', 0.02)
self.declare_parameter('voxel_dims', [2.0, 2.0, 2.0])
self.declare_parameter('voxel_size', 0.05)
self.declare_parameter('read_esdf_world', False)
self.declare_parameter('publish_curobo_world_as_voxels', False)
self.declare_parameter('add_ground_plane', False)
self.declare_parameter('publish_voxel_size', 0.05)
self.declare_parameter('max_publish_voxels', 50000)
self.declare_parameter('joint_states_topic', '/joint_states')
self.declare_parameter('tool_frame', rclpy.Parameter.Type.STRING)
self.declare_parameter('grid_position', [0.0, 0.0, 0.0])
self.declare_parameter('esdf_service_name', '/nvblox_node/get_esdf_and_gradient')
self.declare_parameter('urdf_path', rclpy.Parameter.Type.STRING)
self.declare_parameter('enable_curobo_debug_mode', False)
self.declare_parameter('override_moveit_scaling_factors', False)
debug_mode = (
self.get_parameter('enable_curobo_debug_mode').get_parameter_value().bool_value
)
if debug_mode:
setup_curobo_logger('info')
else:
setup_curobo_logger('warning')
self.__voxel_pub = self.create_publisher(Marker, '/curobo/voxels', 10)
self._action_server = ActionServer(
self, MoveGroup, 'cumotion/move_group', self.execute_callback
)
try:
self.__urdf_path = self.get_parameter('urdf_path')
self.__urdf_path = self.__urdf_path.get_parameter_value().string_value
if self.__urdf_path == '':
self.__urdf_path = None
except rclpy.exceptions.ParameterUninitializedException:
self.__urdf_path = None
try:
self.__tool_frame = self.get_parameter('tool_frame')
self.__tool_frame = self.__tool_frame.get_parameter_value().string_value
if self.__tool_frame == '':
self.__tool_frame = None
except rclpy.exceptions.ParameterUninitializedException:
self.__tool_frame = None
self.__xrdf_path = path.join(
get_package_share_directory('isaac_ros_cumotion_robot_description'), 'xrdf'
)
self.__joint_states_topic = (
self.get_parameter('joint_states_topic').get_parameter_value().string_value
)
self.__add_ground_plane = (
self.get_parameter('add_ground_plane').get_parameter_value().bool_value
)
self.__override_moveit_scaling_factors = (
self.get_parameter('override_moveit_scaling_factors').get_parameter_value().bool_value
)
# ESDF service
self.__read_esdf_grid = (
self.get_parameter('read_esdf_world').get_parameter_value().bool_value
)
self.__publish_curobo_world_as_voxels = (
self.get_parameter('publish_curobo_world_as_voxels').get_parameter_value().bool_value
)
self.__grid_position = (
self.get_parameter('grid_position').get_parameter_value().double_array_value
)
self.__max_publish_voxels = (
self.get_parameter('max_publish_voxels').get_parameter_value().integer_value
)
self.__voxel_dims = (
self.get_parameter('voxel_dims').get_parameter_value().double_array_value
)
self.__publish_voxel_size = (
self.get_parameter('publish_voxel_size').get_parameter_value().double_value
)
self.__voxel_size = self.get_parameter('voxel_size').get_parameter_value().double_value
self.__esdf_client = None
self.__esdf_req = None
if self.__read_esdf_grid:
esdf_service_name = (
self.get_parameter('esdf_service_name').get_parameter_value().string_value
)
esdf_service_cb_group = MutuallyExclusiveCallbackGroup()
self.__esdf_client = self.create_client(
EsdfAndGradients, esdf_service_name, callback_group=esdf_service_cb_group
)
while not self.__esdf_client.wait_for_service(timeout_sec=1.0):
self.get_logger().info(
f'Service({esdf_service_name}) not available, waiting again...'
)
self.__esdf_req = EsdfAndGradients.Request()
self.warmup()
self.__query_count = 0
self.__tensor_args = self.motion_gen.tensor_args
self.subscription = self.create_subscription(
JointState, self.__joint_states_topic, self.js_callback, 10
)
self.__js_buffer = None
def js_callback(self, msg):
self.__js_buffer = {
'joint_names': msg.name,
'position': msg.position,
'velocity': msg.velocity,
}
def warmup(self):
robot_file = self.get_parameter('robot').get_parameter_value().string_value
if robot_file == '':
self.get_logger().fatal('Received empty robot file')
raise SystemExit
collision_cache_cuboid = (
self.get_parameter('collision_cache_cuboid').get_parameter_value().integer_value
)
collision_cache_mesh = (
self.get_parameter('collision_cache_mesh').get_parameter_value().integer_value
)
interpolation_dt = (
self.get_parameter('interpolation_dt').get_parameter_value().double_value
)
self.get_logger().info('Loaded robot file name: ' + robot_file)
self.get_logger().info('warming up cuMotion, wait until ready')
tensor_args = self.tensor_args
world_file = WorldConfig.from_dict(
{
'cuboid': {
'table': {
'pose': [0, 0, -0.05, 1, 0, 0, 0], # x, y, z, qw, qx, qy, qz
'dims': [2.0, 2.0, 0.1],
}
},
'voxel': {
'world_voxel': {
'dims': self.__voxel_dims,
'pose': [0, 0, 0, 1, 0, 0, 0], # x, y, z, qw, qx, qy, qz
'voxel_size': self.__voxel_size,
'feature_dtype': torch.bfloat16,
},
},
}
)
if robot_file.lower().endswith('.xrdf'):
if self.__urdf_path is None:
self.get_logger().fatal('urdf_path is required to load robot from .xrdf')
raise SystemExit
robot_dict = load_yaml(join_path(self.__xrdf_path, robot_file))
robot_dict = convert_xrdf_to_curobo(self.__urdf_path, robot_dict, self.get_logger())
else:
robot_dict = load_yaml(join_path(get_robot_configs_path(), robot_file))
if self.__urdf_path is not None:
robot_dict['robot_cfg']['kinematics']['urdf_path'] = self.__urdf_path
robot_dict = robot_dict['robot_cfg']
motion_gen_config = MotionGenConfig.load_from_robot_config(
robot_dict,
world_file,
tensor_args,
interpolation_dt=interpolation_dt,
collision_cache={
'obb': collision_cache_cuboid,
'mesh': collision_cache_mesh,
},
collision_checker_type=CollisionCheckerType.VOXEL,
ee_link_name=self.__tool_frame,
)
motion_gen = MotionGen(motion_gen_config)
self.__robot_base_frame = motion_gen.kinematics.base_link
motion_gen.warmup(enable_graph=True)
self.__world_collision = motion_gen.world_coll_checker
if not self.__add_ground_plane:
motion_gen.clear_world_cache()
self.motion_gen = motion_gen
self.get_logger().info('cuMotion is ready for planning queries!')
def update_voxel_grid(self):
self.get_logger().info('Calling ESDF service')
# This is half of x,y and z dims
aabb_min = Point()
aabb_min.x = -1 * self.__voxel_dims[0] / 2
aabb_min.y = -1 * self.__voxel_dims[1] / 2
aabb_min.z = -1 * self.__voxel_dims[2] / 2
# This is a voxel size.
voxel_dims = Vector3()
voxel_dims.x = self.__voxel_dims[0]
voxel_dims.y = self.__voxel_dims[1]
voxel_dims.z = self.__voxel_dims[2]
esdf_future = self.send_request(aabb_min, voxel_dims)
while not esdf_future.done():
time.sleep(0.001)
response = esdf_future.result()
esdf_grid = self.get_esdf_voxel_grid(response)
if torch.max(esdf_grid.feature_tensor) <= (-1000.0 + 0.5 * self.__voxel_size + 1e-5):
self.get_logger().error('ESDF data is empty, try again after few seconds.')
return False
self.__world_collision.update_voxel_data(esdf_grid)
self.get_logger().info('Updated ESDF grid')
return True
def send_request(self, aabb_min_m, aabb_size_m):
self.__esdf_req.aabb_min_m = aabb_min_m
self.__esdf_req.aabb_size_m = aabb_size_m
self.get_logger().info(
f'ESDF req = {self.__esdf_req.aabb_min_m}, {self.__esdf_req.aabb_size_m}'
)
esdf_future = self.__esdf_client.call_async(self.__esdf_req)
return esdf_future
def get_esdf_voxel_grid(self, esdf_data):
esdf_array = esdf_data.esdf_and_gradients
array_shape = [
esdf_array.layout.dim[0].size,
esdf_array.layout.dim[1].size,
esdf_array.layout.dim[2].size,
]
array_data = np.array(esdf_array.data)
array_data = self.__tensor_args.to_device(array_data)
# Array data is reshaped to x y z channels
array_data = array_data.view(array_shape[0], array_shape[1], array_shape[2]).contiguous()
# Array is squeezed to 1 dimension
array_data = array_data.reshape(-1, 1)
# nvblox uses negative distance inside obstacles, cuRobo needs the opposite:
array_data = -1 * array_data
# nvblox assigns a value of -1000.0 for unobserved voxels, making
array_data[array_data >= 1000.0] = -1000.0
# nvblox distance are at origin of each voxel, cuRobo's esdf needs it to be at faces
array_data = array_data + 0.5 * self.__voxel_size
esdf_grid = CuVoxelGrid(
name='world_voxel',
dims=self.__voxel_dims,
pose=[
self.__grid_position[0],
self.__grid_position[1],
self.__grid_position[2],
1,
0.0,
0.0,
0,
], # x, y, z, qw, qx, qy, qz
voxel_size=self.__voxel_size,
feature_dtype=torch.float32,
feature_tensor=array_data,
)
return esdf_grid
def get_cumotion_collision_object(self, mv_object: CollisionObject):
objs = []
pose = mv_object.pose
world_pose = [
pose.position.x,
pose.position.y,
pose.position.z,
pose.orientation.w,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z,
]
world_pose = Pose.from_list(world_pose)
supported_objects = True
if len(mv_object.primitives) > 0:
for k in range(len(mv_object.primitives)):
pose = mv_object.primitive_poses[k]
primitive_pose = [
pose.position.x,
pose.position.y,
pose.position.z,
pose.orientation.w,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z,
]
object_pose = world_pose.multiply(Pose.from_list(primitive_pose)).tolist()
if mv_object.primitives[k].type == SolidPrimitive.BOX:
# cuboid:
dims = mv_object.primitives[k].dimensions
obj = Cuboid(
name=str(mv_object.id) + '_' + str(k) + '_cuboid',
pose=object_pose,
dims=dims,
)
objs.append(obj)
elif mv_object.primitives[k].type == SolidPrimitive.SPHERE:
# sphere:
radius = mv_object.primitives[k].dimensions[
mv_object.primitives[k].SPHERE_RADIUS
]
obj = Sphere(
name=str(mv_object.id) + '_' + str(k) + '_sphere',
pose=object_pose,
radius=radius,
)
objs.append(obj)
elif mv_object.primitives[k].type == SolidPrimitive.CYLINDER:
# cylinder:
cyl_height = mv_object.primitives[k].dimensions[
mv_object.primitives[k].CYLINDER_HEIGHT
]
cyl_radius = mv_object.primitives[k].dimensions[
mv_object.primitives[k].CYLINDER_RADIUS
]
obj = Cylinder(
name=str(mv_object.id) + '_' + str(k) + '_cylinder',
pose=object_pose,
height=cyl_height,
radius=cyl_radius,
)
objs.append(obj)
elif mv_object.primitives[k].type == SolidPrimitive.CONE:
self.get_logger().error('Cone primitive is not supported')
supported_objects = False
else:
self.get_logger().error('Unknown primitive type')
supported_objects = False
if len(mv_object.meshes) > 0:
for k in range(len(mv_object.meshes)):
pose = mv_object.mesh_poses[k]
mesh_pose = [
pose.position.x,
pose.position.y,
pose.position.z,
pose.orientation.w,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z,
]
object_pose = world_pose.multiply(Pose.from_list(mesh_pose)).tolist()
verts = mv_object.meshes[k].vertices
verts = [[v.x, v.y, v.z] for v in verts]
tris = [
[v.vertex_indices[0], v.vertex_indices[1], v.vertex_indices[2]]
for v in mv_object.meshes[k].triangles
]
obj = Mesh(
name=str(mv_object.id) + '_' + str(len(objs)) + '_mesh',
pose=object_pose,
vertices=verts,
faces=tris,
)
objs.append(obj)
return objs, supported_objects
def get_joint_trajectory(self, js: CuJointState, dt: float):
traj = RobotTrajectory()
cmd_traj = JointTrajectory()
q_traj = js.position.cpu().view(-1, js.position.shape[-1]).numpy()
vel = js.velocity.cpu().view(-1, js.position.shape[-1]).numpy()
acc = js.acceleration.view(-1, js.position.shape[-1]).cpu().numpy()
for i in range(len(q_traj)):
traj_pt = JointTrajectoryPoint()
traj_pt.positions = q_traj[i].tolist()
if js is not None and i < len(vel):
traj_pt.velocities = vel[i].tolist()
if js is not None and i < len(acc):
traj_pt.accelerations = acc[i].tolist()
time_d = rclpy.time.Duration(seconds=i * dt).to_msg()
traj_pt.time_from_start = time_d
cmd_traj.points.append(traj_pt)
cmd_traj.joint_names = js.joint_names
cmd_traj.header.stamp = self.get_clock().now().to_msg()
traj.joint_trajectory = cmd_traj
return traj
def update_world_objects(self, moveit_objects):
world_update_status = True
if len(moveit_objects) > 0:
cuboid_list = []
sphere_list = []
cylinder_list = []
mesh_list = []
for i, obj in enumerate(moveit_objects):
cumotion_objects, world_update_status = self.get_cumotion_collision_object(obj)
for cumotion_object in cumotion_objects:
if isinstance(cumotion_object, Cuboid):
cuboid_list.append(cumotion_object)
elif isinstance(cumotion_object, Cylinder):
cylinder_list.append(cumotion_object)
elif isinstance(cumotion_object, Sphere):
sphere_list.append(cumotion_object)
elif isinstance(cumotion_object, Mesh):
mesh_list.append(cumotion_object)
world_model = WorldConfig(
cuboid=cuboid_list,
cylinder=cylinder_list,
sphere=sphere_list,
mesh=mesh_list,
).get_collision_check_world()
self.motion_gen.update_world(world_model)
if self.__read_esdf_grid:
world_update_status = self.update_voxel_grid()
if self.__publish_curobo_world_as_voxels:
voxels = self.__world_collision.get_esdf_in_bounding_box(
Cuboid(
name='test',
pose=[0.0, 0.0, 0.0, 1, 0, 0, 0], # x, y, z, qw, qx, qy, qz
dims=self.__voxel_dims,
),
voxel_size=self.__publish_voxel_size,
)
xyzr_tensor = voxels.xyzr_tensor.clone()
xyzr_tensor[..., 3] = voxels.feature_tensor
self.publish_voxels(xyzr_tensor)
return world_update_status
def execute_callback(self, goal_handle):
self.get_logger().info('Executing goal...')
# check moveit scaling factors:
min_scaling_factor = min(goal_handle.request.request.max_velocity_scaling_factor,
goal_handle.request.request.max_acceleration_scaling_factor)
time_dilation_factor = min(1.0, min_scaling_factor)
if time_dilation_factor <= 0.0 or self.__override_moveit_scaling_factors:
time_dilation_factor = self.get_parameter(
'time_dilation_factor').get_parameter_value().double_value
self.get_logger().info('Planning with time_dilation_factor: ' +
str(time_dilation_factor))
plan_req = goal_handle.request.request
goal_handle.succeed()
scene = goal_handle.request.planning_options.planning_scene_diff
world_objects = scene.world.collision_objects
world_update_status = self.update_world_objects(world_objects)
result = MoveGroup.Result()
if not world_update_status:
result.error_code.val = MoveItErrorCodes.COLLISION_CHECKING_UNAVAILABLE
self.get_logger().error('World update failed.')
return result
start_state = None
if len(plan_req.start_state.joint_state.position) > 0:
start_state = self.motion_gen.get_active_js(
CuJointState.from_position(
position=self.tensor_args.to_device(
plan_req.start_state.joint_state.position
).unsqueeze(0),
joint_names=plan_req.start_state.joint_state.name,
)
)
else:
self.get_logger().info(
'PlanRequest start state was empty, reading current joint state'
)
if start_state is None or plan_req.start_state.is_diff:
if self.__js_buffer is None:
self.get_logger().error(
'joint_state was not received from ' + self.__joint_states_topic
)
return result
# read joint state:
state = CuJointState.from_position(
position=self.tensor_args.to_device(self.__js_buffer['position']).unsqueeze(0),
joint_names=self.__js_buffer['joint_names'],
)
state.velocity = self.tensor_args.to_device(self.__js_buffer['velocity']).unsqueeze(0)
current_joint_state = self.motion_gen.get_active_js(state)
if start_state is not None and plan_req.start_state.is_diff:
start_state.position += current_joint_state.position
start_state.velocity += current_joint_state.velocity
else:
start_state = current_joint_state
if len(plan_req.goal_constraints[0].joint_constraints) > 0:
self.get_logger().info('Calculating goal pose from Joint target')
goal_config = [
plan_req.goal_constraints[0].joint_constraints[x].position
for x in range(len(plan_req.goal_constraints[0].joint_constraints))
]
goal_jnames = [
plan_req.goal_constraints[0].joint_constraints[x].joint_name
for x in range(len(plan_req.goal_constraints[0].joint_constraints))
]
goal_state = self.motion_gen.get_active_js(
CuJointState.from_position(
position=self.tensor_args.to_device(goal_config).view(1, -1),
joint_names=goal_jnames,
)
)
goal_pose = self.motion_gen.compute_kinematics(goal_state).ee_pose.clone()
elif (
len(plan_req.goal_constraints[0].position_constraints) > 0
and len(plan_req.goal_constraints[0].orientation_constraints) > 0
):
self.get_logger().info('Using goal from Pose')
position = (
plan_req.goal_constraints[0]
.position_constraints[0]
.constraint_region.primitive_poses[0]
.position
)
position = [position.x, position.y, position.z]
orientation = plan_req.goal_constraints[0].orientation_constraints[0].orientation
orientation = [orientation.w, orientation.x, orientation.y, orientation.z]
pose_list = position + orientation
goal_pose = Pose.from_list(pose_list, tensor_args=self.tensor_args)
# Check if link names match:
position_link_name = plan_req.goal_constraints[0].position_constraints[0].link_name
orientation_link_name = (
plan_req.goal_constraints[0].orientation_constraints[0].link_name
)
plan_link_name = self.motion_gen.kinematics.ee_link
if position_link_name != orientation_link_name:
self.get_logger().error(
'Link name for Target Position "'
+ position_link_name
+ '" and Target Orientation "'
+ orientation_link_name
+ '" do not match'
)
result.error_code.val = MoveItErrorCodes.INVALID_LINK_NAME
return result
if position_link_name != plan_link_name:
self.get_logger().error(
'Link name for Target Pose "'
+ position_link_name
+ '" and Planning frame "'
+ plan_link_name
+ '" do not match, relaunch node with tool_frame = '
+ position_link_name
)
result.error_code.val = MoveItErrorCodes.INVALID_LINK_NAME
return result
else:
self.get_logger().error('Goal constraints not supported')
self.motion_gen.reset(reset_seed=False)
motion_gen_result = self.motion_gen.plan_single(
start_state,
goal_pose,
MotionGenPlanConfig(max_attempts=5, enable_graph_attempt=1,
time_dilation_factor=time_dilation_factor),
)
result = MoveGroup.Result()
if motion_gen_result.success.item():
result.error_code.val = MoveItErrorCodes.SUCCESS
result.trajectory_start = plan_req.start_state
traj = self.get_joint_trajectory(
motion_gen_result.optimized_plan, motion_gen_result.optimized_dt.item()
)
result.planning_time = motion_gen_result.total_time
result.planned_trajectory = traj
elif not motion_gen_result.valid_query:
self.get_logger().error(
f'Invalid planning query: {motion_gen_result.status}'
)
if motion_gen_result.status == MotionGenStatus.INVALID_START_STATE_JOINT_LIMITS:
result.error_code.val = MoveItErrorCodes.START_STATE_INVALID
if motion_gen_result.status in [
MotionGenStatus.INVALID_START_STATE_WORLD_COLLISION,
MotionGenStatus.INVALID_START_STATE_SELF_COLLISION,
]:
result.error_code.val = MoveItErrorCodes.START_STATE_IN_COLLISION
else:
self.get_logger().error(
f'Motion planning failed wih status: {motion_gen_result.status}'
)
if motion_gen_result.status == MotionGenStatus.IK_FAIL:
result.error_code.val = MoveItErrorCodes.NO_IK_SOLUTION
self.get_logger().info(
'returned planning result (query, success, failure_status): '
+ str(self.__query_count)
+ ' '
+ str(motion_gen_result.success.item())
+ ' '
+ str(motion_gen_result.status)
)
self.__query_count += 1
return result
def publish_voxels(self, voxels):
vox_size = self.__publish_voxel_size
# create marker:
marker = Marker()
marker.header.frame_id = self.__robot_base_frame
marker.id = 0
marker.type = 6 # cube list
marker.ns = 'curobo_world'
marker.action = 0
marker.pose.orientation.w = 1.0
marker.lifetime = rclpy.duration.Duration(seconds=1000.0).to_msg()
marker.frame_locked = False
marker.scale.x = vox_size
marker.scale.y = vox_size
marker.scale.z = vox_size
# get only voxels that are inside surfaces:
voxels = voxels[voxels[:, 3] >= 0.0]
vox = voxels.view(-1, 4).cpu().numpy()
marker.points = []
for i in range(min(len(vox), self.__max_publish_voxels)):
pt = Point()
pt.x = float(vox[i, 0])
pt.y = float(vox[i, 1])
pt.z = float(vox[i, 2])
color = ColorRGBA()
d = vox[i, 3]
rgba = [min(1.0, 1.0 - float(d)), 0.0, 0.0, 1.0]
color.r = rgba[0]
color.g = rgba[1]
color.b = rgba[2]
color.a = rgba[3]
marker.colors.append(color)
marker.points.append(pt)
# publish voxels:
marker.header.stamp = self.get_clock().now().to_msg()
self.__voxel_pub.publish(marker)
def main(args=None):
rclpy.init(args=args)
cumotion_action_server = CumotionActionServer()
executor = MultiThreadedExecutor()
executor.add_node(cumotion_action_server)
try:
executor.spin()
except KeyboardInterrupt:
cumotion_action_server.get_logger().info('KeyboardInterrupt, shutting down.\n')
cumotion_action_server.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| 30,274 | Python | 40.816298 | 98 | 0.562397 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/isaac_ros_cumotion/robot_segmenter.py | # Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction,
# disclosure or distribution of this material and related documentation
# without an express license agreement from NVIDIA CORPORATION or
# its affiliates is strictly prohibited.
from copy import deepcopy
import threading
import time
from curobo.types.base import TensorDeviceType
from curobo.types.camera import CameraObservation
from curobo.types.math import Pose as CuPose
from curobo.types.state import JointState as CuJointState
from curobo.util_file import get_robot_configs_path
from curobo.util_file import join_path
from curobo.util_file import load_yaml
from curobo.wrap.model.robot_segmenter import RobotSegmenter
from cv_bridge import CvBridge
from isaac_ros_cumotion.util import get_spheres_marker
from isaac_ros_cumotion.xrdf_utils import convert_xrdf_to_curobo
from message_filters import ApproximateTimeSynchronizer
from message_filters import Subscriber
import numpy as np
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import JointState
from tf2_ros import TransformException
from tf2_ros.buffer import Buffer
from tf2_ros.transform_listener import TransformListener
import torch
from visualization_msgs.msg import MarkerArray
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
class CumotionRobotSegmenter(Node):
"""This node filters out depth pixels assosiated with a robot body using a mask."""
def __init__(self):
super().__init__('cumotion_robot_segmentation')
self.declare_parameter('robot', 'ur5e.yml')
self.declare_parameter('cuda_device', 0)
self.declare_parameter('distance_threshold', 0.1)
self.declare_parameter('time_sync_slop', 0.1)
self.declare_parameter('tf_lookup_duration', 5.0)
self.declare_parameter('joint_states_topic', '/joint_states')
self.declare_parameter('debug_robot_topic', '/cumotion/robot_segmenter/robot_spheres')
self.declare_parameter('depth_image_topics', ['/cumotion/depth_1/image_raw'])
self.declare_parameter('depth_camera_infos', ['/cumotion/depth_1/camera_info'])
self.declare_parameter('robot_mask_publish_topics', ['/cumotion/depth_1/robot_mask'])
self.declare_parameter('world_depth_publish_topics', ['/cumotion/depth_1/world_depth'])
self.declare_parameter('log_debug', False)
self.declare_parameter('urdf_path', rclpy.Parameter.Type.STRING)
try:
self.__urdf_path = self.get_parameter('urdf_path')
self.__urdf_path = self.__urdf_path.get_parameter_value().string_value
except rclpy.exceptions.ParameterUninitializedException:
self.__urdf_path = None
distance_threshold = (
self.get_parameter('distance_threshold').get_parameter_value().double_value)
time_sync_slop = self.get_parameter('time_sync_slop').get_parameter_value().double_value
self._tf_lookup_duration = (
self.get_parameter('tf_lookup_duration').get_parameter_value().double_value
)
joint_states_topic = (
self.get_parameter('joint_states_topic').get_parameter_value().string_value)
debug_robot_topic = (
self.get_parameter('debug_robot_topic').get_parameter_value().string_value)
depth_image_topics = (
self.get_parameter('depth_image_topics').get_parameter_value().string_array_value)
depth_camera_infos = (
self.get_parameter('depth_camera_infos').get_parameter_value().string_array_value)
publish_mask_topics = (
self.get_parameter(
'robot_mask_publish_topics').get_parameter_value().string_array_value)
world_depth_topics = (
self.get_parameter(
'world_depth_publish_topics').get_parameter_value().string_array_value)
self._log_debug = self.get_parameter('log_debug').get_parameter_value().bool_value
num_cameras = len(depth_image_topics)
self._num_cameras = num_cameras
if len(depth_camera_infos) != num_cameras:
self.get_logger().error(
'Number of topics in depth_camera_infos does not match depth_image_topics')
if len(publish_mask_topics) != num_cameras:
self.get_logger().error(
'Number of topics in publish_mask_topics does not match depth_image_topics')
if len(world_depth_topics) != num_cameras:
self.get_logger().error(
'Number of topics in world_depth_topics does not match depth_image_topics')
cuda_device_id = self.get_parameter('cuda_device').get_parameter_value().integer_value
self._tensor_args = TensorDeviceType(device=torch.device('cuda', cuda_device_id))
# Create subscribers:
subscribers = [Subscriber(self, Image, topic) for topic in depth_image_topics]
subscribers.append(Subscriber(self, JointState, joint_states_topic))
# Subscribe to topics with sync:
self.approx_time_sync = ApproximateTimeSynchronizer(
tuple(subscribers), queue_size=100, slop=time_sync_slop)
self.approx_time_sync.registerCallback(self.process_depth_and_joint_state)
self.info_subscribers = []
for idx in range(num_cameras):
self.info_subscribers.append(
self.create_subscription(
CameraInfo, depth_camera_infos[idx],
lambda msg, index=idx: self.camera_info_cb(msg, index), 10)
)
self.mask_publishers = [
self.create_publisher(Image, topic, 10) for topic in publish_mask_topics]
self.segmented_publishers = [
self.create_publisher(Image, topic, 10) for topic in world_depth_topics]
self.debug_robot_publisher = self.create_publisher(MarkerArray, debug_robot_topic, 10)
self.tf_buffer = Buffer(cache_time=rclpy.duration.Duration(seconds=60.0))
self.tf_listener = TransformListener(self.tf_buffer, self)
# Create a depth mask publisher:
robot_file = self.get_parameter('robot').get_parameter_value().string_value
self.br = CvBridge()
# Create buffers to store data:
self._depth_buffers = None
self._depth_intrinsics = [None for x in range(num_cameras)]
self._robot_pose_camera = [None for x in range(num_cameras)]
self._depth_encoding = None
self._js_buffer = None
self._timestamp = None
self._camera_headers = []
self.lock = threading.Lock()
self.timer = self.create_timer(0.01, self.on_timer)
robot_dict = load_yaml(join_path(get_robot_configs_path(), robot_file))
if robot_file.lower().endswith('.xrdf'):
if self.__urdf_path is None:
self.get_logger().fatal('urdf_path is required to load robot from .xrdf')
raise SystemExit
robot_dict = convert_xrdf_to_curobo(self.__urdf_path, robot_dict, self.get_logger())
if self.__urdf_path is not None:
robot_dict['robot_cfg']['kinematics']['urdf_path'] = self.__urdf_path
self._cumotion_segmenter = RobotSegmenter.from_robot_file(
robot_dict, distance_threshold=distance_threshold)
self._cumotion_base_frame = self._cumotion_segmenter.base_link
self._robot_pose_cameras = None
self.get_logger().info(f'Node initialized with {self._num_cameras} cameras')
def process_depth_and_joint_state(self, *msgs):
self._depth_buffers = []
self._depth_encoding = []
self._camera_headers = []
for msg in msgs:
if (isinstance(msg, Image)):
img = self.br.imgmsg_to_cv2(msg)
if msg.encoding == '32FC1':
img = 1000.0 * img
self._depth_buffers.append(img)
self._camera_headers.append(msg.header)
self._depth_encoding.append(msg.encoding)
if (isinstance(msg, JointState)):
self._js_buffer = {'joint_names': msg.name, 'position': msg.position}
self._timestamp = msg.header.stamp
def camera_info_cb(self, msg, idx):
self._depth_intrinsics[idx] = msg.k
def publish_robot_spheres(self, traj: CuJointState):
kin_state = self._cumotion_segmenter.robot_world.get_kinematics(traj.position)
spheres = kin_state.link_spheres_tensor.cpu().numpy()
current_time = self.get_clock().now().to_msg()
m_arr = get_spheres_marker(
spheres[0],
self._cumotion_base_frame,
current_time,
rgb=[0.0, 1.0, 0.0, 1.0],
)
self.debug_robot_publisher.publish(m_arr)
def is_subscribed(self) -> bool:
count_mask = max(
[mask_pub.get_subscription_count() for mask_pub in self.mask_publishers]
+ [seg_pub.get_subscription_count() for seg_pub in self.segmented_publishers]
)
if count_mask > 0:
return True
return False
def publish_images(self, depth_mask, segmented_depth, camera_header, idx: int):
if self.mask_publishers[idx].get_subscription_count() > 0:
depth_mask = depth_mask[idx]
msg = self.br.cv2_to_imgmsg(depth_mask, 'mono8')
msg.header = camera_header[idx]
self.mask_publishers[idx].publish(msg)
if self.segmented_publishers[idx].get_subscription_count() > 0:
segmented_depth = segmented_depth[idx]
if self._depth_encoding[idx] == '16UC1':
segmented_depth = segmented_depth.astype(np.uint16)
elif self._depth_encoding[idx] == '32FC1':
segmented_depth = segmented_depth / 1000.0
msg = self.br.cv2_to_imgmsg(segmented_depth, self._depth_encoding[idx])
msg.header = camera_header[idx]
self.segmented_publishers[idx].publish(msg)
def on_timer(self):
computation_time = -1.0
node_time = -1.0
if not self.is_subscribed():
return
if ((not all(isinstance(intrinsic, np.ndarray) for intrinsic in self._depth_intrinsics))
or (len(self._camera_headers) == 0) or (self._timestamp is None)):
return
timestamp = self._timestamp
# Read camera transforms
if self._robot_pose_cameras is None:
self.get_logger().info('Reading TF from cameras')
with self.lock:
camera_headers = deepcopy(self._camera_headers)
for i in range(self._num_cameras):
if self._robot_pose_camera[i] is None:
try:
t = self.tf_buffer.lookup_transform(
self._cumotion_base_frame,
camera_headers[i].frame_id,
timestamp,
rclpy.duration.Duration(seconds=self._tf_lookup_duration),
)
self._robot_pose_camera[i] = CuPose.from_list(
[
t.transform.translation.x,
t.transform.translation.y,
t.transform.translation.z,
t.transform.rotation.w,
t.transform.rotation.x,
t.transform.rotation.y,
t.transform.rotation.z,
]
)
except TransformException as ex:
self.get_logger().debug(f'Could not transform {camera_headers[i].frame_id} \
to { self._cumotion_base_frame}: {ex}')
continue
if None not in self._robot_pose_camera:
self._robot_pose_cameras = CuPose.cat(self._robot_pose_camera)
self.get_logger().info('Received TF from cameras to robot')
# Check if all camera transforms have been received
if self._robot_pose_cameras is None:
return
with self.lock:
timestamp = self._timestamp
depth_image = np.copy(np.stack((self._depth_buffers)))
intrinsics = np.copy(np.stack(self._depth_intrinsics))
js = np.copy(self._js_buffer['position'])
j_names = deepcopy(self._js_buffer['joint_names'])
camera_headers = deepcopy(self._camera_headers)
self._timestamp = None
self._camera_headers = []
start_node_time = time.time()
depth_image = self._tensor_args.to_device(depth_image.astype(np.float32))
depth_image = depth_image.view(
self._num_cameras, depth_image.shape[-2], depth_image.shape[-1])
if not self._cumotion_segmenter.ready:
intrinsics = self._tensor_args.to_device(intrinsics).view(self._num_cameras, 3, 3)
cam_obs = CameraObservation(depth_image=depth_image, intrinsics=intrinsics)
self._cumotion_segmenter.update_camera_projection(cam_obs)
self.get_logger().info('Updated Projection Matrices')
cam_obs = CameraObservation(depth_image=depth_image, pose=self._robot_pose_cameras)
q = CuJointState.from_numpy(
position=js, joint_names=j_names, tensor_args=self._tensor_args).unsqueeze(0)
q = self._cumotion_segmenter.robot_world.get_active_js(q)
start_segmentation_time = time.time()
depth_mask, segmented_depth = self._cumotion_segmenter.get_robot_mask_from_active_js(
cam_obs, q)
if self._log_debug:
torch.cuda.synchronize()
computation_time = time.time() - start_segmentation_time
depth_mask = depth_mask.cpu().numpy().astype(np.uint8) * 255
segmented_depth = segmented_depth.cpu().numpy()
for x in range(depth_mask.shape[0]):
self.publish_images(depth_mask, segmented_depth, camera_headers, x)
if self.debug_robot_publisher.get_subscription_count() > 0:
self.publish_robot_spheres(q)
if self._log_debug:
node_time = time.time() - start_node_time
self.get_logger().info(f'Node Time(ms), Computation Time(ms): {node_time * 1000.0},\
{computation_time * 1000.0}')
def main(args=None):
# Initialize the rclpy library
rclpy.init(args=args)
# Create the node
cumotion_segmenter = CumotionRobotSegmenter()
# Spin the node so the callback function is called.
rclpy.spin(cumotion_segmenter)
# Destroy the node explicitly
cumotion_segmenter.destroy_node()
# Shutdown the ROS client library for Python
rclpy.shutdown()
if __name__ == '__main__':
main()
| 15,118 | Python | 42.445402 | 100 | 0.618071 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/isaac_ros_cumotion/xrdf_utils.py | # Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction,
# disclosure or distribution of this material and related documentation
# without an express license agreement from NVIDIA CORPORATION or
# its affiliates is strictly prohibited.
from typing import Any, Dict, Union
from curobo.cuda_robot_model.urdf_kinematics_parser import UrdfKinematicsParser
from curobo.util_file import load_yaml
def return_value_if_exists(input_dict: Dict, key: str, logger, suffix: str = 'xrdf') -> Any:
if key not in input_dict:
logger.error(key + ' key not found in ' + suffix)
raise ValueError(key + ' key not found in ' + suffix)
return input_dict[key]
def convert_xrdf_to_curobo(urdf_string: str, input_dict: Union[str, Dict], logger) -> Dict:
# urdf_string needs to be a path to a urdf file.
if isinstance(input_dict, str):
input_dict = load_yaml(input_dict)
if return_value_if_exists(input_dict, 'format', logger) != 'xrdf':
logger.error('format is not xrdf')
raise ValueError('format is not xrdf')
if return_value_if_exists(input_dict, 'format_version', logger) > 1.0:
logger.warn('format_version is greater than 1.0')
# Also get base link as root of urdf
kinematics_parser = UrdfKinematicsParser(urdf_string, build_scene_graph=True)
joint_names = kinematics_parser.get_controlled_joint_names()
base_link = kinematics_parser.root_link
output_dict = {}
if 'collision' in input_dict:
coll_name = return_value_if_exists(input_dict['collision'], 'geometry', logger)
if 'spheres' not in input_dict['geometry'][coll_name]:
logger.error('spheres key not found in xrdf')
raise ValueError('spheres key not found in xrdf')
coll_spheres = return_value_if_exists(input_dict['geometry'][coll_name], 'spheres', logger)
output_dict['collision_spheres'] = coll_spheres
buffer_distance = return_value_if_exists(
input_dict['collision'], 'buffer_distance', logger
)
output_dict['collision_sphere_buffer'] = buffer_distance
output_dict['collision_link_names'] = list(coll_spheres.keys())
if 'self_collision' in input_dict:
if input_dict['self_collision']['geometry'] != input_dict['collision']['geometry']:
logger.error('self_collision geometry does not match collision geometry')
raise ValueError('self_collision geometry does not match collision geometry')
self_collision_ignore = return_value_if_exists(
input_dict['self_collision'],
'ignore',
logger,
)
self_collision_buffer = return_value_if_exists(
input_dict['self_collision'],
'buffer_distance',
logger,
)
output_dict['self_collision_ignore'] = self_collision_ignore
output_dict['self_collision_buffer'] = self_collision_buffer
else:
logger.error('self_collision key not found in xrdf')
raise ValueError('self_collision key not found in xrdf')
else:
logger.warn('collision key not found in xrdf, collision avoidance is disabled')
tool_frames = return_value_if_exists(input_dict, 'tool_frames', logger)
output_dict['ee_link'] = tool_frames[0]
output_dict['link_names'] = None
if len(tool_frames) > 1:
output_dict['link_names'] = input_dict['tool_frames']
# cspace:
cspace_dict = return_value_if_exists(input_dict, 'cspace', logger)
active_joints = return_value_if_exists(cspace_dict, 'joint_names', logger)
default_joint_positions = return_value_if_exists(input_dict, 'default_joint_positions', logger)
active_config = []
locked_joints = {}
for j in joint_names:
if j in active_joints:
if j in default_joint_positions:
active_config.append(default_joint_positions[j])
else:
active_config.append(0.0)
else:
locked_joints[j] = 0.0
if j in default_joint_positions:
locked_joints[j] = default_joint_positions[j]
acceleration_limits = return_value_if_exists(cspace_dict, 'acceleration_limits', logger)
jerk_limits = return_value_if_exists(cspace_dict, 'jerk_limits', logger)
max_acc = max(acceleration_limits)
max_jerk = max(jerk_limits)
output_dict['lock_joints'] = locked_joints
all_joint_names = active_joints + list(locked_joints.keys())
output_cspace = {
'joint_names': all_joint_names,
'retract_config': active_config + list(locked_joints.values()),
'null_space_weight': [1.0 for _ in range(len(all_joint_names))],
'cspace_distance_weight': [1.0 for _ in range(len(all_joint_names))],
'max_acceleration': acceleration_limits
+ [max_acc for _ in range(len(all_joint_names) - len(active_joints))],
'max_jerk': jerk_limits
+ [max_jerk for _ in range(len(all_joint_names) - len(active_joints))],
}
output_dict['cspace'] = output_cspace
extra_links = {}
if 'modifiers' in input_dict:
for k in range(len(input_dict['modifiers'])):
mod_list = list(input_dict['modifiers'][k].keys())
if len(mod_list) > 1:
logger.error('Each modifier should have only one key')
raise ValueError('Each modifier should have only one key')
mod_type = mod_list[0]
if mod_type == 'set_base_frame':
base_link = input_dict['modifiers'][k]['set_base_frame']
elif mod_type == 'add_frame':
frame_data = input_dict['modifiers'][k]['add_frame']
extra_links[frame_data['frame_name']] = {
'parent_link_name': frame_data['parent_frame_name'],
'link_name': frame_data['frame_name'],
'joint_name': frame_data['joint_name'],
'joint_type': frame_data['joint_type'],
'fixed_transform': frame_data['fixed_transform']['position']
+ [frame_data['fixed_transform']['orientation']['w']]
+ frame_data['fixed_transform']['orientation']['xyz'],
}
else:
logger.warn('XRDF modifier "' + mod_type + '" not recognized')
output_dict['extra_links'] = extra_links
output_dict['base_link'] = base_link
output_dict['urdf_path'] = urdf_string
output_dict = {'robot_cfg': {'kinematics': output_dict}}
return output_dict
| 6,828 | Python | 41.949685 | 99 | 0.619801 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/params/robot_segmentation_params.yaml | /**:
ros__parameters:
robot: ur5e.yml
depth_image_topics: [/depth_image]
depth_camera_infos: [/rgb/camera_info]
robot_mask_publish_topics: [/cumotion/camera_1/robot_mask]
world_depth_publish_topics: [/cumotion/camera_1/world_depth]
joint_states_topic: /joint_states
debug_robot_topic: /cumotion/robot_segmenter/robot_spheres
distance_threshold: 0.2
time_sync_slop: 0.1
tf_lookup_duration: 5.0
cuda_device: 0
log_debug: False
urdf_path: null
| 496 | YAML | 30.062498 | 64 | 0.679435 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion/params/isaac_ros_cumotion_params.yaml | /**:
ros__parameters:
robot: ""
time_dilation_factor: 0.5
collision_cache_mesh: 20
collision_cache_cuboid: 20
interpolation_dt: 0.02
voxel_dims: [2.0, 2.0, 2.0]
voxel_size: 0.05
read_esdf_world: False
publish_curobo_world_as_voxels: False
add_ground_plane: False
publish_voxel_size: 0.05
max_publish_voxels: 50000
tool_frame: ""
grid_position: [0.0, 0.0, 0.0]
esdf_service_name: "/nvblox_node/get_esdf_and_gradient"
urdf_path: ""
enable_curobo_debug_mode: False
override_moveit_scaling_factors: False | 574 | YAML | 27.749999 | 59 | 0.644599 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_moveit/cumotion_planner_plugin_description.xml | <library path="libisaac_ros_cumotion_moveit">
<class name="isaac_ros_cumotion_moveit/CumotionPlanner" type="nvidia::isaac::manipulation::CumotionPlannerManager" base_class_type="planning_interface::PlannerManager">
<description>
The cuMotion planner generates collision-free trajectories leveraging CUDA compute.
</description>
</class>
</library>
| 366 | XML | 44.874994 | 170 | 0.770492 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_moveit/src/cumotion_interface.cpp | // SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
// Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "isaac_ros_cumotion_moveit/cumotion_interface.hpp"
#include <chrono>
#include <memory>
#include "moveit/planning_interface/planning_interface.h"
#include "moveit/planning_scene/planning_scene.h"
#include "moveit/robot_state/conversions.h"
#include "rclcpp/rclcpp.hpp"
namespace nvidia
{
namespace isaac
{
namespace manipulation
{
namespace
{
constexpr unsigned kSleepIntervalInMs = 5;
constexpr unsigned kTimeoutIntervalInSeconds = 5;
} // namespace
bool CumotionInterface::solve(
const planning_scene::PlanningSceneConstPtr & planning_scene,
const planning_interface::MotionPlanRequest & request,
planning_interface::MotionPlanDetailedResponse & response)
{
RCLCPP_INFO(node_->get_logger(), "Planning trajectory");
if (!planner_busy) {
action_client_->updateGoal(planning_scene, request);
action_client_->sendGoal();
planner_busy = true;
}
rclcpp::Time start_time = node_->now();
while (
!action_client_->result_ready &&
node_->now().seconds() - start_time.seconds() < kTimeoutIntervalInSeconds)
{
action_client_->getGoal();
std::this_thread::sleep_for(std::chrono::milliseconds(kSleepIntervalInMs));
}
if (!action_client_->result_ready) {
RCLCPP_ERROR(node_->get_logger(), "Timed out!");
planner_busy = false;
return false;
}
RCLCPP_INFO(node_->get_logger(), "Received trajectory result");
if (!action_client_->success) {
RCLCPP_ERROR(node_->get_logger(), "No trajectory");
response.error_code_.val = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
planner_busy = false;
return false;
}
RCLCPP_INFO(node_->get_logger(), "Trajectory success!");
response.error_code_ = action_client_->plan_response.error_code;
response.description_ = action_client_->plan_response.description;
auto result_traj = std::make_shared<robot_trajectory::RobotTrajectory>(
planning_scene->getRobotModel(), request.group_name);
moveit::core::RobotState robot_state(planning_scene->getRobotModel());
moveit::core::robotStateMsgToRobotState(
action_client_->plan_response.trajectory_start,
robot_state);
result_traj->setRobotTrajectoryMsg(
robot_state,
action_client_->plan_response.trajectory[0]);
response.trajectory_.clear();
response.trajectory_.push_back(result_traj);
response.processing_time_ = action_client_->plan_response.processing_time;
planner_busy = false;
return true;
}
} // namespace manipulation
} // namespace isaac
} // namespace nvidia
| 3,225 | C++ | 30.627451 | 83 | 0.726822 |
NVIDIA-ISAAC-ROS/isaac_ros_cumotion/isaac_ros_cumotion_moveit/src/cumotion_move_group_client.cpp | // SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
// Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "isaac_ros_cumotion_moveit/cumotion_move_group_client.hpp"
#include <chrono>
#include <future>
#include <memory>
#include <string>
#include "moveit_msgs/action/move_group.hpp"
#include "moveit_msgs/msg/planning_options.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
namespace nvidia
{
namespace isaac
{
namespace manipulation
{
namespace
{
constexpr unsigned kGetGoalWaitIntervalInMs = 10;
} // namespace
CumotionMoveGroupClient::CumotionMoveGroupClient(const rclcpp::Node::SharedPtr & node)
: result_ready(false),
success(false),
get_goal_handle_(false),
get_result_handle_(false),
node_(node),
client_cb_group_(node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive))
{
client_ = rclcpp_action::create_client<moveit_msgs::action::MoveGroup>(
node_,
"cumotion/move_group",
client_cb_group_);
send_goal_options_ = rclcpp_action::Client<moveit_msgs::action::MoveGroup>::SendGoalOptions();
send_goal_options_.goal_response_callback = std::bind(
&CumotionMoveGroupClient::goalResponseCallback, this, std::placeholders::_1);
send_goal_options_.feedback_callback = std::bind(
&CumotionMoveGroupClient::feedbackCallback, this, std::placeholders::_1, std::placeholders::_2);
send_goal_options_.result_callback = std::bind(
&CumotionMoveGroupClient::resultCallback, this, std::placeholders::_1);
}
void CumotionMoveGroupClient::updateGoal(
const planning_scene::PlanningSceneConstPtr & planning_scene,
const planning_interface::MotionPlanRequest & req)
{
planning_request_ = req;
planning_scene->getPlanningSceneMsg(planning_scene_);
}
bool CumotionMoveGroupClient::sendGoal()
{
result_ready = false;
success = false;
moveit_msgs::msg::PlanningOptions plan_options;
plan_options.planning_scene_diff = planning_scene_;
if (!client_->wait_for_action_server()) {
RCLCPP_ERROR(node_->get_logger(), "Action server not available after waiting");
rclcpp::shutdown();
}
auto goal_msg = moveit_msgs::action::MoveGroup::Goal();
goal_msg.planning_options = plan_options;
goal_msg.request = planning_request_;
RCLCPP_INFO(node_->get_logger(), "Sending goal");
auto goal_handle_future = client_->async_send_goal(goal_msg, send_goal_options_);
goal_h_ = goal_handle_future;
get_result_handle_ = true;
get_goal_handle_ = true;
return true;
}
void CumotionMoveGroupClient::getGoal()
{
using namespace std::chrono_literals;
if (get_goal_handle_) {
if (goal_h_.wait_for(std::chrono::milliseconds(kGetGoalWaitIntervalInMs)) !=
std::future_status::ready)
{
return;
}
GoalHandle::SharedPtr goal_handle = goal_h_.get();
if (!goal_handle) {
RCLCPP_ERROR(node_->get_logger(), "Goal was rejected by server");
return;
}
auto result_future = client_->async_get_result(goal_handle);
result_future_ = result_future;
get_goal_handle_ = false;
}
if (get_result_handle_) {
if (result_future_.wait_for(std::chrono::milliseconds(kGetGoalWaitIntervalInMs)) !=
std::future_status::ready)
{
return;
}
auto res = result_future_.get();
RCLCPP_INFO(node_->get_logger(), "Checking results");
if (res.code == rclcpp_action::ResultCode::SUCCEEDED) {
RCLCPP_INFO(node_->get_logger(), "Success");
result_ready = true;
success = false;
plan_response.error_code = res.result->error_code;
if (plan_response.error_code.val == 1) {
success = true;
plan_response.trajectory_start = res.result->trajectory_start;
plan_response.group_name = planning_request_.group_name;
plan_response.trajectory.resize(1);
plan_response.trajectory[0] = res.result->planned_trajectory;
plan_response.processing_time = {res.result->planning_time};
}
} else {
RCLCPP_INFO(node_->get_logger(), "Failed");
}
get_result_handle_ = false;
}
}
void CumotionMoveGroupClient::goalResponseCallback(const GoalHandle::SharedPtr & future)
{
auto goal_handle = future.get();
if (!goal_handle) {
RCLCPP_ERROR(node_->get_logger(), "Goal was rejected by server");
result_ready = true;
success = false;
} else {
RCLCPP_INFO(node_->get_logger(), "Goal accepted by server, waiting for result");
}
}
void CumotionMoveGroupClient::feedbackCallback(
GoalHandle::SharedPtr,
const std::shared_ptr<const moveit_msgs::action::MoveGroup::Feedback> feedback)
{
std::string status = feedback->state;
RCLCPP_INFO(node_->get_logger(), "Checking status");
RCLCPP_INFO(node_->get_logger(), status.c_str());
}
void CumotionMoveGroupClient::resultCallback(const GoalHandle::WrappedResult & result)
{
RCLCPP_INFO(node_->get_logger(), "Received result");
result_ready = true;
success = false;
switch (result.code) {
case rclcpp_action::ResultCode::SUCCEEDED:
break;
case rclcpp_action::ResultCode::ABORTED:
RCLCPP_ERROR(node_->get_logger(), "Goal was aborted");
return;
case rclcpp_action::ResultCode::CANCELED:
RCLCPP_ERROR(node_->get_logger(), "Goal was canceled");
return;
default:
RCLCPP_ERROR(node_->get_logger(), "Unknown result code");
return;
}
plan_response.error_code = result.result->error_code;
if (plan_response.error_code.val == 1) {
success = true;
plan_response.trajectory_start = result.result->trajectory_start;
plan_response.group_name = planning_request_.group_name;
plan_response.trajectory = {result.result->planned_trajectory};
plan_response.processing_time = {result.result->planning_time};
}
}
} // namespace manipulation
} // namespace isaac
} // namespace nvidia
| 6,424 | C++ | 29.595238 | 100 | 0.696762 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.