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
|
---|---|---|---|---|---|---|
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/poc/services/simple/__init__.py
|
from .extension import *
| 25 |
Python
| 11.999994 | 24 | 0.76 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/config/extension.toml
|
[package]
version = "1.0.0"
authors = ["Josh Parker"]
title = "poc services headless"
description="A simple headless service"
readme = "docs/README.md"
changelog="docs/CHANGELOG.md"
icon = "data/icon.png"
[dependencies]
"omni.services.core" = {}
# Main python module this extension provides, it will be publicly available as "import poc.services.simple".
[[python.module]]
name = "poc.services.headless"
| 407 |
TOML
| 24.499998 | 108 | 0.732187 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 |
Markdown
| 18.888887 | 80 | 0.702247 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/docs/README.md
|
# Python Extension Example [poc.services.simple]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 178 |
Markdown
| 34.799993 | 126 | 0.786517 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/docs/index.rst
|
poc.services.simple
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"poc.services.simple"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 339 |
reStructuredText
| 15.190475 | 43 | 0.619469 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/poc/services/headless/extension.py
|
import omni.ext
from omni.services.core import main
def hello_headless():
return "hello headless service!!"
class PocServicesHeadlessExtension(omni.ext.IExt):
def on_startup(self, ext_id):
main.register_endpoint("get", "/hello_headless", hello_headless)
def on_shutdown(self):
main.deregister_endpoint("get", "/hello_headless")
| 360 |
Python
| 24.785713 | 72 | 0.705556 |
parkerjgit/omniverse-sandbox/poc.extensions/headless-service/exts/poc.services.headless/poc/services/headless/__init__.py
|
from .extension import *
| 25 |
Python
| 11.999994 | 24 | 0.76 |
parkerjgit/omniverse-sandbox/poc.extensions/containerized-service/hello_world.py
|
from omni.services.core import main
def hello_world():
return "hello containerized service"
main.register_endpoint("get", "/hello-world", hello_world)
| 156 |
Python
| 25.166662 | 58 | 0.75 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/readme.md
|
# Omniverse farm on Aks
## Getting Started
## Stack
* Omniverse Services/Applications:
* Farm
* Terraform - for provisioning infrasture
* Docker - container virtualization
* Kubernetes - container orchestration
* NVIDIA device plugin for Kubernetes - req. to run GPU enabled containers in your Kubernetes cluster.
* Helm - Package Manager for Kubernetes
* Azure Services
* AKS
## Prerequisites
* [Omniverse farm ~~prerequisites~~ recommendations](https://docs.omniverse.nvidia.com/app_farm/app_farm/omniverse_farm_cloud_setup.html#prerequisites)
* Two types of node configurations are needed: Farm services and farm workers.
* Recommended:
* Farm containers are currently very large (improvements are coming) with a couple of gigs, and your local system storage would need to support that. We tend to run with 100GB file systems size.
* Farm services:
* 3 x the equivalent of an t3.large (ie., 2vCPU, 8GB of Ram)
* Farm Workers:
* Kubernetes >= 1.24. Must be supported by the GPU operator (min = 1.16)
* support the NVIDIA drivers, device plugin and container toolkit and have the GPU Operator installed on them.
* For OV based GPU workloads they'll need to be RTX enabled GPUs for best results.
* [NVIDIA device plugin prerequisites](https://github.com/NVIDIA/k8s-device-plugin#prerequisites):
* NVIDIA drivers ~= 384.81
* nvidia-docker >= 2.0 || nvidia-container-toolkit >= 1.7.0 (>= 1.11.0 to use integrated GPUs on Tegra-based systems)
* nvidia-container-runtime configured as the default low-level runtime
* Kubernetes version >= 1.10
* [NVIDIA Container Toolkit prerequisites]():
* GNU/Linux x86_64 with kernel version > 3.10
* Docker >= 19.03 (recommended, but some distributions may include older versions of Docker. The minimum supported version is 1.12)
* NVIDIA GPU with Architecture >= Kepler (or compute capability 3.0)
* NVIDIA Linux drivers >= 418.81.07 (Note that older driver releases or branches are unsupported.)
## Setup
### 1. Deploy Kubernetes Cluster
> TODO: Verify that version of k8s is supported by farm (ie., >= 1.16, >= 1.24 recommended)
1. Configure resources to be created.
1. Create `/infra-compute/terraform.tfvars` file:
```
resource_group_name = "saz-resources"
ssh_public_key = "~/.ssh/id_rsa.pub"
```
* Notes,
* if you don't have an ssh key pair, [create one](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/ssh-from-windows#create-an-ssh-key-pair)
* add "GPU" node label to nodes in node pool, so that we can easily target them by label (when we install nvidia device plugin)
1. Create cloud resources
1. Initialize terraform and provision cloud resources.
```sh
# from `/infra-compute` directory:
terraform init
terraform plan
terraform apply
```
1. Perform sanity checks
1. connect to cluster
```
az aks get-credentials \
--resource-group "dt-sandbox-resources" \
--name "ovfarm-dev-aks-cluster"
```
1. inspect cluster
```
kubectl get all
kubectl describe svc kubernetes
```
### 2a. Deploy Node Pool from image (Recommended)
1. Update your cluster to use the AKS GPU image
1. Install aks preview extension
```
az extension add --name aks-preview
az extension update --name aks-preview
```
1. Register the GPUDedicatedVHDPreview feature (enables feature flag)
```
az feature register --namespace "Microsoft.ContainerService" --name "GPUDedicatedVHDPreview"
az feature show --namespace "Microsoft.ContainerService" --name "GPUDedicatedVHDPreview"
```
1. Register provider (hack to propage the change)
```
az provider register --namespace Microsoft.ContainerService
```
1. Deploy node pool
```
az aks nodepool add \
--resource-group dt-sandbox-resources \
--cluster-name ovfarm-dev-aks-cluster \
--name gpunodepool \
--node-count 1 \
--node-vm-size Standard_NV12ads_A10_v5 \
--node-taints sku=gpu:NoSchedule \
--aks-custom-headers UseGPUDedicatedVHD=true \
--enable-cluster-autoscaler \
--min-count 1 \
--max-count 3 \
--os-sku Ubuntu \
--mode User \
--labels vm_type=GPU
```
. Verify that GPUs are schedulable
```
kubectl get nodes
kubectl describe node <node_name>
```
* Should see "nvidia.com/gpu" listed under "Capacity"
1. Run a sample GPU workload
```sh
kubectl apply -f ./jobs/samples-tf-mnist-demo.yaml
```
1. Get job status
```
kubectl get jobs samples-tf-mnist-demo --watch
```1
1. Get logs
```
kubectl get pods --selector app=samples-tf-mnist-demo
kubectl logs <pod_name>
````
1. [optionally] Update nodepool e.g. to add labels (expensive to recreate)
```
az aks nodepool update \
--resource-group dt-sandbox-resources \
--cluster-name ovfarm-dev-aks-cluster \
--name gpunodepool \
--node-taints "" \
--labels vm_type=GPU
```
1. [optionally] Delete and re-deploy eg., to change vm-size
```
az aks nodepool delete \
--resource-group dt-sandbox-resources \
--cluster-name ovfarm-dev-aks-cluster \
--name gpunodepool
az aks nodepool add ... (see Deploy node pool above)
```
1. [optionally] Clean-up resources
```
az aks nodepool delete \
--resource-group dt-sandbox-resources \
--cluster-name ovfarm-dev-aks-cluster \
--name gpunodepool
```
### 2b. Deploy GPU Node Pool from Daemonset
tbd...
### 3. Deploy Farm
1. Prerequisites
1. NGC CLI
1. windows - download from https://ngc.nvidia.com/setup/installers/cli
1. wsl/linux (amd64):
```
wget --content-disposition https://ngc.nvidia.com/downloads/ngccli_linux.zip && unzip ngccli_linux.zip && chmod u+x ngc-cli/ngc
find ngc-cli/ -type f -exec md5sum {} + | LC_ALL=C sort | md5sum -c ngc-cli.md5
echo "export PATH=\"\$PATH:$(pwd)/ngc-cli\"" >> ~/.bash_profile && source ~/.bash_profile
ngc --version
```
1. NGC API Key
1. generate from https://ngc.nvidia.com/setup
1. login to ngc from cli with API Key
```
ngc config set
````
1. K8s Cluster
1. connect to cluster
```
az aks get-credentials \
--resource-group "dt-sandbox-resources" \
--name "ovfarm-dev-aks-cluster"
```
1. Define variables
```
K8S_NAMESPACE="ovfarm"
NGC_API_KEY=<NGC_API_TOKEN>
1. Create namespace
```
kubectl create namespace $K8S_NAMESPACE
```
* Question: can this be default namespace?
1. Create [Docker Config Secret](https://kubernetes.io/docs/concepts/configuration/secret/#docker-config-secrets)
```
kubectl create secret docker-registry my-registry-secret \
--namespace $K8S_NAMESPACE \
--docker-server="nvcr.io" \
--docker-username='$oauthtoken' \
--docker-password=$NGC_API_KEY
```
1. fetch helm chart
```
helm fetch https://helm.ngc.nvidia.com/nvidia/omniverse/charts/omniverse-farm-0.3.2.tgz \
--username='$oauthtoken' \
--password=$NGC_API_KEY
```
1. configure deployment. besure to use correct dns zone for host in `values.yaml` file. Can get DNS Zone Name with:
```sh
az aks show
--resource-group "ov-resources"
--name "ovfarm-dev-aks-cluster"
--query addonProfiles.httpApplicationRouting.config.HTTPApplicationRoutingZoneName
```
1. install farm
```
helm upgrade \
--install \
omniverse-farm \
omniverse-farm-0.3.2.tgz \
--create-namespace \
--namespace $K8S_NAMESPACE \
--values ./containers/farm/values.yaml
helm list -n ovfarm
```
1. [optionally] update deployment
```
helm upgrade --values ./containers/farm/values.yaml omniverse-farm omniverse-farm-0.3.2.tgz --namespace ovfarm
```
1. Validate the installation.
1. Check that Pods are running
```sh
kubectl get pods -o wide $K8S_NAMESPACE
```
1. Ensure all pods in ready state
```sh
kubectl -n $K8S_NAMESPACE wait --timeout=300s --for condition=Ready pods --all
```
* Note, controller takes a very long time to initialize
1. Check for errors for any pod that aren't ready
```sh
kubectl describe pod <pod_name>
```
1. Check endpoints with curl pod
1. [run curl pod](https://kubernetes.io/docs/tutorials/services/connect-applications-service/#accessing-the-service)
```sh
kubectl run curl --namespace=$K8S_NAMESPACE --image=radial/busyboxplus:curl -i --tty -- sh
# use "exec" if curl pod already exists
kubectl exec curl --namespace=$K8S_NAMESPACE -i --tty -- sh
```
1. check endpoints
```sh
[ root@curl:/ ]$ check_endpoint() {
url=$1
curl -s -o /dev/null "$url" && echo -e "[UP]\t${url}" || echo -e "[DOWN]\t${url}"
}
[ root@curl:/ ]$ check_farm_status() {
echo "======================================================================"
echo "Farm status:"
echo "----------------------------------------------------------------------"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/agents/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/dashboard/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/jobs/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/jobs/load"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/logs/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/retries/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/tasks/status"
check_endpoint "farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/tasks/list?status=submitted"
echo "======================================================================"
}
[ root@curl:/ ]$ check_farm_status
```
1. log into queue management dashboard
http://farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/dashboard
http://farm.23711a66dc7f46649e88.eastus.aksapp.io/queue/management/ui/
1. Find api docs
http://farm.23711a66dc7f46649e88.eastus.aksapp.io/docs
* Issue Cannot find docs.
1. Explore ConfigMaps
### 4. Submit job
1. Prerequisites
* Python
* Script dependancies
```
pip install requests
pip install toml
```
1. Download sample job
download the example sample jobs:
```
ngc registry resource download-version "nvidia/omniverse-farm/cpu_verification:1.0.0"
ngc registry resource download-version "nvidia/omniverse-farm/gpu_verification:1.0.0"
```
1. Get Jobs API Key
```sh
kubectl get cm omniverse-farm-jobs -o yaml -n $K8S_NAMESPACE | grep api_key
FARM_API_KEY=<api_key>
```
1. Upload job definitions to cluster
```sh
FARM_BASE_URL="http://farm.23711a66dc7f46649e88.eastus.aksapp.io"
python3 ./job_definition_upload.py df.kit --farm-url=$FARM_BASE_URL --api-key=$FARM_API_KEY
python3 ./job_definition_upload.py gpu.kit --farm-url=$FARM_BASE_URL --api-key=$FARM_API_KEY
```
1. Get Job definitions
```sh
curl -X 'GET' \
"${FARM_BASE_URL}/agent/operator/job/definitions" \
-H 'accept: application/json'
```
* TODO: wrong endpoint. fix^
1. Submit CPU test job (df)
```sh
curl -X "POST" \
"${FARM_BASE_URL}/queue/management/tasks/submit" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"user": "testuser",
"task_type": "df",
"task_args": {},
"metadata": {
"_retry": {
"is_retryable": false
}
},
"status": "submitted"
}'
```
1. Submit GPU test job
```sh
curl -X "POST" \
"${FARM_BASE_URL}/queue/management/tasks/submit" \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"user": "testuser",
"task_type": "gpu",
"task_args": {},
"metadata": {
"_retry": {
"is_retryable": false
}
},
"status": "submitted"
}'
```
https://catalog.ngc.nvidia.com/orgs/nvidia/teams/omniverse-farm/resources/gpu_verification/quick-start-guide
## Troubleshooting
### How to get current installed drivers?
### Are nvidia drivers pre-installed on NV series VMs?
### azurerm terrafrom provider support for enabling aks preview feature GPUDedicatedVHDPreview using terraform.
* pending [azurerm custom header support](https://github.com/hashicorp/terraform-provider-azurerm/issues/6793)
* [failed PR](https://github.com/hashicorp/terraform-provider-azurerm/pull/14178) tried to fix this.
* pending [AKS custom feature support](https://github.com/Azure/AKS/issues/2757)
* possible work around using [xpd provider](https://registry.terraform.io/providers/0x2b3bfa0/xpd/latest/docs/guides/test)
### ISSUE: Cannot find swagger docs at `/docs` after deploying helm chart to AKS
Helm chart does not seem to deploy a swagger docs.
### ISSUE: kubectl not working on wsl2
fix is to copy over kube config
```
mkdir ~/.kube \ && cp /mnt/c/Users/nycjyp/.kube/config ~/.kube
```
## ref
* https://docs.omniverse.nvidia.com/app_farm/app_farm/omniverse_farm_cloud_setup.html
* https://github.com/NVIDIA/k8s-device-plugin#deployment-via-helm
* https://www.youtube.com/watch?v=KplFFvj3XRk
* https://itnext.io/enabling-nvidia-gpus-on-k3s-for-cuda-workloads-a11b96f967b0
* https://learn.microsoft.com/en-us/azure/aks/node-access - node access
* https://forums.developer.nvidia.com/t/set-up-cloud-rendering-using-aws-farm-queue/221879/3?u=mati-nvidia
* https://docs.nvidia.com/datacenter/tesla/tesla-installation-notes/index.html
* https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#post-installation-actions
* https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/
### configure GPU nodes
* https://learn.microsoft.com/en-us/azure/aks/gpu-cluster#manually-install-the-nvidia-device-plugin
* https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/aks/gpu-cluster.md
### Setting up VMs
* https://azuremarketplace.microsoft.com/en-us/marketplace/apps/nvidia.ngc_azure_17_11?tab=overview
* https://michaelcollier.wordpress.com/2017/08/04/how-to-setup-nvidia-driver-on-nv-series-azure-vm/
| 15,071 |
Markdown
| 36.68 | 202 | 0.634397 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/containers/nvidia-device-plugin/values.yaml
|
# overrides https://github.com/NVIDIA/k8s-device-plugin/blob/v0.13.0/deployments/helm/nvidia-device-plugin/values.yaml
nodeSelector:
vm_type: "GPU"
| 151 |
YAML
| 36.999991 | 118 | 0.774834 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/containers/farm/secrets.yaml
|
apiVersion: v1
kind: Secret
metadata:
name: server-vars
namespace: default
stringData:
docker-registry: 'my-registry-secret'
| 130 |
YAML
| 17.714283 | 39 | 0.769231 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/containers/farm/values.yaml
|
global:
imagePullSecrets:
- name: my-registry-secret
ingress:
host: "farm.23711a66dc7f46649e88.eastus.aksapp.io"
annotations:
kubernetes.io/ingress.class: addon-http-application-routing
controller:
serviceConfig:
k8s:
jobTemplateSpecOverrides:
imagePullSecrets:
- name: my-registry-secret
dashboard:
nodeSelector:
vm_type: CPU
| 388 |
YAML
| 19.473683 | 65 | 0.693299 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/jobs/sample-tf-minst-demo.yaml
|
apiVersion: batch/v1
kind: Job
metadata:
labels:
app: samples-tf-mnist-demo
name: samples-tf-mnist-demo
spec:
template:
metadata:
labels:
app: samples-tf-mnist-demo
spec:
containers:
- name: samples-tf-mnist-demo
image: mcr.microsoft.com/azuredocs/samples-tf-mnist-demo:gpu
args: ["--max_steps", "500"]
imagePullPolicy: IfNotPresent
resources:
limits:
nvidia.com/gpu: 1
restartPolicy: OnFailure
tolerations:
- key: "sku"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
| 611 |
YAML
| 22.538461 | 68 | 0.589198 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/jobs/cpu_verification_v1.0.0/job_definition_upload.py
|
#!/usr/bin/env python3
import argparse
from dataclasses import (
asdict,
dataclass,
field,
)
from typing import (
Dict,
Optional,
)
try:
import requests
except ImportError:
raise Exception("'requests' python package is required, install and try again. 'pip install requests'")
try:
import toml
except ImportError:
raise Exception("'toml' python package is required, install and try again. 'pip install toml'")
@dataclass
class _JobDefinition:
name: str
job_type: str
command: str
job_spec_path: Optional[str] = None
args: list = field(default_factory=list)
task_function: Optional[str] = None
env: Dict = field(default_factory=dict)
log_to_stdout: Optional[bool] = True
extension_paths: list = field(default_factory=list)
allowed_args: Dict = field(default_factory=dict)
headless: Optional[bool] = True
active: Optional[bool] = True
unresolved_command_path: Optional[str] = None
success_return_codes: list = field(default_factory=lambda: [0])
capacity_requirements: Dict = field(default_factory=dict)
working_directory: Optional[str] = ""
container: Optional[str] = None
def _load_job_definitions(job_config_filepath: str, force: bool = False):
job_config = toml.load(job_config_filepath)
jobs = job_config.get("job")
if not jobs:
raise Exception(f"No job definitions found in config file: {job_config_filepath}")
job_definitions = []
for job_name, params in jobs.items():
if not params.get("container"):
print(f"WARNING: There is no container defined for '{job_name}'.")
if "unresolved_command_path" not in params:
params["unresolved_command_path"] = params["command"]
if "job_spec_path" not in params:
params["job_spec_path"] = str(job_config_filepath)
try:
job_definition = _JobDefinition(**params)
except TypeError as exc:
raise Exception(f"Error processing job definition '{job_name}'. {exc}") from exc
job_definitions.append(job_definition)
return job_definitions
def upload_job_definitions(farm_url, job_definitions_file, api_key, timeout):
jobs_save_endpoint = f"{farm_url.rstrip('/')}/queue/management/jobs/save"
job_defs = _load_job_definitions(job_definitions_file)
print(f"Found '{len(job_defs)}' Job definition(s) in '{job_definitions_file}'")
for job in job_defs:
print(f"\nUploading Job definition: '{job.name}'")
response = requests.post(
url=jobs_save_endpoint,
json=asdict(job),
timeout=timeout,
headers={"X-API-KEY": api_key},
)
response.raise_for_status()
print(f'Response: {response.json()}')
def main():
parser = argparse.ArgumentParser(description="Upload and save job definitions found in the job config")
parser.add_argument('job_definitions_file', help="TOML file containing the Job definitions.")
parser.add_argument('--farm-url', help="Farm base URL.", required=True)
parser.add_argument('--api-key', help="Jobs API Key.", required=True)
parser.add_argument('--timeout', type=int, default=60, help="Request timeout.")
args = parser.parse_args()
upload_job_definitions(args.farm_url, args.job_definitions_file, args.api_key, args.timeout)
if __name__ == '__main__':
main()
| 3,404 |
Python
| 31.122641 | 107 | 0.659224 |
parkerjgit/omniverse-sandbox/poc.farmOnAks/jobs/gpu_verification_v1.0.0/job_definition_upload.py
|
#!/usr/bin/env python3
import argparse
from dataclasses import (
asdict,
dataclass,
field,
)
from typing import (
Dict,
Optional,
)
try:
import requests
except ImportError:
raise Exception("'requests' python package is required, install and try again. 'pip install requests'")
try:
import toml
except ImportError:
raise Exception("'toml' python package is required, install and try again. 'pip install toml'")
@dataclass
class _JobDefinition:
name: str
job_type: str
command: str
job_spec_path: Optional[str] = None
args: list = field(default_factory=list)
task_function: Optional[str] = None
env: Dict = field(default_factory=dict)
log_to_stdout: Optional[bool] = True
extension_paths: list = field(default_factory=list)
allowed_args: Dict = field(default_factory=dict)
headless: Optional[bool] = True
active: Optional[bool] = True
unresolved_command_path: Optional[str] = None
success_return_codes: list = field(default_factory=lambda: [0])
capacity_requirements: Dict = field(default_factory=dict)
working_directory: Optional[str] = ""
container: Optional[str] = None
def _load_job_definitions(job_config_filepath: str, force: bool = False):
job_config = toml.load(job_config_filepath)
jobs = job_config.get("job")
if not jobs:
raise Exception(f"No job definitions found in config file: {job_config_filepath}")
job_definitions = []
for job_name, params in jobs.items():
if not params.get("container"):
print(f"WARNING: There is no container defined for '{job_name}'.")
if "unresolved_command_path" not in params:
params["unresolved_command_path"] = params["command"]
if "job_spec_path" not in params:
params["job_spec_path"] = str(job_config_filepath)
try:
job_definition = _JobDefinition(**params)
except TypeError as exc:
raise Exception(f"Error processing job definition '{job_name}'. {exc}") from exc
job_definitions.append(job_definition)
return job_definitions
def upload_job_definitions(farm_url, job_definitions_file, api_key, timeout):
jobs_save_endpoint = f"{farm_url.rstrip('/')}/queue/management/jobs/save"
job_defs = _load_job_definitions(job_definitions_file)
print(f"Found '{len(job_defs)}' Job definition(s) in '{job_definitions_file}'")
for job in job_defs:
print(f"\nUploading Job definition: '{job.name}'")
response = requests.post(
url=jobs_save_endpoint,
json=asdict(job),
timeout=timeout,
headers={"X-API-KEY": api_key},
)
response.raise_for_status()
print(f'Response: {response.json()}')
def main():
parser = argparse.ArgumentParser(description="Upload and save job definitions found in the job config")
parser.add_argument('job_definitions_file', help="TOML file containing the Job definitions.")
parser.add_argument('--farm-url', help="Farm base URL.", required=True)
parser.add_argument('--api-key', help="Jobs API Key.", required=True)
parser.add_argument('--timeout', type=int, default=60, help="Request timeout.")
args = parser.parse_args()
upload_job_definitions(args.farm_url, args.job_definitions_file, args.api_key, args.timeout)
if __name__ == '__main__':
main()
| 3,404 |
Python
| 31.122641 | 107 | 0.659224 |
parkerjgit/omniverse-sandbox/poc.farmOnLinux/readme.md
|
# Omniverse Farm on Linux (Headless)
## Overview
1. Queue
1. Install Queue (service)
2. Configure Queue URL (for agents to connect. Also, this is base url for api endpoint)
3. Navigate to dashboard at: `http://<queue_url>/queue/management/ui/`
2. Agent
1. Install Agent
1. Connect to Queue
2. Configure Jobs directory (this is where scripts and kits go)
3. Navigate to dashboard at: `http://<agent_url>/agent/management/ui/`
## Running Farm (after setup)
```
/opt/ove/ov-farm-queue/queue.sh &
/opt/ove/ov-farm-agent/agent.sh &
```
## Setup Queue
1. Install Dependencies
```
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libatomic1 \
libxi6 \
libxrandr2 \
libxt6 \
libegl1 \
libglu1-mesa \
libgomp1 \
libsm6 \
unzip
```
1. Instal Farm Queue package
```sh
sudo mkdir -p /opt/ove/ov-farm-queue
sudo curl https://d4i3qtqj3r0z5.cloudfront.net/farm-queue-launcher%40103.1.0%2Bmaster.33.956d9b7d.teamcity.linux-x86_64.release.zip --output /opt/ove/ov-farm-queue/farm-queue-launcher.zip
sudo unzip /opt/ove/ov-farm-queue/farm-queue-launcher.zip
sudo rm /opt/ove/ov-farm-queue/farm-queue-launcher.zip
```
1. Install the Kit SDK package
```sh
sudo mkdir -p /opt/ove/ov-farm-queue/kit
sudo curl https://d4i3qtqj3r0z5.cloudfront.net/[email protected]%2Brelease.6024.1fc2e16c.tc.linux-x86_64.release.zip --output /opt/ove/ov-farm-queue/kit/kit-sdk-launcher.zip
sudo unzip /opt/ove/ov-farm-queue/kit/kit-sdk-launcher.zip -d /opt/ove/ov-farm-queue/
sudo rm /opt/ove/ov-farm-queue/kit/kit-sdk-launcher.zip
```
1. Recursively set owner of `ov-farm-queue` and subdirectories to non root user
```
sudo chown -R josh:josh ov-farm-queue
```
1. Create launch script
```
cat << 'EOF' > /opt/ove/ov-farm-queue/queue.sh
#!/bin/bash
BASEDIR=$(dirname "$0")
exec $BASEDIR/kit/kit $BASEDIR/apps/omni.farm.queue.headless.kit \
--ext-folder $BASEDIR/exts-farm-queue \
--/exts/omni.services.farm.management.tasks/dbs/task-persistence/connection_string=sqlite:///$BASEDIR//task-management.db
EOF
```
* Note, Queue URL is automatically set to `http://localhost:8222`
1. Make queue script executable
```
sudo chmod +x /opt/ove/ov-farm-queue/queue.sh
```
1. Start Queue
```
./queue.sh &
```
1. Navigate to Queue Management dashboard(s):
```sh
# http://<queue_url>/queue/management/ui/
http://localhost:8222/queue/management/ui/
```
1. Find Queue Management API docs
```sh
# http://<queue_url>/docs
http://localhost:8222/docs
```
1. Perform health check
```
curl -X GET 'http://localhost:8222/status' \
-H 'accept: application/json'
```
## Setup Agent
1. Install Dependencies
```
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libatomic1 \
libxi6 \
libxrandr2 \
libxt6 \
libegl1 \
libglu1-mesa \
libgomp1 \
libsm6 \
unzip
```
1. Install Farm Agent Package
```
sudo mkdir -p /opt/ove/ov-farm-agent
sudo curl https://d4i3qtqj3r0z5.cloudfront.net/farm-agent-launcher%40103.1.0%2Bmaster.53.238d4340.teamcity.linux-x86_64.release.zip --output /opt/ove/ov-farm-agent/farm-agent-launcher.zip
sudo unzip /opt/ove/ov-farm-agent/farm-agent-launcher.zip -d /opt/ove/ov-farm-agent/
sudo rm /opt/ove/ov-farm-agent/farm-agent-launcher.zip
```
1. Install the Kit SDK package
```sh
sudo mkdir -p /opt/ove/ov-farm-agent/kit
sudo curl https://d4i3qtqj3r0z5.cloudfront.net/[email protected]%2Brelease.6024.1fc2e16c.tc.linux-x86_64.release.zip --output /opt/ove/ov-farm-agent/kit/kit-sdk-launcher.zip
sudo unzip /opt/ove/ov-farm-agent/kit/kit-sdk-launcher.zip -d /opt/ove/ov-farm-agent/kit/
sudo rm /opt/ove/ov-farm-agent/kit/kit-sdk-launcher.zip
```
1. Recursively set owner of `ov-farm-agent` and subdirectories to non root user
```
sudo chown -R josh:josh ov-farm-agent
```
1. Create launch script (configure jobs directory and queue host)
```
cat << 'EOF' > /opt/ove/ov-farm-agent/agent.sh
#!/bin/bash
JOBSDIR="~/code/sandbox/omniverse-sandbox/poc.farmOnLinux/agent/jobs"
exec $BASEDIR/kit/kit $BASEDIR/apps/omni.farm.agent.headless.kit \
--ext-folder $BASEDIR/exts-farm-agent \
--/exts/omni.services.farm.agent.operator/job_store_args/job_directories/0=$JOBSDIR/* \
--/exts/omni.services.farm.agent.controller/manager_host=http://localhost:8222 \
--/exts/omni.services.farm.agent.operator/manager_host=http://localhost:8222
EOF
```
1. Make agent script executable
```
chmod +x /opt/ove/ov-farm-agent/agent.sh
```
1. Start agent (in background)
```
./agent.sh &
```
* [Expected Error](https://docs.omniverse.nvidia.com/app_farm/app_farm/agent.html#output-log) if no supported GPU capacity:
```
2023-01-02 22:49:01 [2,349ms] [Error] [omni.services.farm.facilities.agent.capacity.managers.base] Failed to load capacities for omni.services.farm.facilities.agent.capacity.GPU: NVML Shared Library Not Found
```
1. Navigate to Job Management Dashboard:
```sh
# http://<agent_url>/agent/management/ui/
http://localhost:8223/agent/management/ui/
```
* Note, this form simply edits the file specified by `job-spec-path` property (ie., Job definition path) in configured jobs directory. The effect is same as manually editing file, however not all [properties](https://docs.omniverse.nvidia.com/app_farm/app_farm/guides/creating_job_definitions.html#schema-reference) are exposed in form.
1. Find Agent Management API docs:
```sh
# http://<agent_url>/docs
http://localhost:8223/docs
```
1. Perform health check
```
curl -X GET 'http://localhost:8223/status' \
-H 'accept: application/json'
```
## Job: Hello World
1. [If you did NOT configure jobs directory to use repo] Copy `hello-omniverse` folder to configured jobs directory, e.g., `/opt/ove/ov-farm-agent/jobs`
```
cp -R poc.farmOnLinux/agent/jobs/hello-omniverse /opt/ove/ov-farm-agent/jobs/hello-omniverse
```
> **Notes**:
> * `job type` property is set to "base" (ie., Command or executable) to allow execution of arbitrary shell commands or executable files.
> * `command` property is set to name of shell command "echo". If we were executing a script, this would be the full path to script or executable.
> * `args` (ie., Process arguments) are automatically passed
> * `allowed_args` are passed by the client
1. [If nec] Restart agent to pick up job.
```
kill -9 $(lsof -ti tcp:8223)
./agent.sh &
```
> TODO: what is a better way to restart agent
1. [Optionally] Verify Job has been added by Getting list of jobs
```
curl -X GET 'http://localhost:8223/agent/operator/available' \
-H 'accept: application/json'
```
1. Submit task using `queue/management/tasks/submit` endpoint:
```
curl -X POST "http://localhost:8222/queue/management/tasks/submit" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{"user":"my-user-id","task_type":"hello-omniverse","task_args":{},"task_comment":"My job!"}'
```
1. Get Status of task:
```sh
# of task with task id (returned when you submitted task)
curl -X GET 'http://localhost:8222/queue/management/tasks/info/848973c4-5864-416b-976f-56a94cfc8258' \
-H 'accept: application/json'
# of all tasks matching type:
curl -X GET 'http://localhost:8222/queue/management/tasks/list?task_type=hello-omniverse' \
-H 'accept: application/json'
```
## Job: Run a Simple Python Script
1. [If you did NOT configure jobs directory to use repo] Copy `simple-python-script` folder to configured jobs directory, e.g., `/opt/ove/ov-farm-agent/jobs`
```sh
cp -R poc.farmOnLinux/agent/jobs/simple-python-script /opt/ove/ov-farm-agent/jobs/simple-python-script
```
1. [If nec] Restart agent to pick up job.
```
kill -9 $(lsof -ti tcp:8223)
./agent.sh &
```
1. [Optionally] Verify Job has been added by Getting list of jobs
```
curl -X GET 'http://localhost:8223/agent/operator/available' \
-H 'accept: application/json'
```
1. Submit task using `queue/management/tasks/submit` endpoint:
```
curl -X POST "http://localhost:8222/queue/management/tasks/submit" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{"user":"my-user-id","task_type":"simple-python-script","task_args":{"name":"Python Script"},"task_comment":"My job!"}'
```
1. Get Status of task:
```sh
# of task with task id (returned when you submitted task)
curl -X GET 'http://localhost:8222/queue/management/tasks/info/848973c4-5864-416b-976f-56a94cfc8258' \
-H 'accept: application/json'
# of all tasks matching type:
curl -X GET 'http://localhost:8222/queue/management/tasks/list?task_type=simple-python-script' \
-H 'accept: application/json'
```
## Questions
* How to get running agent to pick up changes to jobs without restarting service?
| 9,351 |
Markdown
| 37.171428 | 340 | 0.662603 |
parkerjgit/omniverse-sandbox/poc.farmOnLinux/agent/jobs/simple-python-script/script.py
|
import argparse
def main():
parser = argparse.ArgumentParser(description="A simple command-line script")
parser.add_argument("--name", help="Your name")
args = parser.parse_args()
print(f"Hello, {args.name}!")
if __name__ == "__main__":
main()
| 267 |
Python
| 21.333332 | 80 | 0.632959 |
Coriago/examplo-ros2/README.md
|
# examplo-ros2
ROS2 pkgs and resources for examplo bot
## Setup steps
-------
- Install ROS2
- Build+Install repo
- Install Isaac Sim
- Make ROS2 Default Ext
1. Open `~/.local/share/ov/pkg/isaac_sim-2022.1.1/apps/omni.isaac.sim.base.kit` \
2. search for `omni.isaac.ros_bridge` and change it to `omni.isaac.ros2_bridge`
- Setup Examplobot Extension
1. Open the extension manager by doing `Window -> Extensions`
2. Hit the gear icon and add the path `<path-to-repo>/isaac`
3. Enable the Examplo Bot extension by searching for it and hitting the toggle button.
https://docs.omniverse.nvidia.com/prod_launcher/prod_kit/linux-troubleshooting.html
| 647 |
Markdown
| 31.399998 | 86 | 0.749614 |
Coriago/examplo-ros2/src/mecanum_controller/mecanum_plugin.xml
|
<library path="mecanum_controller">
<class name="mecanum_controller/MecanumController" type="mecanum_controller::MecanumController" base_class_type="controller_interface::ControllerInterface">
<description>
The differential mecanum controller transforms linear and angular velocity messages into signals for each wheel(s) for a differential drive robot.
</description>
</class>
</library>
| 401 |
XML
| 49.249994 | 158 | 0.793017 |
Coriago/examplo-ros2/src/mecanum_controller/test/test_mecanum_controller.cpp
|
// Copyright 2020 PAL Robotics SL.
//
// 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.
#include <gmock/gmock.h>
#include <array>
#include <memory>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "mecanum_controller/mecanum_controller.hpp"
#include "hardware_interface/loaned_command_interface.hpp"
#include "hardware_interface/loaned_state_interface.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "lifecycle_msgs/msg/state.hpp"
#include "rclcpp/rclcpp.hpp"
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
using hardware_interface::HW_IF_POSITION;
using hardware_interface::HW_IF_VELOCITY;
using hardware_interface::LoanedCommandInterface;
using hardware_interface::LoanedStateInterface;
using lifecycle_msgs::msg::State;
using testing::SizeIs;
class TestableMecanumController : public mecanum_controller::MecanumController
{
public:
using MecanumController::MecanumController;
std::shared_ptr<geometry_msgs::msg::TwistStamped> getLastReceivedTwist()
{
std::shared_ptr<geometry_msgs::msg::TwistStamped> ret;
received_velocity_msg_ptr_.get(ret);
return ret;
}
/**
* @brief wait_for_twist block until a new twist is received.
* Requires that the executor is not spinned elsewhere between the
* message publication and the call to this function
*
* @return true if new twist msg was received, false if timeout
*/
bool wait_for_twist(
rclcpp::Executor & executor,
const std::chrono::milliseconds & timeout = std::chrono::milliseconds(500))
{
rclcpp::WaitSet wait_set;
wait_set.add_subscription(velocity_command_subscriber_);
if (wait_set.wait(timeout).kind() == rclcpp::WaitResultKind::Ready)
{
executor.spin_some();
return true;
}
return false;
}
};
class TestMecanumController : public ::testing::Test
{
protected:
static void SetUpTestCase() { rclcpp::init(0, nullptr); }
void SetUp() override
{
controller_ = std::make_unique<TestableMecanumController>();
pub_node = std::make_shared<rclcpp::Node>("velocity_publisher");
velocity_publisher = pub_node->create_publisher<geometry_msgs::msg::TwistStamped>(
controller_name + "/cmd_vel", rclcpp::SystemDefaultsQoS());
}
static void TearDownTestCase() { rclcpp::shutdown(); }
/// Publish velocity msgs
/**
* linear - magnitude of the linear command in the geometry_msgs::twist message
* angular - the magnitude of the angular command in geometry_msgs::twist message
*/
void publish(double linear, double angular)
{
int wait_count = 0;
auto topic = velocity_publisher->get_topic_name();
while (pub_node->count_subscribers(topic) == 0)
{
if (wait_count >= 5)
{
auto error_msg = std::string("publishing to ") + topic + " but no node subscribes to it";
throw std::runtime_error(error_msg);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
++wait_count;
}
geometry_msgs::msg::TwistStamped velocity_message;
velocity_message.header.stamp = pub_node->get_clock()->now();
velocity_message.twist.linear.x = linear;
velocity_message.twist.angular.z = angular;
velocity_publisher->publish(velocity_message);
}
/// \brief wait for the subscriber and publisher to completely setup
void waitForSetup()
{
constexpr std::chrono::seconds TIMEOUT{2};
auto clock = pub_node->get_clock();
auto start = clock->now();
while (velocity_publisher->get_subscription_count() <= 0)
{
if ((clock->now() - start) > TIMEOUT)
{
FAIL();
}
rclcpp::spin_some(pub_node);
}
}
void assignResourcesPosFeedback()
{
std::vector<LoanedStateInterface> state_ifs;
state_ifs.emplace_back(left_wheel_pos_state_);
state_ifs.emplace_back(right_wheel_pos_state_);
std::vector<LoanedCommandInterface> command_ifs;
command_ifs.emplace_back(left_wheel_vel_cmd_);
command_ifs.emplace_back(right_wheel_vel_cmd_);
controller_->assign_interfaces(std::move(command_ifs), std::move(state_ifs));
}
void assignResourcesVelFeedback()
{
std::vector<LoanedStateInterface> state_ifs;
state_ifs.emplace_back(left_wheel_vel_state_);
state_ifs.emplace_back(right_wheel_vel_state_);
std::vector<LoanedCommandInterface> command_ifs;
command_ifs.emplace_back(left_wheel_vel_cmd_);
command_ifs.emplace_back(right_wheel_vel_cmd_);
controller_->assign_interfaces(std::move(command_ifs), std::move(state_ifs));
}
const std::string controller_name = "test_mecanum_controller";
std::unique_ptr<TestableMecanumController> controller_;
const std::vector<std::string> left_wheel_names = {"left_wheel_joint"};
const std::vector<std::string> right_wheel_names = {"right_wheel_joint"};
std::vector<double> position_values_ = {0.1, 0.2};
std::vector<double> velocity_values_ = {0.01, 0.02};
hardware_interface::StateInterface left_wheel_pos_state_{
left_wheel_names[0], HW_IF_POSITION, &position_values_[0]};
hardware_interface::StateInterface right_wheel_pos_state_{
right_wheel_names[0], HW_IF_POSITION, &position_values_[1]};
hardware_interface::StateInterface left_wheel_vel_state_{
left_wheel_names[0], HW_IF_VELOCITY, &velocity_values_[0]};
hardware_interface::StateInterface right_wheel_vel_state_{
right_wheel_names[0], HW_IF_VELOCITY, &velocity_values_[1]};
hardware_interface::CommandInterface left_wheel_vel_cmd_{
left_wheel_names[0], HW_IF_VELOCITY, &velocity_values_[0]};
hardware_interface::CommandInterface right_wheel_vel_cmd_{
right_wheel_names[0], HW_IF_VELOCITY, &velocity_values_[1]};
rclcpp::Node::SharedPtr pub_node;
rclcpp::Publisher<geometry_msgs::msg::TwistStamped>::SharedPtr velocity_publisher;
};
TEST_F(TestMecanumController, configure_fails_without_parameters)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, configure_fails_with_only_left_or_only_right_side_defined)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(std::vector<std::string>())));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(std::vector<std::string>())));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, configure_fails_with_mismatching_wheel_side_size)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
auto extended_right_wheel_names = right_wheel_names;
extended_right_wheel_names.push_back("extra_wheel");
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(extended_right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, configure_succeeds_when_wheels_are_specified)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
ASSERT_THAT(
controller_->state_interface_configuration().names,
SizeIs(left_wheel_names.size() + right_wheel_names.size()));
ASSERT_THAT(
controller_->command_interface_configuration().names,
SizeIs(left_wheel_names.size() + right_wheel_names.size()));
}
TEST_F(TestMecanumController, activate_fails_without_resources_assigned)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
ASSERT_EQ(controller_->on_activate(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, activate_succeeds_with_pos_resources_assigned)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
// We implicitly test that by default position feedback is required
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
assignResourcesPosFeedback();
ASSERT_EQ(controller_->on_activate(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
}
TEST_F(TestMecanumController, activate_succeeds_with_vel_resources_assigned)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("position_feedback", rclcpp::ParameterValue(false)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
assignResourcesVelFeedback();
ASSERT_EQ(controller_->on_activate(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
}
TEST_F(TestMecanumController, activate_fails_with_wrong_resources_assigned_1)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("position_feedback", rclcpp::ParameterValue(false)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
assignResourcesPosFeedback();
ASSERT_EQ(controller_->on_activate(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, activate_fails_with_wrong_resources_assigned_2)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("position_feedback", rclcpp::ParameterValue(true)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
ASSERT_EQ(controller_->on_configure(rclcpp_lifecycle::State()), CallbackReturn::SUCCESS);
assignResourcesVelFeedback();
ASSERT_EQ(controller_->on_activate(rclcpp_lifecycle::State()), CallbackReturn::ERROR);
}
TEST_F(TestMecanumController, cleanup)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
controller_->get_node()->set_parameter(rclcpp::Parameter("wheel_separation", 0.4));
controller_->get_node()->set_parameter(rclcpp::Parameter("wheel_radius", 0.1));
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(controller_->get_node()->get_node_base_interface());
auto state = controller_->configure();
ASSERT_EQ(State::PRIMARY_STATE_INACTIVE, state.id());
assignResourcesPosFeedback();
state = controller_->activate();
ASSERT_EQ(State::PRIMARY_STATE_ACTIVE, state.id());
waitForSetup();
// send msg
const double linear = 1.0;
const double angular = 1.0;
publish(linear, angular);
controller_->wait_for_twist(executor);
ASSERT_EQ(
controller_->update(rclcpp::Time(0, 0, RCL_ROS_TIME), rclcpp::Duration::from_seconds(0.01)),
controller_interface::return_type::OK);
state = controller_->deactivate();
ASSERT_EQ(State::PRIMARY_STATE_INACTIVE, state.id());
ASSERT_EQ(
controller_->update(rclcpp::Time(0, 0, RCL_ROS_TIME), rclcpp::Duration::from_seconds(0.01)),
controller_interface::return_type::OK);
state = controller_->cleanup();
ASSERT_EQ(State::PRIMARY_STATE_UNCONFIGURED, state.id());
// should be stopped
EXPECT_EQ(0.0, left_wheel_vel_cmd_.get_value());
EXPECT_EQ(0.0, right_wheel_vel_cmd_.get_value());
executor.cancel();
}
TEST_F(TestMecanumController, correct_initialization_using_parameters)
{
const auto ret = controller_->init(controller_name);
ASSERT_EQ(ret, controller_interface::return_type::OK);
controller_->get_node()->set_parameter(
rclcpp::Parameter("left_wheel_names", rclcpp::ParameterValue(left_wheel_names)));
controller_->get_node()->set_parameter(
rclcpp::Parameter("right_wheel_names", rclcpp::ParameterValue(right_wheel_names)));
controller_->get_node()->set_parameter(rclcpp::Parameter("wheel_separation", 0.4));
controller_->get_node()->set_parameter(rclcpp::Parameter("wheel_radius", 1.0));
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(controller_->get_node()->get_node_base_interface());
auto state = controller_->configure();
assignResourcesPosFeedback();
ASSERT_EQ(State::PRIMARY_STATE_INACTIVE, state.id());
EXPECT_EQ(0.01, left_wheel_vel_cmd_.get_value());
EXPECT_EQ(0.02, right_wheel_vel_cmd_.get_value());
state = controller_->activate();
ASSERT_EQ(State::PRIMARY_STATE_ACTIVE, state.id());
// send msg
const double linear = 1.0;
const double angular = 0.0;
publish(linear, angular);
// wait for msg is be published to the system
ASSERT_TRUE(controller_->wait_for_twist(executor));
ASSERT_EQ(
controller_->update(rclcpp::Time(0, 0, RCL_ROS_TIME), rclcpp::Duration::from_seconds(0.01)),
controller_interface::return_type::OK);
EXPECT_EQ(1.0, left_wheel_vel_cmd_.get_value());
EXPECT_EQ(1.0, right_wheel_vel_cmd_.get_value());
// deactivated
// wait so controller process the second point when deactivated
std::this_thread::sleep_for(std::chrono::milliseconds(500));
state = controller_->deactivate();
ASSERT_EQ(state.id(), State::PRIMARY_STATE_INACTIVE);
ASSERT_EQ(
controller_->update(rclcpp::Time(0, 0, RCL_ROS_TIME), rclcpp::Duration::from_seconds(0.01)),
controller_interface::return_type::OK);
EXPECT_EQ(0.0, left_wheel_vel_cmd_.get_value()) << "Wheels are halted on deactivate()";
EXPECT_EQ(0.0, right_wheel_vel_cmd_.get_value()) << "Wheels are halted on deactivate()";
// cleanup
state = controller_->cleanup();
ASSERT_EQ(State::PRIMARY_STATE_UNCONFIGURED, state.id());
EXPECT_EQ(0.0, left_wheel_vel_cmd_.get_value());
EXPECT_EQ(0.0, right_wheel_vel_cmd_.get_value());
state = controller_->configure();
ASSERT_EQ(State::PRIMARY_STATE_INACTIVE, state.id());
executor.cancel();
}
| 16,941 |
C++
| 37.768879 | 97 | 0.717077 |
Coriago/examplo-ros2/src/mecanum_controller/test/test_accumulator.cpp
|
// Copyright 2020 PAL Robotics SL.
//
// 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.
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include <mecanum_controller/rolling_mean_accumulator.hpp>
#include <gmock/gmock.h>
#include <cmath>
#include <memory>
TEST(TestAccumulator, test_accumulator)
{
constexpr double THRESHOLD = 1e-12;
mecanum_controller::RollingMeanAccumulator<double> accum(4);
accum.accumulate(1.);
EXPECT_NEAR(1., accum.getRollingMean(), THRESHOLD);
accum.accumulate(1.);
EXPECT_NEAR(1., accum.getRollingMean(), THRESHOLD);
accum.accumulate(5.);
EXPECT_NEAR(7. / 3., accum.getRollingMean(), THRESHOLD);
accum.accumulate(5.);
EXPECT_NEAR(12. / 4., accum.getRollingMean(), THRESHOLD);
// Start removing old values
accum.accumulate(5.);
EXPECT_NEAR(16. / 4., accum.getRollingMean(), THRESHOLD);
accum.accumulate(5.);
EXPECT_NEAR(20. / 4., accum.getRollingMean(), THRESHOLD);
}
TEST(TestAccumulator, spam_accumulator)
{
constexpr double THRESHOLD = 1e-12;
mecanum_controller::RollingMeanAccumulator<double> accum(10);
for (int i = 0; i < 10000; ++i)
{
accum.accumulate(M_PI);
EXPECT_NEAR(M_PI, accum.getRollingMean(), THRESHOLD);
}
}
| 1,712 |
C++
| 28.033898 | 75 | 0.718458 |
Coriago/examplo-ros2/src/mecanum_controller/test/test_load_mecanum_controller.cpp
|
// Copyright 2020 PAL Robotics SL.
//
// 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.
#include <gmock/gmock.h>
#include <memory>
#include "controller_manager/controller_manager.hpp"
#include "rclcpp/utilities.hpp"
#include "ros2_control_test_assets/descriptions.hpp"
TEST(TestLoadMecanumController, load_controller)
{
rclcpp::init(0, nullptr);
std::shared_ptr<rclcpp::Executor> executor =
std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
controller_manager::ControllerManager cm(
std::make_unique<hardware_interface::ResourceManager>(ros2_control_test_assets::diffbot_urdf),
executor, "test_controller_manager");
ASSERT_NO_THROW(
cm.load_controller("test_mecanum_controller", "mecanum_controller/MecanumController"));
rclcpp::shutdown();
}
| 1,294 |
C++
| 33.078946 | 98 | 0.749614 |
Coriago/examplo-ros2/src/mecanum_controller/test/config/test_mecanum_controller.yaml
|
test_mecanum_controller:
ros__parameters:
left_wheel_names: ["left_wheels"]
right_wheel_names: ["right_wheels"]
write_op_modes: ["motor_controller"]
wheel_separation: 0.40
wheels_per_side: 1 # actually 2, but both are controlled by 1 signal
wheel_radius: 0.02
wheel_separation_multiplier: 1.0
left_wheel_radius_multiplier: 1.0
right_wheel_radius_multiplier: 1.0
odom_frame_id: odom
base_frame_id: base_link
pose_covariance_diagonal: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
twist_covariance_diagonal: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
position_feedback: false
open_loop: true
enable_odom_tf: true
cmd_vel_timeout: 500 # milliseconds
publish_limited_velocity: true
velocity_rolling_window_size: 10
linear.x.has_velocity_limits: false
linear.x.has_acceleration_limits: false
linear.x.has_jerk_limits: false
linear.x.max_velocity: 0.0
linear.x.min_velocity: 0.0
linear.x.max_acceleration: 0.0
linear.x.max_jerk: 0.0
linear.x.min_jerk: 0.0
angular.z.has_velocity_limits: false
angular.z.has_acceleration_limits: false
angular.z.has_jerk_limits: false
angular.z.max_velocity: 0.0
angular.z.min_velocity: 0.0
angular.z.max_acceleration: 0.0
angular.z.min_acceleration: 0.0
angular.z.max_jerk: 0.0
angular.z.min_jerk: 0.0
| 1,356 |
YAML
| 28.499999 | 73 | 0.670354 |
Coriago/examplo-ros2/src/mecanum_controller/src/odometry.cpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Enrique Fernández
*/
#include "mecanum_controller/odometry.hpp"
namespace mecanum_controller
{
Odometry::Odometry(size_t velocity_rolling_window_size)
: timestamp_(0.0),
x_(0.0),
y_(0.0),
heading_(0.0),
linear_(0.0),
angular_(0.0),
wheel_separation_(0.0),
left_wheel_radius_(0.0),
right_wheel_radius_(0.0),
left_wheel_old_pos_(0.0),
right_wheel_old_pos_(0.0),
velocity_rolling_window_size_(velocity_rolling_window_size),
linear_accumulator_(velocity_rolling_window_size),
angular_accumulator_(velocity_rolling_window_size)
{
}
void Odometry::init(const rclcpp::Time & time)
{
// Reset accumulators and timestamp:
resetAccumulators();
timestamp_ = time;
}
bool Odometry::update(double left_pos, double right_pos, const rclcpp::Time & time)
{
// We cannot estimate the speed with very small time intervals:
const double dt = time.seconds() - timestamp_.seconds();
if (dt < 0.0001)
{
return false; // Interval too small to integrate with
}
// Get current wheel joint positions:
const double left_wheel_cur_pos = left_pos * left_wheel_radius_;
const double right_wheel_cur_pos = right_pos * right_wheel_radius_;
// Estimate velocity of wheels using old and current position:
const double left_wheel_est_vel = left_wheel_cur_pos - left_wheel_old_pos_;
const double right_wheel_est_vel = right_wheel_cur_pos - right_wheel_old_pos_;
// Update old position with current:
left_wheel_old_pos_ = left_wheel_cur_pos;
right_wheel_old_pos_ = right_wheel_cur_pos;
updateFromVelocity(left_wheel_est_vel, right_wheel_est_vel, time);
return true;
}
bool Odometry::updateFromVelocity(double left_vel, double right_vel, const rclcpp::Time & time)
{
const double dt = time.seconds() - timestamp_.seconds();
// Compute linear and angular diff:
const double linear = (left_vel + right_vel) * 0.5;
// Now there is a bug about scout angular velocity
const double angular = (right_vel - left_vel) / wheel_separation_;
// Integrate odometry:
integrateExact(linear, angular);
timestamp_ = time;
// Estimate speeds using a rolling mean to filter them out:
linear_accumulator_.accumulate(linear / dt);
angular_accumulator_.accumulate(angular / dt);
linear_ = linear_accumulator_.getRollingMean();
angular_ = angular_accumulator_.getRollingMean();
return true;
}
void Odometry::updateOpenLoop(double linear, double angular, const rclcpp::Time & time)
{
/// Save last linear and angular velocity:
linear_ = linear;
angular_ = angular;
/// Integrate odometry:
const double dt = time.seconds() - timestamp_.seconds();
timestamp_ = time;
integrateExact(linear * dt, angular * dt);
}
void Odometry::resetOdometry()
{
x_ = 0.0;
y_ = 0.0;
heading_ = 0.0;
}
void Odometry::setWheelParams(
double wheel_separation, double left_wheel_radius, double right_wheel_radius)
{
wheel_separation_ = wheel_separation;
left_wheel_radius_ = left_wheel_radius;
right_wheel_radius_ = right_wheel_radius;
}
void Odometry::setVelocityRollingWindowSize(size_t velocity_rolling_window_size)
{
velocity_rolling_window_size_ = velocity_rolling_window_size;
resetAccumulators();
}
void Odometry::integrateRungeKutta2(double linear, double angular)
{
const double direction = heading_ + angular * 0.5;
/// Runge-Kutta 2nd order integration:
x_ += linear * cos(direction);
y_ += linear * sin(direction);
heading_ += angular;
}
void Odometry::integrateExact(double linear, double angular)
{
if (fabs(angular) < 1e-6)
{
integrateRungeKutta2(linear, angular);
}
else
{
/// Exact integration (should solve problems when angular is zero):
const double heading_old = heading_;
const double r = linear / angular;
heading_ += angular;
x_ += r * (sin(heading_) - sin(heading_old));
y_ += -r * (cos(heading_) - cos(heading_old));
}
}
void Odometry::resetAccumulators()
{
linear_accumulator_ = RollingMeanAccumulator(velocity_rolling_window_size_);
angular_accumulator_ = RollingMeanAccumulator(velocity_rolling_window_size_);
}
} // namespace mecanum_controller
| 4,710 |
C++
| 27.379518 | 95 | 0.705945 |
Coriago/examplo-ros2/src/mecanum_controller/src/speed_limiter.cpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Enrique Fernández
*/
#include <algorithm>
#include <stdexcept>
#include "mecanum_controller/speed_limiter.hpp"
#include "rcppmath/clamp.hpp"
namespace mecanum_controller
{
SpeedLimiter::SpeedLimiter(
bool has_velocity_limits, bool has_acceleration_limits, bool has_jerk_limits, double min_velocity,
double max_velocity, double min_acceleration, double max_acceleration, double min_jerk,
double max_jerk)
: has_velocity_limits_(has_velocity_limits),
has_acceleration_limits_(has_acceleration_limits),
has_jerk_limits_(has_jerk_limits),
min_velocity_(min_velocity),
max_velocity_(max_velocity),
min_acceleration_(min_acceleration),
max_acceleration_(max_acceleration),
min_jerk_(min_jerk),
max_jerk_(max_jerk)
{
// Check if limits are valid, max must be specified, min defaults to -max if unspecified
if (has_velocity_limits_)
{
if (std::isnan(max_velocity_))
{
throw std::runtime_error("Cannot apply velocity limits if max_velocity is not specified");
}
if (std::isnan(min_velocity_))
{
min_velocity_ = -max_velocity_;
}
}
if (has_acceleration_limits_)
{
if (std::isnan(max_acceleration_))
{
throw std::runtime_error(
"Cannot apply acceleration limits if max_acceleration is not specified");
}
if (std::isnan(min_acceleration_))
{
min_acceleration_ = -max_acceleration_;
}
}
if (has_jerk_limits_)
{
if (std::isnan(max_jerk_))
{
throw std::runtime_error("Cannot apply jerk limits if max_jerk is not specified");
}
if (std::isnan(min_jerk_))
{
min_jerk_ = -max_jerk_;
}
}
}
double SpeedLimiter::limit(double & v, double v0, double v1, double dt)
{
const double tmp = v;
limit_jerk(v, v0, v1, dt);
limit_acceleration(v, v0, dt);
limit_velocity(v);
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_velocity(double & v)
{
const double tmp = v;
if (has_velocity_limits_)
{
v = rcppmath::clamp(v, min_velocity_, max_velocity_);
}
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_acceleration(double & v, double v0, double dt)
{
const double tmp = v;
if (has_acceleration_limits_)
{
const double dv_min = min_acceleration_ * dt;
const double dv_max = max_acceleration_ * dt;
const double dv = rcppmath::clamp(v - v0, dv_min, dv_max);
v = v0 + dv;
}
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_jerk(double & v, double v0, double v1, double dt)
{
const double tmp = v;
if (has_jerk_limits_)
{
const double dv = v - v0;
const double dv0 = v0 - v1;
const double dt2 = 2. * dt * dt;
const double da_min = min_jerk_ * dt2;
const double da_max = max_jerk_ * dt2;
const double da = rcppmath::clamp(dv - dv0, da_min, da_max);
v = v0 + dv0 + da;
}
return tmp != 0.0 ? v / tmp : 1.0;
}
} // namespace mecanum_controller
| 3,529 |
C++
| 24.035461 | 100 | 0.655143 |
Coriago/examplo-ros2/src/mecanum_controller/src/mecanum_controller.cpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "mecanum_controller/mecanum_controller.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "lifecycle_msgs/msg/state.hpp"
#include "rclcpp/logging.hpp"
namespace
{
constexpr auto DEFAULT_COMMAND_TOPIC = "~/cmd_vel";
constexpr auto DEFAULT_COMMAND_UNSTAMPED_TOPIC = "~/cmd_vel_unstamped";
constexpr auto DEFAULT_COMMAND_OUT_TOPIC = "~/cmd_vel_out";
} // namespace
namespace mecanum_controller
{
using namespace std::chrono_literals;
using controller_interface::interface_configuration_type;
using controller_interface::InterfaceConfiguration;
using hardware_interface::HW_IF_POSITION;
using hardware_interface::HW_IF_VELOCITY;
using lifecycle_msgs::msg::State;
Wheel::Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity,
std::string name) : velocity_(velocity), name(std::move(name)) {}
void Wheel::set_velocity(double velocity)
{
velocity_.get().set_value(velocity);
}
MecanumController::MecanumController() : controller_interface::ControllerInterface() {}
CallbackReturn MecanumController::on_init()
{
try
{
// with the lifecycle node being initialized, we can declare parameters
auto_declare<std::string>("front_left_joint", front_left_joint_name_);
auto_declare<std::string>("front_right_joint", front_right_joint_name_);
auto_declare<std::string>("rear_left_joint", rear_left_joint_name_);
auto_declare<std::string>("rear_right_joint", rear_right_joint_name_);
auto_declare<double>("chassis_center_to_axle", wheel_params_.x_offset);
auto_declare<double>("axle_center_to_wheel", wheel_params_.y_offset);
auto_declare<double>("wheel_radius", wheel_params_.radius);
auto_declare<double>("cmd_vel_timeout", cmd_vel_timeout_.count() / 1000.0);
auto_declare<bool>("use_stamped_vel", use_stamped_vel_);
}
catch (const std::exception & e)
{
fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what());
return CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
InterfaceConfiguration MecanumController::command_interface_configuration() const
{
std::vector<std::string> conf_names;
conf_names.push_back(front_left_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(front_right_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_left_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_right_joint_name_ + "/" + HW_IF_VELOCITY);
return {interface_configuration_type::INDIVIDUAL, conf_names};
}
InterfaceConfiguration MecanumController::state_interface_configuration() const
{
return {interface_configuration_type::NONE};
}
controller_interface::return_type MecanumController::update(
const rclcpp::Time & time, const rclcpp::Duration & /*period*/)
{
auto logger = node_->get_logger();
if (get_state().id() == State::PRIMARY_STATE_INACTIVE)
{
if (!is_halted)
{
halt();
is_halted = true;
}
return controller_interface::return_type::OK;
}
const auto current_time = time;
std::shared_ptr<Twist> last_command_msg;
received_velocity_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(logger, "Velocity message received was a nullptr.");
return controller_interface::return_type::ERROR;
}
const auto age_of_last_command = current_time - last_command_msg->header.stamp;
// Brake if cmd_vel has timeout, override the stored command
if (age_of_last_command > cmd_vel_timeout_)
{
last_command_msg->twist.linear.x = 0.0;
last_command_msg->twist.angular.z = 0.0;
}
Twist command = *last_command_msg;
double & linear_x_cmd = command.twist.linear.x;
double & linear_y_cmd = command.twist.linear.y;
double & angular_cmd = command.twist.angular.z;
double x_offset = wheel_params_.x_offset;
double y_offset = wheel_params_.y_offset;
double radius = wheel_params_.radius;
// Compute Wheel Velocities
const double front_left_offset = (-1 * x_offset + -1 * y_offset);
const double front_right_offset = (x_offset + y_offset);
const double rear_left_offset = (-1 * x_offset + -1 * y_offset);
const double rear_right_offset = (x_offset + y_offset);
const double front_left_velocity = (front_left_offset * angular_cmd + linear_x_cmd - linear_y_cmd) / radius;
const double front_right_velocity = (front_right_offset * angular_cmd + linear_x_cmd + linear_y_cmd) / radius;
const double rear_left_velocity = (rear_left_offset * angular_cmd + linear_x_cmd + linear_y_cmd) / radius;
const double rear_right_velocity = (rear_right_offset * angular_cmd + linear_x_cmd - linear_y_cmd) / radius;
// Set Wheel Velocities
front_left_handle_->set_velocity(front_left_velocity);
front_right_handle_->set_velocity(front_right_velocity);
rear_left_handle_->set_velocity(rear_left_velocity);
rear_right_handle_->set_velocity(rear_right_velocity);
// Time update
const auto update_dt = current_time - previous_update_timestamp_;
previous_update_timestamp_ = current_time;
return controller_interface::return_type::OK;
}
CallbackReturn MecanumController::on_configure(const rclcpp_lifecycle::State &)
{
auto logger = node_->get_logger();
// Get Parameters
front_left_joint_name_ = node_->get_parameter("front_left_joint").as_string();
front_right_joint_name_ = node_->get_parameter("front_right_joint").as_string();
rear_left_joint_name_ = node_->get_parameter("rear_left_joint").as_string();
rear_right_joint_name_ = node_->get_parameter("rear_right_joint").as_string();
if (front_left_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_left_joint_name is not set");
return CallbackReturn::ERROR;
}
if (front_right_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_right_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_left_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_left_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_right_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_right_joint_name is not set");
return CallbackReturn::ERROR;
}
wheel_params_.x_offset = node_->get_parameter("chassis_center_to_axle").as_double();
wheel_params_.y_offset = node_->get_parameter("axle_center_to_wheel").as_double();
wheel_params_.radius = node_->get_parameter("wheel_radius").as_double();
cmd_vel_timeout_ = std::chrono::milliseconds{
static_cast<int>(node_->get_parameter("cmd_vel_timeout").as_double() * 1000.0)};
use_stamped_vel_ = node_->get_parameter("use_stamped_vel").as_bool();
// Run reset to make sure everything is initialized correctly
if (!reset())
{
return CallbackReturn::ERROR;
}
const Twist empty_twist;
received_velocity_msg_ptr_.set(std::make_shared<Twist>(empty_twist));
// initialize command subscriber
if (use_stamped_vel_)
{
velocity_command_subscriber_ = node_->create_subscription<Twist>(
DEFAULT_COMMAND_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<Twist> msg) -> void {
if (!subscriber_is_active_)
{
RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
if ((msg->header.stamp.sec == 0) && (msg->header.stamp.nanosec == 0))
{
RCLCPP_WARN_ONCE(
node_->get_logger(),
"Received TwistStamped with zero timestamp, setting it to current "
"time, this message will only be shown once");
msg->header.stamp = node_->get_clock()->now();
}
received_velocity_msg_ptr_.set(std::move(msg));
});
}
else
{
velocity_command_unstamped_subscriber_ = node_->create_subscription<geometry_msgs::msg::Twist>(
DEFAULT_COMMAND_UNSTAMPED_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<geometry_msgs::msg::Twist> msg) -> void {
if (!subscriber_is_active_)
{
RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
// Write fake header in the stored stamped command
std::shared_ptr<Twist> twist_stamped;
received_velocity_msg_ptr_.get(twist_stamped);
twist_stamped->twist = *msg;
twist_stamped->header.stamp = node_->get_clock()->now();
});
}
previous_update_timestamp_ = node_->get_clock()->now();
return CallbackReturn::SUCCESS;
}
CallbackReturn MecanumController::on_activate(const rclcpp_lifecycle::State &)
{
front_left_handle_ = get_wheel(front_left_joint_name_);
front_right_handle_ = get_wheel(front_right_joint_name_);
rear_left_handle_ = get_wheel(rear_left_joint_name_);
rear_right_handle_ = get_wheel(rear_right_joint_name_);
if (!front_left_handle_ || !front_right_handle_ || !rear_left_handle_ || !rear_right_handle_)
{
return CallbackReturn::ERROR;
}
is_halted = false;
subscriber_is_active_ = true;
RCLCPP_DEBUG(node_->get_logger(), "Subscriber and publisher are now active.");
return CallbackReturn::SUCCESS;
}
CallbackReturn MecanumController::on_deactivate(const rclcpp_lifecycle::State &)
{
subscriber_is_active_ = false;
return CallbackReturn::SUCCESS;
}
CallbackReturn MecanumController::on_cleanup(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return CallbackReturn::ERROR;
}
received_velocity_msg_ptr_.set(std::make_shared<Twist>());
return CallbackReturn::SUCCESS;
}
CallbackReturn MecanumController::on_error(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
bool MecanumController::reset()
{
subscriber_is_active_ = false;
velocity_command_subscriber_.reset();
velocity_command_unstamped_subscriber_.reset();
received_velocity_msg_ptr_.set(nullptr);
is_halted = false;
return true;
}
CallbackReturn MecanumController::on_shutdown(const rclcpp_lifecycle::State &)
{
return CallbackReturn::SUCCESS;
}
void MecanumController::halt()
{
front_left_handle_->set_velocity(0.0);
front_right_handle_->set_velocity(0.0);
rear_left_handle_->set_velocity(0.0);
rear_right_handle_->set_velocity(0.0);
auto logger = node_->get_logger();
RCLCPP_WARN(logger, "-----HALT CALLED : STOPPING ALL MOTORS-----");
}
std::shared_ptr<Wheel> MecanumController::get_wheel( const std::string & wheel_name )
{
auto logger = node_->get_logger();
if (wheel_name.empty())
{
RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified.");
return nullptr;
}
// Get Command Handle for joint
const auto command_handle = std::find_if(
command_interfaces_.begin(), command_interfaces_.end(),
[&wheel_name](const auto & interface) {
return interface.get_name() == wheel_name &&
interface.get_interface_name() == HW_IF_VELOCITY;
});
if (command_handle == command_interfaces_.end())
{
RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", wheel_name.c_str());
return nullptr;
}
return std::make_shared<Wheel>(std::ref(*command_handle), wheel_name);
}
} // namespace mecanum_controller
#include "class_loader/register_macro.hpp"
CLASS_LOADER_REGISTER_CLASS(
mecanum_controller::MecanumController, controller_interface::ControllerInterface)
| 12,060 |
C++
| 32.974648 | 112 | 0.689884 |
Coriago/examplo-ros2/src/mecanum_controller/doc/userdoc.rst
|
.. _diff_drive_controller_userdoc:
diff_drive_controller
=====================
Controller for mobile robots with differential drive.
Input for control are robot body velocity commands which are translated to wheel commands for the differential drive base.
Odometry is computed from hardware feedback and published.
Velocity commands
-----------------
The controller works with a velocity twist from which it extracts the x component of the linear velocity and the z component of the angular velocity. Velocities on other components are ignored.
Hardware interface type
-----------------------
The controller works with wheel joints through a velocity interface.
Other features
--------------
Realtime-safe implementation.
Odometry publishing
Task-space velocity, acceleration and jerk limits
Automatic stop after command time-out
| 854 |
reStructuredText
| 30.666666 | 193 | 0.737705 |
Coriago/examplo-ros2/src/mecanum_controller/include/mecanum_controller/odometry.hpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Luca Marchionni
* Author: Bence Magyar
* Author: Enrique Fernández
* Author: Paul Mathieu
*/
#ifndef MECANUM_CONTROLLER__ODOMETRY_HPP_
#define MECANUM_CONTROLLER__ODOMETRY_HPP_
#include <cmath>
#include "mecanum_controller/rolling_mean_accumulator.hpp"
#include "rclcpp/time.hpp"
namespace mecanum_controller
{
class Odometry
{
public:
explicit Odometry(size_t velocity_rolling_window_size = 10);
void init(const rclcpp::Time & time);
bool update(double left_pos, double right_pos, const rclcpp::Time & time);
bool updateFromVelocity(double left_vel, double right_vel, const rclcpp::Time & time);
void updateOpenLoop(double linear, double angular, const rclcpp::Time & time);
void resetOdometry();
double getX() const { return x_; }
double getY() const { return y_; }
double getHeading() const { return heading_; }
double getLinear() const { return linear_; }
double getAngular() const { return angular_; }
void setWheelParams(double wheel_separation, double left_wheel_radius, double right_wheel_radius);
void setVelocityRollingWindowSize(size_t velocity_rolling_window_size);
private:
using RollingMeanAccumulator = mecanum_controller::RollingMeanAccumulator<double>;
void integrateRungeKutta2(double linear, double angular);
void integrateExact(double linear, double angular);
void resetAccumulators();
// Current timestamp:
rclcpp::Time timestamp_;
// Current pose:
double x_; // [m]
double y_; // [m]
double heading_; // [rad]
// Current velocity:
double linear_; // [m/s]
double angular_; // [rad/s]
// Wheel kinematic parameters [m]:
double wheel_separation_;
double left_wheel_radius_;
double right_wheel_radius_;
// Previous wheel position/state [rad]:
double left_wheel_old_pos_;
double right_wheel_old_pos_;
// Rolling mean accumulators for the linear and angular velocities:
size_t velocity_rolling_window_size_;
RollingMeanAccumulator linear_accumulator_;
RollingMeanAccumulator angular_accumulator_;
};
} // namespace mecanum_controller
#endif // MECANUM_CONTROLLER__ODOMETRY_HPP_
| 2,725 |
C++
| 29.629213 | 100 | 0.725872 |
Coriago/examplo-ros2/src/mecanum_controller/include/mecanum_controller/visibility_control.h
|
// 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.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef MECANUM_CONTROLLER__VISIBILITY_CONTROL_H_
#define MECANUM_CONTROLLER__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define MECANUM_CONTROLLER_EXPORT __attribute__((dllexport))
#define MECANUM_CONTROLLER_IMPORT __attribute__((dllimport))
#else
#define MECANUM_CONTROLLER_EXPORT __declspec(dllexport)
#define MECANUM_CONTROLLER_IMPORT __declspec(dllimport)
#endif
#ifdef MECANUM_CONTROLLER_BUILDING_DLL
#define MECANUM_CONTROLLER_PUBLIC MECANUM_CONTROLLER_EXPORT
#else
#define MECANUM_CONTROLLER_PUBLIC MECANUM_CONTROLLER_IMPORT
#endif
#define MECANUM_CONTROLLER_PUBLIC_TYPE MECANUM_CONTROLLER_PUBLIC
#define MECANUM_CONTROLLER_LOCAL
#else
#define MECANUM_CONTROLLER_EXPORT __attribute__((visibility("default")))
#define MECANUM_CONTROLLER_IMPORT
#if __GNUC__ >= 4
#define MECANUM_CONTROLLER_PUBLIC __attribute__((visibility("default")))
#define MECANUM_CONTROLLER_LOCAL __attribute__((visibility("hidden")))
#else
#define MECANUM_CONTROLLER_PUBLIC
#define MECANUM_CONTROLLER_LOCAL
#endif
#define MECANUM_CONTROLLER_PUBLIC_TYPE
#endif
#endif // MECANUM_CONTROLLER__VISIBILITY_CONTROL_H_
| 2,251 |
C
| 38.508771 | 79 | 0.76988 |
Coriago/examplo-ros2/src/mecanum_controller/include/mecanum_controller/rolling_mean_accumulator.hpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Víctor López
*/
#ifndef MECANUM_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
#define MECANUM_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
#include <cassert>
#include <cstdio>
#include <vector>
namespace mecanum_controller
{
/**
* \brief Simplification of boost::accumulators::accumulator_set<double,
* bacc::stats<bacc::tag::rolling_mean>> to avoid dragging boost dependencies
*
* Computes the mean of the last accumulated elements
*/
template <typename T>
class RollingMeanAccumulator
{
public:
explicit RollingMeanAccumulator(size_t rolling_window_size)
: buffer_(rolling_window_size, 0.0), next_insert_(0), sum_(0.0), buffer_filled_(false)
{
}
void accumulate(T val)
{
sum_ -= buffer_[next_insert_];
sum_ += val;
buffer_[next_insert_] = val;
next_insert_++;
buffer_filled_ |= next_insert_ >= buffer_.size();
next_insert_ = next_insert_ % buffer_.size();
}
T getRollingMean() const
{
size_t valid_data_count = buffer_filled_ * buffer_.size() + !buffer_filled_ * next_insert_;
assert(valid_data_count > 0);
return sum_ / valid_data_count;
}
private:
std::vector<T> buffer_;
size_t next_insert_;
T sum_;
bool buffer_filled_;
};
} // namespace mecanum_controller
#endif // MECANUM_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
| 1,904 |
C++
| 27.014705 | 95 | 0.700105 |
Coriago/examplo-ros2/src/mecanum_controller/include/mecanum_controller/speed_limiter.hpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Enrique Fernández
*/
#ifndef MECANUM_CONTROLLER__SPEED_LIMITER_HPP_
#define MECANUM_CONTROLLER__SPEED_LIMITER_HPP_
#include <cmath>
namespace mecanum_controller
{
class SpeedLimiter
{
public:
/**
* \brief Constructor
* \param [in] has_velocity_limits if true, applies velocity limits
* \param [in] has_acceleration_limits if true, applies acceleration limits
* \param [in] has_jerk_limits if true, applies jerk limits
* \param [in] min_velocity Minimum velocity [m/s], usually <= 0
* \param [in] max_velocity Maximum velocity [m/s], usually >= 0
* \param [in] min_acceleration Minimum acceleration [m/s^2], usually <= 0
* \param [in] max_acceleration Maximum acceleration [m/s^2], usually >= 0
* \param [in] min_jerk Minimum jerk [m/s^3], usually <= 0
* \param [in] max_jerk Maximum jerk [m/s^3], usually >= 0
*/
SpeedLimiter(
bool has_velocity_limits = false, bool has_acceleration_limits = false,
bool has_jerk_limits = false, double min_velocity = NAN, double max_velocity = NAN,
double min_acceleration = NAN, double max_acceleration = NAN, double min_jerk = NAN,
double max_jerk = NAN);
/**
* \brief Limit the velocity and acceleration
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity to v [m/s]
* \param [in] v1 Previous velocity to v0 [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
*/
double limit(double & v, double v0, double v1, double dt);
/**
* \brief Limit the velocity
* \param [in, out] v Velocity [m/s]
* \return Limiting factor (1.0 if none)
*/
double limit_velocity(double & v);
/**
* \brief Limit the acceleration
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
*/
double limit_acceleration(double & v, double v0, double dt);
/**
* \brief Limit the jerk
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity to v [m/s]
* \param [in] v1 Previous velocity to v0 [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
* \see http://en.wikipedia.org/wiki/Jerk_%28physics%29#Motion_control
*/
double limit_jerk(double & v, double v0, double v1, double dt);
private:
// Enable/Disable velocity/acceleration/jerk limits:
bool has_velocity_limits_;
bool has_acceleration_limits_;
bool has_jerk_limits_;
// Velocity limits:
double min_velocity_;
double max_velocity_;
// Acceleration limits:
double min_acceleration_;
double max_acceleration_;
// Jerk limits:
double min_jerk_;
double max_jerk_;
};
} // namespace mecanum_controller
#endif // MECANUM_CONTROLLER__SPEED_LIMITER_HPP_
| 3,435 |
C++
| 31.415094 | 88 | 0.661718 |
Coriago/examplo-ros2/src/mecanum_controller/include/mecanum_controller/mecanum_controller.hpp
|
// Copyright 2020 PAL Robotics S.L.
//
// 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.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#ifndef MECANUM_CONTROLLER__MECANUM_CONTROLLER_HPP_
#define MECANUM_CONTROLLER__MECANUM_CONTROLLER_HPP_
#include <chrono>
#include <cmath>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "controller_interface/controller_interface.hpp"
#include "mecanum_controller/visibility_control.h"
#include "geometry_msgs/msg/twist.hpp"
#include "geometry_msgs/msg/twist_stamped.hpp"
#include "hardware_interface/handle.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include <hardware_interface/loaned_command_interface.hpp>
namespace mecanum_controller
{
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
class Wheel {
public:
Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name);
void set_velocity(double velocity);
private:
std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity_;
std::string name;
};
class MecanumController : public controller_interface::ControllerInterface
{
using Twist = geometry_msgs::msg::TwistStamped;
public:
MECANUM_CONTROLLER_PUBLIC
MecanumController();
MECANUM_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration command_interface_configuration() const override;
MECANUM_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration state_interface_configuration() const override;
MECANUM_CONTROLLER_PUBLIC
controller_interface::return_type update(
const rclcpp::Time & time, const rclcpp::Duration & period) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_init() override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_configure(const rclcpp_lifecycle::State & previous_state) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_cleanup(const rclcpp_lifecycle::State & previous_state) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_error(const rclcpp_lifecycle::State & previous_state) override;
MECANUM_CONTROLLER_PUBLIC
CallbackReturn on_shutdown(const rclcpp_lifecycle::State & previous_state) override;
protected:
std::shared_ptr<Wheel> get_wheel(const std::string & wheel_name);
std::shared_ptr<Wheel> front_left_handle_;
std::shared_ptr<Wheel> front_right_handle_;
std::shared_ptr<Wheel> rear_left_handle_;
std::shared_ptr<Wheel> rear_right_handle_;
std::string front_left_joint_name_;
std::string front_right_joint_name_;
std::string rear_left_joint_name_;
std::string rear_right_joint_name_;
struct WheelParams
{
double x_offset = 0.0; // Chassis Center to Axle Center
double y_offset = 0.0; // Axle Center to Wheel Center
double radius = 0.0; // Assumed to be the same for all wheels
} wheel_params_;
// Timeout to consider cmd_vel commands old
std::chrono::milliseconds cmd_vel_timeout_{500};
rclcpp::Time previous_update_timestamp_{0};
// Topic Subscription
bool subscriber_is_active_ = false;
rclcpp::Subscription<Twist>::SharedPtr velocity_command_subscriber_ = nullptr;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr
velocity_command_unstamped_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<Twist>> received_velocity_msg_ptr_{nullptr};
bool is_halted = false;
bool use_stamped_vel_ = true;
bool reset();
void halt();
};
} // namespace mecanum_controller
#endif // MECANUM_CONTROLLER__MECANUM_CONTROLLER_HPP_
| 4,454 |
C++
| 32.49624 | 105 | 0.759542 |
Coriago/examplo-ros2/src/robot_hardware/robot_hardware.xml
|
<library path="robot_hardware">
<class name="robot_hardware/IsaacDriveHardware"
type="robot_hardware::IsaacDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface to talk with Isaac Sim robot drive train.
</description>
</class>
</library>
| 339 |
XML
| 36.777774 | 83 | 0.713864 |
Coriago/examplo-ros2/src/robot_hardware/src/isaac_drive.cpp
|
// Copyright 2021 ros2_control Development Team
//
// 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.
#include "robot_hardware/isaac_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
using std::placeholders::_1;
namespace robot_hardware
{
CallbackReturn IsaacDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
// rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;
// custom_qos_profile.depth = 7;
node_ = rclcpp::Node::make_shared("isaac_hardware_interface");
// PUBLISHER SETUP
isaac_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>("isaac_joint_commands", rclcpp::SystemDefaultsQoS());
realtime_isaac_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
isaac_publisher_);
// SUBSCRIBER SETUP
const sensor_msgs::msg::JointState empty_joint_state;
received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state));
isaac_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>("isaac_joint_states", rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void
{
if (!subscriber_is_active_) {
RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive");
return;
}
received_joint_msg_ptr_.set(std::move(msg));
});
// INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != CallbackReturn::SUCCESS)
{
return CallbackReturn::ERROR;
}
// hw_start_sec_ = stod(info_.hardware_parameters["example_param_hw_start_duration_sec"]);
// hw_stop_sec_ = stod(info_.hardware_parameters["example_param_hw_stop_duration_sec"]);
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_commands_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return CallbackReturn::ERROR;
}
}
return CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> IsaacDriveHardware::export_state_interfaces()
{
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> IsaacDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
command_interfaces.emplace_back(hardware_interface::CommandInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_commands_[i]));
}
return command_interfaces;
}
CallbackReturn IsaacDriveHardware::on_activate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Activating ...please wait...");
// set some default values
for (auto i = 0u; i < hw_positions_.size(); i++)
{
if (std::isnan(hw_positions_[i]))
{
hw_positions_[i] = 0;
hw_velocities_[i] = 0;
hw_commands_[i] = 0;
}
joint_names_map_[joint_names_[i]] = i + 1; // ADD 1 to differentiate null key
}
subscriber_is_active_ = true;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully activated!");
return CallbackReturn::SUCCESS;
}
CallbackReturn IsaacDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Deactivating ...please wait...");
subscriber_is_active_ = false;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully deactivated!");
return CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
hardware_interface::return_type IsaacDriveHardware::read()
{
rclcpp::spin_some(node_);
std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg;
received_joint_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "Velocity message received was a nullptr.");
return hardware_interface::return_type::ERROR;
}
auto names = last_command_msg->name;
auto positions = last_command_msg->position;
auto velocities = last_command_msg->velocity;
for (auto i = 0u; i < names.size(); i++) {
uint p = joint_names_map_[names[i]];
if (p > 0) {
hw_positions_[p - 1] = positions[i];
hw_velocities_[p - 1] = velocities[i];
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type robot_hardware::IsaacDriveHardware::write()
{
// RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Velocity: %f", hw_commands_[0]);
if (realtime_isaac_publisher_->trylock()) {
auto & realtime_isaac_command = realtime_isaac_publisher_->msg_;
realtime_isaac_command.header.stamp = node_->get_clock()->now();
realtime_isaac_command.name = joint_names_;
realtime_isaac_command.velocity = hw_commands_;
realtime_isaac_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
return hardware_interface::return_type::OK;
}
} // namespace robot_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
robot_hardware::IsaacDriveHardware, hardware_interface::SystemInterface)
| 8,210 |
C++
| 32.514286 | 129 | 0.684166 |
Coriago/examplo-ros2/src/robot_hardware/include/robot_hardware/visibility_control.h
|
// 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.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef ROBOT_HARDWARE__VISIBILITY_CONTROL_H_
#define ROBOT_HARDWARE__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define ROBOT_HARDWARE_EXPORT __attribute__((dllexport))
#define ROBOT_HARDWARE_IMPORT __attribute__((dllimport))
#else
#define ROBOT_HARDWARE_EXPORT __declspec(dllexport)
#define ROBOT_HARDWARE_IMPORT __declspec(dllimport)
#endif
#ifdef ROBOT_HARDWARE_BUILDING_DLL
#define ROBOT_HARDWARE_PUBLIC ROBOT_HARDWARE_EXPORT
#else
#define ROBOT_HARDWARE_PUBLIC ROBOT_HARDWARE_IMPORT
#endif
#define ROBOT_HARDWARE_PUBLIC_TYPE ROBOT_HARDWARE_PUBLIC
#define ROBOT_HARDWARE_LOCAL
#else
#define ROBOT_HARDWARE_EXPORT __attribute__((visibility("default")))
#define ROBOT_HARDWARE_IMPORT
#if __GNUC__ >= 4
#define ROBOT_HARDWARE_PUBLIC __attribute__((visibility("default")))
#define ROBOT_HARDWARE_LOCAL __attribute__((visibility("hidden")))
#else
#define ROBOT_HARDWARE_PUBLIC
#define ROBOT_HARDWARE_LOCAL
#endif
#define ROBOT_HARDWARE_PUBLIC_TYPE
#endif
#endif // ROBOT_HARDWARE__VISIBILITY_CONTROL_H_
| 2,162 |
C
| 37.624999 | 79 | 0.76087 |
Coriago/examplo-ros2/src/robot_hardware/include/robot_hardware/isaac_drive.hpp
|
// Copyright 2021 ros2_control Development Team
//
// 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.
#ifndef ROBOT_HARDWARE__ISAAC_DRIVE_HPP_
#define ROBOT_HARDWARE__ISAAC_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "robot_hardware/visibility_control.h"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
namespace robot_hardware
{
class IsaacDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(IsaacDriveHardware)
ROBOT_HARDWARE_PUBLIC
CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
ROBOT_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
ROBOT_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
ROBOT_HARDWARE_PUBLIC
CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
ROBOT_HARDWARE_PUBLIC
CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
ROBOT_HARDWARE_PUBLIC
hardware_interface::return_type read() override;
ROBOT_HARDWARE_PUBLIC
hardware_interface::return_type write() override;
private:
// Parameters for the DiffBot simulation
double hw_start_sec_;
double hw_stop_sec_;
// Store the command for the simulated robot
std::vector<double> hw_commands_;
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
std::vector<std::string> joint_names_;
std::map<std::string, uint> joint_names_map_;
// Pub Sub to isaac
rclcpp::Node::SharedPtr node_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> isaac_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_isaac_publisher_ = nullptr;
bool subscriber_is_active_ = false;
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr isaac_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr};
};
} // namespace robot_hardware
#endif // ROBOT_HARDWARE__DIFFBOT_SYSTEM_HPP_
| 3,284 |
C++
| 34.32258 | 110 | 0.766748 |
Coriago/examplo-ros2/src/robot_description/launch/rviz.launch.py
|
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from launch.actions import DeclareLaunchArgument, ExecuteProcess
from launch_ros.actions import Node
import xacro
def generate_launch_description():
# Check if we're told to use sim time
use_sim_time = LaunchConfiguration('use_sim_time')
# Process the URDF file
pkg_path = os.path.join(get_package_share_directory('robot_description'))
xacro_file = os.path.join(pkg_path,'urdf', 'robots','examplo.urdf.xacro')
robot_description_config = xacro.process_file(xacro_file)
print(robot_description_config.toxml())
# Create a robot_state_publisher node
params = {'robot_description': robot_description_config.toxml(), 'use_sim_time': use_sim_time}
node_robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
output='screen',
parameters=[params]
)
# Start Rviz2 with basic view
rviz2_config_path = os.path.join(get_package_share_directory('robot_description'), 'config/isaac.rviz')
run_rviz2 = ExecuteProcess(
cmd=['rviz2', '-d', rviz2_config_path],
output='screen'
)
# Launch!
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='true',
description='Use sim time if true'),
node_robot_state_publisher,
run_rviz2
])
| 1,543 |
Python
| 29.879999 | 107 | 0.680493 |
Coriago/examplo-ros2/src/robot_description/launch/rviz_gui.launch.py
|
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from launch.actions import DeclareLaunchArgument, ExecuteProcess
from launch_ros.actions import Node
import xacro
def generate_launch_description():
# Check if we're told to use sim time
use_sim_time = LaunchConfiguration('use_sim_time')
# Process the URDF file
pkg_path = os.path.join(get_package_share_directory('robot_description'))
xacro_file = os.path.join(pkg_path,'urdf', 'robots','examplo.urdf.xacro')
robot_description_config = xacro.process_file(xacro_file)
print(robot_description_config.toxml())
# Create a robot_state_publisher node
params = {'robot_description': robot_description_config.toxml(), 'use_sim_time': use_sim_time}
node_robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
output='screen',
parameters=[params]
)
# Create the publiser gui
joint_state_publisher_gui = Node(
package='joint_state_publisher_gui',
executable='joint_state_publisher_gui',
output='screen'
)
# Start Rviz2 with basic view
rviz2_config_path = os.path.join(get_package_share_directory('robot_description'), 'config/view.rviz')
run_rviz2 = ExecuteProcess(
cmd=['rviz2', '-d', rviz2_config_path],
output='screen'
)
# Launch!
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
node_robot_state_publisher,
joint_state_publisher_gui,
run_rviz2
])
| 1,771 |
Python
| 29.033898 | 106 | 0.672501 |
Coriago/examplo-ros2/src/robot_description/launch/joy.launch.py
|
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
def generate_launch_description():
# Joystick Teleop
joy = Node(
package='joy',
executable='joy_node',
name='joy_node',
parameters=[{
'dev': '/dev/input/js0',
'deadzone': 0.3,
'autorepeat_rate': 20.0,
}])
config_filepath = os.path.join(get_package_share_directory('teleop_twist_joy'), 'config/xbox.config.yaml')
teleop = Node(
package='teleop_twist_joy',
executable='teleop_node',
name='teleop_twist_joy_node',
parameters=[config_filepath],
)
# Launch!
return LaunchDescription([
joy,
teleop
])
| 1,068 |
Python
| 26.410256 | 110 | 0.632959 |
Coriago/examplo-ros2/src/robot_description/launch/isaac.launch.py
|
import os
from ament_index_python.packages import get_package_prefix, get_package_share_directory
from launch import LaunchDescription
from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
import xacro
def generate_launch_description():
# Get Local Files
pkg_path = os.path.join(get_package_share_directory('robot_description'))
xacro_file = os.path.join(pkg_path, 'urdf', 'robots','examplo.urdf.xacro')
controllers_file = os.path.join(pkg_path, 'config', 'controllers.yaml')
joystick_file = os.path.join(pkg_path, 'config', 'xbox-holonomic.config.yaml')
rviz_file = os.path.join(pkg_path, 'config', 'isaac.rviz')
robot_description_config = xacro.process_file(xacro_file)
robot_description_xml = robot_description_config.toxml()
source_code_path = os.path.abspath(os.path.join(pkg_path, "../../../../src/robot_description"))
urdf_save_path = os.path.join(source_code_path, "examplo.urdf")
with open(urdf_save_path, 'w') as f:
f.write(robot_description_xml)
# Create a robot_state_publisher node
description_params = {'robot_description': robot_description_xml, 'use_sim_time': True }
node_robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
output='screen',
parameters=[description_params]
)
# Starts ROS2 Control
control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[{'robot_description': robot_description_xml, 'use_sim_time': True }, controllers_file],
output="screen",
)
# Starts ROS2 Control Joint State Broadcaster
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=["joint_state_broadcaster", "--controller-manager", "/controller_manager"],
)
# Starts ROS2 Control Mecanum Drive Controller
mecanum_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=["mecanum_controller", "-c", "/controller_manager"],
)
mecanum_drive_controller_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[mecanum_drive_controller_spawner],
)
)
# Start Rviz2 with basic view
run_rviz2_node = Node(
package='rviz2',
executable='rviz2',
parameters=[{ 'use_sim_time': True }],
name='isaac_rviz2',
output='screen',
arguments=[["-d"], [rviz_file]],
)
# run_rviz2 = ExecuteProcess(
# cmd=['rviz2', '-d', rviz_file],
# output='screen'
# )
rviz2_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[run_rviz2_node],
)
)
# Start Joystick Node
joy = Node(
package='joy',
executable='joy_node',
name='joy_node',
parameters=[{
'dev': '/dev/input/js0',
'deadzone': 0.3,
'autorepeat_rate': 20.0,
}])
# Start Teleop Node to translate joystick commands to robot commands
joy_teleop = Node(
package='teleop_twist_joy',
executable='teleop_node',
name='teleop_twist_joy_node',
parameters=[joystick_file],
remappings={('/cmd_vel', '/mecanum_controller/cmd_vel_unstamped')}
)
# Launch!
return LaunchDescription([
control_node,
node_robot_state_publisher,
joint_state_broadcaster_spawner,
mecanum_drive_controller_delay,
rviz2_delay,
joy,
joy_teleop
])
| 3,985 |
Python
| 31.672131 | 107 | 0.63187 |
Coriago/examplo-ros2/src/robot_description/config/controllers.yaml
|
controller_manager:
ros__parameters:
update_rate: 10 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
mecanum_controller:
type: mecanum_controller/MecanumController
joint_state_broadcaster:
ros__parameters:
extra_joints: [
"rear_right_roller_0_joint",
"rear_right_roller_1_joint",
"rear_right_roller_2_joint",
"rear_right_roller_3_joint",
"rear_right_roller_4_joint",
"rear_right_roller_5_joint",
"rear_right_roller_6_joint",
"rear_right_roller_7_joint",
"rear_right_roller_8_joint",
"rear_left_roller_0_joint",
"rear_left_roller_1_joint",
"rear_left_roller_2_joint",
"rear_left_roller_3_joint",
"rear_left_roller_4_joint",
"rear_left_roller_5_joint",
"rear_left_roller_6_joint",
"rear_left_roller_7_joint",
"rear_left_roller_8_joint",
"front_left_roller_0_joint",
"front_left_roller_1_joint",
"front_left_roller_2_joint",
"front_left_roller_3_joint",
"front_left_roller_4_joint",
"front_left_roller_5_joint",
"front_left_roller_6_joint",
"front_left_roller_7_joint",
"front_left_roller_8_joint",
"front_right_roller_0_joint",
"front_right_roller_1_joint",
"front_right_roller_2_joint",
"front_right_roller_3_joint",
"front_right_roller_4_joint",
"front_right_roller_5_joint",
"front_right_roller_6_joint",
"front_right_roller_7_joint",
"front_right_roller_8_joint"]
mecanum_controller:
ros__parameters:
front_left_joint: "front_left_mecanum_joint"
front_right_joint: "front_right_mecanum_joint"
rear_left_joint: "rear_left_mecanum_joint"
rear_right_joint: "rear_right_mecanum_joint"
chassis_center_to_axle: 0.145
axle_center_to_wheel: 0.128
wheel_radius: 0.0485
cmd_vel_timeout: 0.5
use_stamped_vel: false
| 1,933 |
YAML
| 29.21875 | 57 | 0.636317 |
Coriago/examplo-ros2/src/robot_description/config/xbox-holonomic.config.yaml
|
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear:
x: 0.7
y: 0.7
axis_angular: # Left thumb stick horizontal
yaw: 3
scale_angular:
yaw: 1.5
| 285 |
YAML
| 16.874999 | 48 | 0.575439 |
Coriago/examplo-ros2/src/robot_control/setup.py
|
from setuptools import setup
package_name = 'robot_control'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='helios',
maintainer_email='[email protected]',
description='Control the robot',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'publish = robot_control.publish_joint_command:main',
],
},
)
| 664 |
Python
| 23.629629 | 65 | 0.596386 |
Coriago/examplo-ros2/src/robot_control/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 |
Coriago/examplo-ros2/src/robot_control/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 |
Coriago/examplo-ros2/src/robot_control/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 |
Coriago/examplo-ros2/src/robot_control/robot_control/publish_joint_command.py
|
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_joint_commands')
self.publisher_ = self.create_publisher(JointState, 'isaac_joint_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
velocity_cmds = JointState()
velocity_cmds.name = [
'front_left_mecanum_joint',
'front_right_mecanum_joint',
'rear_left_mecanum_joint',
'rear_right_mecanum_joint']
velocity_cmds.velocity = [ 15.0, 15.0, 15.0, 15.0 ]
self.publisher_.publish(velocity_cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| 1,191 |
Python
| 24.913043 | 87 | 0.609572 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/config/extension.toml
|
[core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
title = "Examplo Bot"
description = "Extension for running examplo bot in Isaac Sim"
authors = ["Gage Miller"]
repository = ""
keywords = ["isaac", "samples", "manipulation"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
writeTarget.kit = true
[dependencies]
"omni.kit.uiapp" = {}
"omni.physx" = {}
"omni.physx.vehicle" = {}
"omni.isaac.dynamic_control" = {}
"omni.isaac.motion_planning" = {}
"omni.isaac.synthetic_utils" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
"omni.isaac.franka" = {}
"omni.isaac.dofbot" = {}
"omni.isaac.universal_robots" = {}
"omni.isaac.motion_generation" = {}
"omni.isaac.demos" = {}
"omni.graph.action" = {}
"omni.graph.nodes" = {}
"omni.graph.core" = {}
"omni.isaac.quadruped" = {}
"omni.isaac.wheeled_robots" = {}
"omni.isaac.examples" = {}
[[python.module]]
name = "omni.isaac.examplo_bot.import_bot"
[[test]]
timeout = 960
| 1,023 |
TOML
| 21.755555 | 62 | 0.660802 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/base_sample/base_sample.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.core import World
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async
import gc
from abc import abstractmethod
class BaseSample(object):
def __init__(self) -> None:
self._world = None
self._current_tasks = None
self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0}
# self._logging_info = ""
return
def get_world(self):
return self._world
def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None):
if physics_dt is not None:
self._world_settings["physics_dt"] = physics_dt
if stage_units_in_meters is not None:
self._world_settings["stage_units_in_meters"] = stage_units_in_meters
if rendering_dt is not None:
self._world_settings["rendering_dt"] = rendering_dt
return
async def load_world_async(self):
"""Function called when clicking load buttton
"""
if World.instance() is None:
await create_new_stage_async()
self._world = World(**self._world_settings)
await self._world.initialize_simulation_context_async()
self.setup_scene()
else:
self._world = World.instance()
self._current_tasks = self._world.get_current_tasks()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_load()
if len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
async def reset_async(self):
"""Function called when clicking reset buttton
"""
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.remove_physics_callback("tasks_step")
await self._world.play_async()
await update_stage_async()
await self.setup_pre_reset()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_reset()
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
@abstractmethod
def setup_scene(self, scene: Scene) -> None:
"""used to setup anything in the world, adding tasks happen here for instance.
Args:
scene (Scene): [description]
"""
return
@abstractmethod
async def setup_post_load(self):
"""called after first reset of the world when pressing load,
intializing provate variables happen here.
"""
return
@abstractmethod
async def setup_pre_reset(self):
""" called in reset button before resetting the world
to remove a physics callback for instance or a controller reset
"""
return
@abstractmethod
async def setup_post_reset(self):
""" called in reset button after resetting the world which includes one step with rendering
"""
return
@abstractmethod
async def setup_post_clear(self):
"""called after clicking clear button
or after creating a new stage and clearing the instance of the world with its callbacks
"""
return
# def log_info(self, info):
# self._logging_info += str(info) + "\n"
# return
def _world_cleanup(self):
self._world.stop()
self._world.clear_all_callbacks()
self._current_tasks = None
self.world_cleanup()
return
def world_cleanup(self):
"""Function called when extension shutdowns and starts again, (hot reloading feature)
"""
return
async def clear_async(self):
"""Function called when clicking clear buttton
"""
await create_new_stage_async()
if self._world is not None:
self._world_cleanup()
self._world.clear_instance()
self._world = None
gc.collect()
await self.setup_post_clear()
return
| 4,657 |
Python
| 34.287879 | 115 | 0.624222 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/base_sample/base_sample_extension.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from abc import abstractmethod
import omni.ext
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
import weakref
from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder
import asyncio
from omni.isaac.examplo_bot.base_sample import BaseSample
from omni.isaac.core import World
class BaseSampleExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
self._menu_items = None
self._buttons = None
self._ext_id = ext_id
self._sample = None
self._extra_frames = []
return
def start_extension(
self,
menu_name: str,
submenu_name: str,
name: str,
title: str,
doc_link: str,
overview: str,
file_path: str,
sample=None,
number_of_extra_frames=1,
window_width=350,
):
if sample is None:
self._sample = BaseSample()
else:
self._sample = sample
menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())]
if menu_name == "" or menu_name is None:
self._menu_items = menu_items
elif submenu_name == "" or submenu_name is None:
self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)]
else:
self._menu_items = [
MenuItemDescription(
name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)]
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._buttons = dict()
self._build_ui(
name=name,
title=title,
doc_link=doc_link,
overview=overview,
file_path=file_path,
number_of_extra_frames=number_of_extra_frames,
window_width=window_width,
)
if self.get_world() is not None:
self._on_load_world()
return
@property
def sample(self):
return self._sample
def get_frame(self, index):
if index >= len(self._extra_frames):
raise Exception("there were {} extra frames created only".format(len(self._extra_frames)))
return self._extra_frames[index]
def get_world(self):
return World.instance()
def get_buttons(self):
return self._buttons
def _build_ui(self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width):
self._window = omni.ui.Window(
name, width=window_width, height=0, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
setup_ui_headers(self._ext_id, file_path, title, doc_link, overview)
self._controls_frame = ui.CollapsableFrame(
title="World Controls",
width=ui.Fraction(1),
height=0,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with ui.VStack(style=get_style(), spacing=5, height=0):
for i in range(number_of_extra_frames):
self._extra_frames.append(
ui.CollapsableFrame(
title="",
width=ui.Fraction(0.33),
height=0,
visible=False,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
)
with self._controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
dict = {
"label": "Load World",
"type": "button",
"text": "Load",
"tooltip": "Load World and Task",
"on_clicked_fn": self._on_load_world,
}
self._buttons["Load World"] = btn_builder(**dict)
self._buttons["Load World"].enabled = True
dict = {
"label": "Reset",
"type": "button",
"text": "Reset",
"tooltip": "Reset robot and environment",
"on_clicked_fn": self._on_reset,
}
self._buttons["Reset"] = btn_builder(**dict)
self._buttons["Reset"].enabled = False
return
def _set_button_tooltip(self, button_name, tool_tip):
self._buttons[button_name].set_tooltip(tool_tip)
return
def _on_load_world(self):
async def _on_load_world_async():
await self._sample.load_world_async()
await omni.kit.app.get_app().next_update_async()
self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event)
self._enable_all_buttons(True)
self._buttons["Load World"].enabled = False
self.post_load_button_event()
self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event)
asyncio.ensure_future(_on_load_world_async())
return
def _on_reset(self):
async def _on_reset_async():
await self._sample.reset_async()
await omni.kit.app.get_app().next_update_async()
self.post_reset_button_event()
asyncio.ensure_future(_on_reset_async())
return
@abstractmethod
def post_reset_button_event(self):
return
@abstractmethod
def post_load_button_event(self):
return
@abstractmethod
def post_clear_button_event(self):
return
def _enable_all_buttons(self, flag):
for btn_name, btn in self._buttons.items():
if isinstance(btn, omni.ui._ui.Button):
btn.enabled = flag
return
def _menu_callback(self):
self._window.visible = not self._window.visible
return
def _on_window(self, status):
# if status:
return
def on_shutdown(self):
self._extra_frames = []
if self._sample._world is not None:
self._sample._world_cleanup()
if self._menu_items is not None:
self._sample_window_cleanup()
if self._buttons is not None:
self._buttons["Load World"].enabled = True
self._enable_all_buttons(False)
self.shutdown_cleanup()
return
def shutdown_cleanup(self):
return
def _sample_window_cleanup(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
self._menu_items = None
self._buttons = None
return
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
if World.instance() is not None:
self.sample._world_cleanup()
self.sample._world.clear_instance()
if hasattr(self, "_buttons"):
if self._buttons is not None:
self._enable_all_buttons(False)
self._buttons["Load World"].enabled = True
return
def _reset_on_stop_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._buttons["Load World"].enabled = False
self._buttons["Reset"].enabled = True
self.post_clear_button_event()
return
| 8,607 |
Python
| 35.786325 | 114 | 0.541187 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/base_sample/__init__.py
|
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examplo_bot.base_sample.base_sample import BaseSample
from omni.isaac.examplo_bot.base_sample.base_sample_extension import BaseSampleExtension
| 588 |
Python
| 48.083329 | 88 | 0.819728 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/import_bot/__init__.py
|
from omni.isaac.examplo_bot.import_bot.import_bot import ImportBot
from omni.isaac.examplo_bot.import_bot.import_bot_extension import ImportBotExtension
| 154 |
Python
| 37.749991 | 85 | 0.844156 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/import_bot/import_bot_extension.py
|
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
from omni.isaac.examplo_bot.base_sample import BaseSampleExtension
from omni.isaac.examplo_bot.import_bot.import_bot import ImportBot
class ImportBotExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Examplo Bot",
submenu_name="",
name="Import URDF",
title="Load the URDF for Examplo Bot",
doc_link="",
overview="This loads the examplo bot into Isaac Sim.",
file_path=os.path.abspath(__file__),
sample=ImportBot(),
)
return
| 1,079 |
Python
| 37.571427 | 76 | 0.688601 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/omni/isaac/examplo_bot/import_bot/import_bot.py
|
import omni.graph.core as og
import omni.usd
from omni.isaac.examplo_bot.base_sample import BaseSample
from omni.isaac.urdf import _urdf
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils import prims
from omni.isaac.core_nodes.scripts.utils import set_target_prims
from omni.kit.viewport_legacy import get_default_viewport_window
from pxr import UsdPhysics
import omni.kit.commands
import os
import numpy as np
import math
import carb
def set_drive_params(drive, stiffness, damping, max_force):
drive.GetStiffnessAttr().Set(stiffness)
drive.GetDampingAttr().Set(damping)
drive.GetMaxForceAttr().Set(max_force)
return
class ImportBot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
self.setup_perspective_cam()
self.setup_world_action_graph()
return
async def setup_post_load(self):
self._world = self.get_world()
self.robot_name = "examplo"
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
self.path_to_urdf = os.path.join(self.project_root_path, "src/robot_description/examplo.urdf")
carb.log_info(self.path_to_urdf)
self._robot_prim_path = self.import_robot(self.path_to_urdf)
if self._robot_prim_path is None:
print("Error: failed to import robot")
return
self._robot_prim = self._world.scene.add(
Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.3]))
)
self.configure_robot(self._robot_prim_path)
return
def import_robot(self, urdf_path):
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = False
import_config.import_inertia_tensor = True
import_config.default_drive_strength = 1047.19751
import_config.default_position_drive_damping = 52.35988
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.distance_scale = 1.0
import_config.density = 0.0
result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config)
if result:
return prim_path
return None
def configure_robot(self, robot_prim_path):
w_sides = ['left', 'right']
l_sides = ['front', 'rear']
stage = self._world.stage
for w_side in w_sides:
for l_side in l_sides:
for i in range(9):
joint_name = "{}_{}_roller_{}_joint".format(l_side, w_side, i)
joint_path = "{}/{}_{}_mecanum_link/{}".format(robot_prim_path, l_side, w_side, joint_name)
prim = stage.GetPrimAtPath(joint_path)
omni.kit.commands.execute(
"UnapplyAPISchemaCommand",
api=UsdPhysics.DriveAPI,
prim=prim,
api_prefix="drive",
multiple_api_token="angular")
# drive = UsdPhysics.DriveAPI.Get(prim, "angular")
# set_drive_params(drive, 0.0, 2.0, 0.0)
front_left = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/chassis_link/front_left_mecanum_joint"), "angular")
front_right = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/chassis_link/front_right_mecanum_joint"), "angular")
rear_left = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/chassis_link/rear_left_mecanum_joint"), "angular")
rear_right = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/chassis_link/rear_right_mecanum_joint"), "angular")
set_drive_params(front_left, 0, math.radians(1e5), 98.0)
set_drive_params(front_right, 0, math.radians(1e5), 98.0)
set_drive_params(rear_left, 0, math.radians(1e5), 98.0)
set_drive_params(rear_right, 0, math.radians(1e5), 98.0)
self.create_lidar(robot_prim_path)
self.create_depth_camera()
self.setup_robot_action_graph(robot_prim_path)
return
def create_lidar(self, robot_prim_path):
lidar_parent = "{}/lidar_link".format(robot_prim_path)
lidar_path = "/lidar"
self.lidar_prim_path = lidar_parent + lidar_path
result, prim = omni.kit.commands.execute(
"RangeSensorCreateLidar",
path=lidar_path,
parent=lidar_parent,
min_range=0.4,
max_range=25.0,
draw_points=False,
draw_lines=True,
horizontal_fov=360.0,
vertical_fov=30.0,
horizontal_resolution=0.4,
vertical_resolution=4.0,
rotation_rate=0.0,
high_lod=False,
yaw_offset=0.0,
enable_semantics=False
)
return
def create_depth_camera(self):
self.depth_left_camera_path = f"{self._robot_prim_path}/zed_left_camera_frame/left_cam"
self.depth_right_camera_path = f"{self._robot_prim_path}/zed_right_camera_frame/right_cam"
self.left_camera = prims.create_prim(
prim_path=self.depth_left_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
self.right_camera = prims.create_prim(
prim_path=self.depth_right_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
return
def setup_world_action_graph(self):
og.Controller.edit(
{"graph_path": "/globalclock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"),
("Context.outputs:context", "PublishClock.inputs:context"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
],
}
)
return
def setup_perspective_cam(self):
# Get the Viewport and the Default Camera
viewport_window = get_default_viewport_window()
camera = self.get_world().stage.GetPrimAtPath(viewport_window.get_active_camera())
# Get Default Cam Values
camAttributes = {}
camOrientation = None
camTranslation = None
for att in camera.GetAttributes():
name = att.GetName()
if not (name.startswith('omni') or name.startswith('xform')):
camAttributes[att.GetName()] = att.Get()
elif name == 'xformOp:orient':
convertedQuat = [att.Get().GetReal()] + list(att.Get().GetImaginary())
camOrientation = np.array(convertedQuat)
elif name == 'xformOp:translate':
camTranslation = np.array(list(att.Get()))
# Modify what we want
camAttributes["clippingRange"] = (0.1, 1000000)
camAttributes["clippingPlanes"] = np.array([1.0, 0.0, 1.0, 1.0])
# Create a new camera with desired values
cam_path = "/World/PerspectiveCam"
prims.create_prim(
prim_path=cam_path,
prim_type="Camera",
translation=camTranslation,
orientation=camOrientation,
attributes=camAttributes,
)
# Use the camera for our viewport
viewport_window.set_active_camera(cam_path)
return
def setup_robot_action_graph(self, robot_prim_path):
robot_controller_path = f"{robot_prim_path}/ros_interface_controller"
og.Controller.edit(
{"graph_path": robot_controller_path, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
("isaac_read_lidar_beams_node", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
("ros2_publish_laser_scan", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
("ros2_camera_helper", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("ros2_camera_helper_02", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("ros2_camera_helper_03", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("isaac_create_viewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
("set_active_camera", "omni.graph.ui.SetActiveViewportCamera"),
("get_prim_path", "omni.graph.nodes.GetPrimPath"),
("constant_token", "omni.graph.nodes.ConstantToken"),
("constant_token_02", "omni.graph.nodes.ConstantToken"),
],
og.Controller.Keys.SET_VALUES: [
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeJointState.inputs:topicName", "isaac_joint_commands"),
("articulation_controller.inputs:usePath", False),
("ros2_publish_laser_scan.inputs:topicName", "laser_scan"),
("ros2_publish_laser_scan.inputs:frameId", "base_link"),
("ros2_camera_helper.inputs:frameId", "base_link"),
("ros2_camera_helper_02.inputs:frameId", "base_link"),
("ros2_camera_helper_02.inputs:topicName", "camera_info"),
("ros2_camera_helper_03.inputs:frameId", "base_link"),
("ros2_camera_helper_03.inputs:topicName", "depth"),
("isaac_create_viewport.inputs:viewportId", 1),
("constant_token.inputs:value", "camera_info"),
("constant_token_02.inputs:value", "depth"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "isaac_read_lidar_beams_node.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "isaac_create_viewport.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "articulation_controller.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("ReadSimTime.outputs:simulationTime", "ros2_publish_laser_scan.inputs:timeStamp"),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeJointState.inputs:context"),
("Context.outputs:context", "ros2_publish_laser_scan.inputs:context"),
("Context.outputs:context", "ros2_camera_helper.inputs:context"),
("Context.outputs:context", "ros2_camera_helper_02.inputs:context"),
("SubscribeJointState.outputs:jointNames", "articulation_controller.inputs:jointNames"),
("SubscribeJointState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"),
("isaac_read_lidar_beams_node.outputs:execOut", "ros2_publish_laser_scan.inputs:execIn"),
("isaac_read_lidar_beams_node.outputs:azimuthRange", "ros2_publish_laser_scan.inputs:azimuthRange"),
("isaac_read_lidar_beams_node.outputs:depthRange", "ros2_publish_laser_scan.inputs:depthRange"),
("isaac_read_lidar_beams_node.outputs:horizontalFov", "ros2_publish_laser_scan.inputs:horizontalFov"),
("isaac_read_lidar_beams_node.outputs:horizontalResolution", "ros2_publish_laser_scan.inputs:horizontalResolution"),
("isaac_read_lidar_beams_node.outputs:intensitiesData", "ros2_publish_laser_scan.inputs:intensitiesData"),
("isaac_read_lidar_beams_node.outputs:linearDepthData", "ros2_publish_laser_scan.inputs:linearDepthData"),
("isaac_read_lidar_beams_node.outputs:numCols", "ros2_publish_laser_scan.inputs:numCols"),
("isaac_read_lidar_beams_node.outputs:numRows", "ros2_publish_laser_scan.inputs:numRows"),
("isaac_read_lidar_beams_node.outputs:rotationRate", "ros2_publish_laser_scan.inputs:rotationRate"),
("isaac_create_viewport.outputs:viewport", "ros2_camera_helper.inputs:viewport"),
("isaac_create_viewport.outputs:viewport", "ros2_camera_helper_02.inputs:viewport"),
("isaac_create_viewport.outputs:viewport", "set_active_camera.inputs:viewport"),
("isaac_create_viewport.outputs:execOut", "set_active_camera.inputs:execIn"),
("set_active_camera.outputs:execOut", "ros2_camera_helper.inputs:execIn"),
("set_active_camera.outputs:execOut", "ros2_camera_helper_02.inputs:execIn"),
("get_prim_path.outputs:primPath", "set_active_camera.inputs:primPath"),
("constant_token.inputs:value", "ros2_camera_helper_02.inputs:type"),
],
}
)
set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/isaac_read_lidar_beams_node", targetPrimPaths=[self.lidar_prim_path], inputName="inputs:lidarPrim")
set_target_prims(primPath=f"{robot_controller_path}/get_prim_path", targetPrimPaths=[self.depth_left_camera_path], inputName="inputs:prim")
return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
async def setup_post_clear(self):
return
def world_cleanup(self):
self._world.scene.remove_object(self.robot_name)
return
| 15,832 |
Python
| 49.746795 | 159 | 0.593734 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/docs/CHANGELOG.md
|
**********
CHANGELOG
**********
[0.1.0] - 2022-6-26
========================
Added
-------
- Initial version of Examplo Bot Extension
| 137 |
Markdown
| 10.499999 | 42 | 0.430657 |
Coriago/examplo-ros2/isaac/omni.isaac.examplo_bot/docs/README.md
|
# Usage
To enable this extension, go to the Extension Manager menu and enable omni.isaac.examplo_bot extension.
| 114 |
Markdown
| 21.999996 | 103 | 0.789474 |
John-Dillermand/Isaac-Orbit/README.md
|
# Isaac-Orbit Maintenance Branch
| 34 |
Markdown
| 10.666663 | 32 | 0.794118 |
John-Dillermand/Isaac-Orbit/orbit/pyproject.toml
|
[tool.isort]
py_version = 310
line_length = 120
group_by_package = true
# Files to skip
skip_glob = ["docs/*", "logs/*", "_isaac_sim/*", ".vscode/*"]
# Order of imports
sections = [
"FUTURE",
"STDLIB",
"THIRDPARTY",
"ASSETS_FIRSTPARTY",
"FIRSTPARTY",
"EXTRA_FIRSTPARTY",
"LOCALFOLDER",
]
# Extra standard libraries considered as part of python (permissive licenses
extra_standard_library = [
"numpy",
"h5py",
"open3d",
"torch",
"tensordict",
"bpy",
"matplotlib",
"gymnasium",
"gym",
"scipy",
"hid",
"yaml",
"prettytable",
"toml",
"trimesh",
"tqdm",
]
# Imports from Isaac Sim and Omniverse
known_third_party = [
"omni.isaac.core",
"omni.replicator.isaac",
"omni.replicator.core",
"pxr",
"omni.kit.*",
"warp",
"carb",
]
# Imports from this repository
known_first_party = "omni.isaac.orbit"
known_assets_firstparty = "omni.isaac.assets"
known_extra_firstparty = [
"omni.isaac.contrib_tasks",
"omni.isaac.orbit_tasks"
]
# Imports from the local folder
known_local_folder = "config"
[tool.pyright]
include = ["source/extensions", "source/standalone"]
exclude = [
"**/__pycache__",
"**/_isaac_sim",
"**/docs",
"**/logs",
".git",
".vscode",
]
typeCheckingMode = "basic"
pythonVersion = "3.10"
pythonPlatform = "Linux"
enableTypeIgnoreComments = true
# This is required as the CI pre-commit does not download the module (i.e. numpy, torch, prettytable)
# Therefore, we have to ignore missing imports
reportMissingImports = "none"
# This is required to ignore for type checks of modules with stubs missing.
reportMissingModuleSource = "none" # -> most common: prettytable in mdp managers
reportGeneralTypeIssues = "none" # -> raises 218 errors (usage of literal MISSING in dataclasses)
reportOptionalMemberAccess = "warning" # -> raises 8 errors
reportPrivateUsage = "warning"
[tool.codespell]
skip = '*.usd,*.svg,*.png,_isaac_sim*,*.bib,*.css,*/_build'
quiet-level = 0
# the world list should always have words in lower case
ignore-words-list = "haa,slq,collapsable"
# todo: this is hack to deal with incorrect spelling of "Environment" in the Isaac Sim grid world asset
exclude-file = "source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/from_files/from_files.py"
| 2,340 |
TOML
| 23.642105 | 106 | 0.665385 |
John-Dillermand/Isaac-Orbit/orbit/CONTRIBUTING.md
|
# Contribution Guidelines
Orbit is a community maintained project. We wholeheartedly welcome contributions to the project to make
the framework more mature and useful for everyone. These may happen in forms of bug reports, feature requests,
design proposals and more.
For general information on how to contribute see
<https://isaac-orbit.github.io/orbit/source/refs/contributing.html>.
| 388 |
Markdown
| 42.222218 | 110 | 0.81701 |
John-Dillermand/Isaac-Orbit/orbit/CONTRIBUTORS.md
|
# Orbit Developers and Contributors
This is the official list of Orbit Project developers and contributors.
To see the full list of contributors, please check the revision history in the source control.
Guidelines for modifications:
* Please keep the lists sorted alphabetically.
* Names should be added to this file as: *individual names* or *organizations*.
* E-mail addresses are tracked elsewhere to avoid spam.
## Developers
* Boston Dynamics AI Institute, Inc.
* ETH Zurich
* NVIDIA Corporation & Affiliates
* University of Toronto
---
* David Hoeller
* Farbod Farshidian
* Hunter Hansen
* James Smith
* **Mayank Mittal** (maintainer)
* Nikita Rudin
* Pascal Roth
## Contributors
* Anton Bjørndahl Mortensen
* Alice Zhou
* Andrej Orsula
* Antonio Serrano-Muñoz
* Arjun Bhardwaj
* Calvin Yu
* Chenyu Yang
* Jia Lin Yuan
* Jingzhou Liu
* Kourosh Darvish
* Qinxi Yu
* René Zurbrügg
* Ritvik Singh
* Rosario Scalise
## Acknowledgements
* Ajay Mandlekar
* Animesh Garg
* Buck Babich
* Gavriel State
* Hammad Mazhar
* Marco Hutter
* Yunrong Guo
| 1,057 |
Markdown
| 17.892857 | 94 | 0.757805 |
John-Dillermand/Isaac-Orbit/orbit/README.md
|

---
# Orbit
[](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html)
[](https://docs.python.org/3/whatsnew/3.10.html)
[](https://releases.ubuntu.com/20.04/)
[](https://pre-commit.com/)
[](https://isaac-orbit.github.io/orbit)
[](https://opensource.org/licenses/BSD-3-Clause)
<!-- TODO: Replace docs status with workflow badge? Link: https://github.com/isaac-orbit/orbit/actions/workflows/docs.yaml/badge.svg -->
**Orbit** is a unified and modular framework for robot learning that aims to simplify common workflows
in robotics research (such as RL, learning from demonstrations, and motion planning). It is built upon
[NVIDIA Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html) to leverage the latest
simulation capabilities for photo-realistic scenes and fast and accurate simulation.
Please refer to our [documentation page](https://isaac-orbit.github.io/orbit) to learn more about the
installation steps, features, and tutorials.
## 🎉 Announcement (22.12.2023)
We're excited to announce merging of our latest development branch into the main branch! This update introduces
several improvements and fixes to enhance the modularity and user-friendliness of the framework. We have added
several new environments, especially for legged locomotion, and are in the process of adding new environments.
Feel free to explore the latest changes and updates. We appreciate your ongoing support and contributions!
For more details, please check the post here: [#106](https://github.com/NVIDIA-Omniverse/Orbit/discussions/106)
## Contributing to Orbit
We wholeheartedly welcome contributions from the community to make this framework mature and useful for everyone.
These may happen as bug reports, feature requests, or code contributions. For details, please check our
[contribution guidelines](https://isaac-orbit.github.io/orbit/source/refs/contributing.html).
## Troubleshooting
Please see the [troubleshooting](https://isaac-orbit.github.io/orbit/source/refs/troubleshooting.html) section for
common fixes or [submit an issue](https://github.com/NVIDIA-Omniverse/orbit/issues).
For issues related to Isaac Sim, we recommend checking its [documentation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html)
or opening a question on its [forums](https://forums.developer.nvidia.com/c/agx-autonomous-machines/isaac/67).
## Support
* Please use GitHub [Discussions](https://github.com/NVIDIA-Omniverse/Orbit/discussions) for discussing ideas, asking questions, and requests for new features.
* Github [Issues](https://github.com/NVIDIA-Omniverse/orbit/issues) should only be used to track executable pieces of work with a definite scope and a clear deliverable. These can be fixing bugs, documentation issues, new features, or general updates.
## Acknowledgement
NVIDIA Isaac Sim is available freely under [individual license](https://www.nvidia.com/en-us/omniverse/download/). For more information about its license terms, please check [here](https://docs.omniverse.nvidia.com/app_isaacsim/common/NVIDIA_Omniverse_License_Agreement.html#software-support-supplement).
Orbit framework is released under [BSD-3 License](LICENSE). The license files of its dependencies and assets are present in the [`docs/licenses`](docs/licenses) directory.
## Citation
Please cite [this paper](https://arxiv.org/abs/2301.04195) if you use this framework in your work:
```text
@article{mittal2023orbit,
author={Mittal, Mayank and Yu, Calvin and Yu, Qinxi and Liu, Jingzhou and Rudin, Nikita and Hoeller, David and Yuan, Jia Lin and Singh, Ritvik and Guo, Yunrong and Mazhar, Hammad and Mandlekar, Ajay and Babich, Buck and State, Gavriel and Hutter, Marco and Garg, Animesh},
journal={IEEE Robotics and Automation Letters},
title={Orbit: A Unified Simulation Framework for Interactive Robot Learning Environments},
year={2023},
volume={8},
number={6},
pages={3740-3747},
doi={10.1109/LRA.2023.3270034}
}
```
| 4,504 |
Markdown
| 59.066666 | 304 | 0.777753 |
John-Dillermand/Isaac-Orbit/orbit/tools/tests_to_skip.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# The following tests are skipped by run_tests.py
TESTS_TO_SKIP = [
# orbit
"test_argparser_launch.py", # app.close issue
"test_env_var_launch.py", # app.close issue
"test_kwarg_launch.py", # app.close issue
"compat/test_kit_utils.py", # Compat to be deprecated
"compat/sensors/test_height_scanner.py", # Compat to be deprecated
"compat/sensors/test_camera.py", # Timing out
"test_differential_ik.py", # Failing
# orbit_tasks
"test_data_collector.py", # Failing
"test_record_video.py", # Failing
"test_rsl_rl_wrapper.py", # Timing out (10 minutes)
"test_sb3_wrapper.py", # Timing out (10 minutes)
]
| 785 |
Python
| 34.727271 | 71 | 0.667516 |
John-Dillermand/Isaac-Orbit/orbit/tools/run_all_tests.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""A runner script for all the tests within source directory.
.. code-block:: bash
./orbit.sh -p tools/run_all_tests.py
# for dry run
./orbit.sh -p tools/run_all_tests.py --discover_only
# for quiet run
./orbit.sh -p tools/run_all_tests.py --quiet
# for increasing timeout (default is 600 seconds)
./orbit.sh -p tools/run_all_tests.py --timeout 1000
"""
from __future__ import annotations
import argparse
import logging
import os
import subprocess
import time
from datetime import datetime
from pathlib import Path
from prettytable import PrettyTable
# Tests to skip
from tests_to_skip import TESTS_TO_SKIP
ORBIT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
"""Path to the root directory of Orbit repository."""
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Run all tests under current directory.")
# add arguments
parser.add_argument(
"--skip_tests",
default="",
help="Space separated list of tests to skip in addition to those in tests_to_skip.py.",
type=str,
nargs="*",
)
# configure default test directory (source directory)
default_test_dir = os.path.join(ORBIT_PATH, "source")
parser.add_argument(
"--test_dir", type=str, default=default_test_dir, help="Path to the directory containing the tests."
)
# configure default logging path based on time stamp
log_file_name = "test_results_" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".log"
default_log_path = os.path.join(ORBIT_PATH, "logs", log_file_name)
parser.add_argument(
"--log_path", type=str, default=default_log_path, help="Path to the log file to store the results in."
)
parser.add_argument("--discover_only", action="store_true", help="Only discover and print tests, don't run them.")
parser.add_argument("--quiet", action="store_true", help="Don't print to console, only log to file.")
parser.add_argument("--timeout", type=int, default=600, help="Timeout for each test in seconds.")
# parse arguments
args = parser.parse_args()
return args
def test_all(
test_dir: str,
tests_to_skip: list[str],
log_path: str,
timeout: float = 600.0,
discover_only: bool = False,
quiet: bool = False,
) -> bool:
"""Run all tests under the given directory.
Args:
test_dir: Path to the directory containing the tests.
tests_to_skip: List of tests to skip.
log_path: Path to the log file to store the results in.
timeout: Timeout for each test in seconds. Defaults to 600 seconds (10 minutes).
discover_only: If True, only discover and print the tests without running them. Defaults to False.
quiet: If False, print the output of the tests to the terminal console (in addition to the log file).
Defaults to False.
Returns:
True if all un-skipped tests pass or `discover_only` is True. Otherwise, False.
Raises:
ValueError: If any test to skip is not found under the given `test_dir`.
"""
# Create the log directory if it doesn't exist
os.makedirs(os.path.dirname(log_path), exist_ok=True)
# Add file handler to log to file
logging_handlers = [logging.FileHandler(log_path)]
# We also want to print to console
if not quiet:
logging_handlers.append(logging.StreamHandler())
# Set up logger
logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=logging_handlers)
# Discover all tests under current directory
all_test_paths = [str(path) for path in Path(test_dir).resolve().rglob("*test_*.py")]
skipped_test_paths = []
test_paths = []
# Check that all tests to skip are actually in the tests
for test_to_skip in tests_to_skip:
for test_path in all_test_paths:
if test_to_skip in test_path:
break
else:
raise ValueError(f"Test to skip '{test_to_skip}' not found in tests.")
# Remove tests to skip from the list of tests to run
if len(tests_to_skip) != 0:
for test_path in all_test_paths:
if any([test_to_skip in test_path for test_to_skip in tests_to_skip]):
skipped_test_paths.append(test_path)
else:
test_paths.append(test_path)
else:
test_paths = all_test_paths
# Sort test paths so they're always in the same order
all_test_paths.sort()
test_paths.sort()
skipped_test_paths.sort()
# Print tests to be run
logging.info("\n" + "=" * 60 + "\n")
logging.info(f"The following {len(all_test_paths)} tests will be run:")
for i, test_path in enumerate(all_test_paths):
logging.info(f"{i + 1:02d}: {test_path}")
logging.info("\n" + "=" * 60 + "\n")
logging.info(f"The following {len(skipped_test_paths)} tests are marked to be skipped:")
for i, test_path in enumerate(skipped_test_paths):
logging.info(f"{i + 1:02d}: {test_path}")
logging.info("\n" + "=" * 60 + "\n")
# Exit if only discovering tests
if discover_only:
return True
results = {}
# Resolve python executable to use
orbit_shell_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "orbit.sh")
# Run each script and store results
for test_path in test_paths:
results[test_path] = {}
before = time.time()
logging.info("\n" + "-" * 60 + "\n")
logging.info(f"[INFO] Running '{test_path}'\n")
try:
completed_process = subprocess.run(
["bash", orbit_shell_path, "-p", test_path], check=True, capture_output=True, timeout=timeout
)
except subprocess.TimeoutExpired as e:
logging.error(f"Timeout occurred: {e}")
result = "TIMEDOUT"
stdout = e.stdout
stderr = e.stderr
except Exception as e:
logging.error(f"Exception {e}!")
result = "FAILED"
stdout = e.stdout
stderr = e.stderr
else:
result = "PASSED" if completed_process.returncode == 0 else "FAILED"
stdout = completed_process.stdout
stderr = completed_process.stderr
after = time.time()
time_elapsed = after - before
# Decode stdout and stderr and write to file and print to console if desired
stdout_str = stdout.decode("utf-8") if stdout is not None else ""
stderr_str = stderr.decode("utf-8") if stderr is not None else ""
# Write to log file
logging.info(stdout_str)
logging.info(stderr_str)
logging.info(f"[INFO] Time elapsed: {time_elapsed:.2f} s")
logging.info(f"[INFO] Result '{test_path}': {result}")
# Collect results
results[test_path]["time_elapsed"] = time_elapsed
results[test_path]["result"] = result
# Calculate the number and percentage of passing tests
num_tests = len(all_test_paths)
num_passing = len([test_path for test_path in test_paths if results[test_path]["result"] == "PASSED"])
num_failing = len([test_path for test_path in test_paths if results[test_path]["result"] == "FAILED"])
num_timing_out = len([test_path for test_path in test_paths if results[test_path]["result"] == "TIMEDOUT"])
num_skipped = len(skipped_test_paths)
if num_tests == 0:
passing_percentage = 100
else:
passing_percentage = (num_passing + num_skipped) / num_tests * 100
# Print summaries of test results
summary_str = "\n\n"
summary_str += "===================\n"
summary_str += "Test Result Summary\n"
summary_str += "===================\n"
summary_str += f"Total: {num_tests}\n"
summary_str += f"Passing: {num_passing}\n"
summary_str += f"Failing: {num_failing}\n"
summary_str += f"Skipped: {num_skipped}\n"
summary_str += f"Timing Out: {num_timing_out}\n"
summary_str += f"Passing Percentage: {passing_percentage:.2f}%\n"
# Print time elapsed in hours, minutes, seconds
total_time = sum([results[test_path]["time_elapsed"] for test_path in test_paths])
summary_str += f"Total Time Elapsed: {total_time // 3600}h"
summary_str += f"{total_time // 60 % 60}m"
summary_str += f"{total_time % 60:.2f}s"
summary_str += "\n\n=======================\n"
summary_str += "Per Test Result Summary\n"
summary_str += "=======================\n"
# Construct table of results per test
per_test_result_table = PrettyTable(field_names=["Test Path", "Result", "Time (s)"])
per_test_result_table.align["Test Path"] = "l"
per_test_result_table.align["Time (s)"] = "r"
for test_path in test_paths:
per_test_result_table.add_row(
[test_path, results[test_path]["result"], f"{results[test_path]['time_elapsed']:0.2f}"]
)
for test_path in skipped_test_paths:
per_test_result_table.add_row([test_path, "SKIPPED", "N/A"])
summary_str += per_test_result_table.get_string()
# Print summary to console and log file
logging.info(summary_str)
# Only count failing and timing out tests towards failure
return num_failing + num_timing_out == 0
if __name__ == "__main__":
# parse command line arguments
args = parse_args()
# add tests to skip to the list of tests to skip
tests_to_skip = TESTS_TO_SKIP
tests_to_skip += args.skip_tests
# run all tests
test_success = test_all(
test_dir=args.test_dir,
tests_to_skip=tests_to_skip,
log_path=args.log_path,
timeout=args.timeout,
discover_only=args.discover_only,
quiet=args.quiet,
)
# update exit status based on all tests passing or not
if not test_success:
exit(1)
| 9,974 |
Python
| 35.538461 | 118 | 0.624123 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/setup.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.orbit_tasks' python package."""
import itertools
import os
import toml
from setuptools import setup
# Obtain the extension data from the extension.toml file
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
# Read the extension.toml file
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# generic
"numpy",
"torch==2.0.1",
"torchvision>=0.14.1", # ensure compatibility with torch 1.13.1
"protobuf>=3.20.2",
# data collection
"h5py",
# basic logger
"tensorboard",
# video recording
"moviepy",
]
# Extra dependencies for RL agents
EXTRAS_REQUIRE = {
"sb3": ["stable-baselines3>=2.0"],
"skrl": ["skrl>=1.1.0"],
"rl_games": ["rl-games==1.6.1", "gym"], # rl-games still needs gym :(
"rsl_rl": ["rsl_rl@git+https://github.com/leggedrobotics/rsl_rl.git"],
"robomimic": ["robomimic@git+https://github.com/ARISE-Initiative/robomimic.git"],
}
# cumulation of all extra-requires
EXTRAS_REQUIRE["all"] = list(itertools.chain.from_iterable(EXTRAS_REQUIRE.values()))
# Installation operation
setup(
name="omni-isaac-orbit_tasks",
author="ORBIT Project Developers",
maintainer="Mayank Mittal",
maintainer_email="[email protected]",
url=EXTENSION_TOML_DATA["package"]["repository"],
version=EXTENSION_TOML_DATA["package"]["version"],
description=EXTENSION_TOML_DATA["package"]["description"],
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
include_package_data=True,
python_requires=">=3.10",
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
packages=["omni.isaac.orbit_tasks"],
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 2023.1.0-hotfix.1",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 2,113 |
Python
| 29.637681 | 89 | 0.67345 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_environments.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnv, RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
class TestEnvironments(unittest.TestCase):
"""Test cases for all registered environments."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
"""
Test fixtures.
"""
def test_multiple_instances_gpu(self):
"""Run all environments with multiple instances and check environments return valid signals."""
# common parameters
num_envs = 32
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
def test_single_instance_gpu(self):
"""Run all environments with single instance and check environments return valid signals."""
# common parameters
num_envs = 1
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
"""
Helper functions.
"""
def _check_random_actions(self, task_name: str, use_gpu: bool, num_envs: int, num_steps: int = 1000):
"""Run random actions and check environments return valid signals."""
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=use_gpu, num_envs=num_envs)
# create environment
env: RLTaskEnv = gym.make(task_name, cfg=env_cfg)
# reset environment
obs, _ = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
# simulate environment for num_steps steps
with torch.inference_mode():
for _ in range(num_steps):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
env.close()
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestEnvironments._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
# run main
unittest.main(verbosity=2, exit=False)
# close sim app
simulation_app.close()
| 4,763 |
Python
| 32.787234 | 105 | 0.613059 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_data_collector.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
import torch
import unittest
from omni.isaac.orbit_tasks.utils.data_collector import RobomimicDataCollector
class TestRobomimicDataCollector(unittest.TestCase):
"""Test dataset flushing behavior of robomimic data collector."""
def test_basic_flushing(self):
"""Adds random data into the collector and checks saving of the data."""
# name of the environment (needed by robomimic)
task_name = "My-Task-v0"
# specify directory for logging experiments
test_dir = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(test_dir, "output", "demos")
# name of the file to save data
filename = "hdf_dataset.hdf5"
# number of episodes to collect
num_demos = 10
# number of environments to simulate
num_envs = 4
# create data-collector
collector_interface = RobomimicDataCollector(task_name, log_dir, filename, num_demos)
# reset the collector
collector_interface.reset()
while not collector_interface.is_stopped():
# generate random data to store
# -- obs
obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- actions
actions = torch.randn(num_envs, 7)
# -- next obs
next_obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- rewards
rewards = torch.randn(num_envs)
# -- dones
dones = torch.rand(num_envs) > 0.5
# store signals
# -- obs
for key, value in obs.items():
collector_interface.add(f"obs/{key}", value)
# -- actions
collector_interface.add("actions", actions)
# -- next_obs
for key, value in next_obs.items():
collector_interface.add(f"next_obs/{key}", value.cpu().numpy())
# -- rewards
collector_interface.add("rewards", rewards)
# -- dones
collector_interface.add("dones", dones)
# flush data from collector for successful environments
# note: in this case we flush all the time
reset_env_ids = dones.nonzero(as_tuple=False).squeeze(-1)
collector_interface.flush(reset_env_ids)
# close collector
collector_interface.close()
# TODO: Add inspection of the saved dataset as part of the test.
if __name__ == "__main__":
unittest.main()
| 3,057 |
Python
| 32.604395 | 101 | 0.610729 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_record_video.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, offscreen_render=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import os
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnv, RLTaskEnvCfg
import omni.isaac.contrib_tasks # noqa: F401
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils import parse_env_cfg
class TestRecordVideoWrapper(unittest.TestCase):
"""Test recording videos using the RecordVideo wrapper."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
# directory to save videos
cls.videos_dir = os.path.join(os.path.dirname(__file__), "output", "videos")
def setUp(self) -> None:
# common parameters
self.num_envs = 16
self.use_gpu = True
# video parameters
self.step_trigger = lambda step: step % 225 == 0
self.video_length = 200
def test_record_video(self):
"""Run random actions agent with recording of videos."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env: RLTaskEnv = gym.make(task_name, cfg=env_cfg, render_mode="rgb_array")
# directory to save videos
videos_dir = os.path.join(self.videos_dir, task_name)
# wrap environment to record videos
env = gym.wrappers.RecordVideo(
env, videos_dir, step_trigger=self.step_trigger, video_length=self.video_length, disable_logger=True
)
# reset environment
env.reset()
# simulate environment
with torch.inference_mode():
for _ in range(500):
# compute zero actions
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
_ = env.step(actions)
# close the simulator
env.close()
if __name__ == "__main__":
# run main
unittest.main(verbosity=2, exit=False)
# close sim app
simulation_app.close()
| 3,202 |
Python
| 31.353535 | 116 | 0.626483 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/wrappers/test_rsl_rl_wrapper.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlVecEnvWrapper
class TestRslRlVecEnvWrapper(unittest.TestCase):
"""Test that RSL-RL VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# only pick the first three environments to test
cls.registered_tasks = cls.registered_tasks[:3]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
obs, extras = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
self.assertTrue(self._check_valid_tensor(extras))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
def test_no_time_outs(self):
"""Check that environments with finite horizon do not send time-out signals."""
for task_name in self.registered_tasks[0:5]:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# change to finite horizon
env_cfg.is_finite_horizon = True
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
_, extras = env.reset()
# check signal
self.assertNotIn("time_outs", extras, msg="Time-out signal found in finite horizon environment.")
# simulate environment for 10 steps
with torch.inference_mode():
for _ in range(10):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
extras = env.step(actions)[-1]
# check signals
self.assertNotIn("time_outs", extras, msg="Time-out signal found in finite horizon environment.")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestRslRlVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
# run main
unittest.main(verbosity=2, exit=False)
# close sim app
simulation_app.close()
| 5,664 |
Python
| 34.40625 | 117 | 0.591984 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/wrappers/test_rl_games_wrapper.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rl_games import RlGamesVecEnvWrapper
class TestRlGamesVecEnvWrapper(unittest.TestCase):
"""Test that RL-Games VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# only pick the first three environments to test
cls.registered_tasks = cls.registered_tasks[:3]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RlGamesVecEnvWrapper(env, "cuda:0", 100, 100)
# reset environment
obs = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
# simulate environment for 100 steps
with torch.inference_mode():
for _ in range(100):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.num_envs, *env.action_space.shape, device=env.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestRlGamesVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
# run main
unittest.main(verbosity=2, exit=False)
# close sim app
simulation_app.close()
| 4,078 |
Python
| 31.895161 | 106 | 0.60667 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/test/wrappers/test_sb3_wrapper.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import os
from omni.isaac.orbit.app import AppLauncher
# launch the simulator
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
app_launcher = AppLauncher(headless=True, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import numpy as np
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.sb3 import Sb3VecEnvWrapper
class TestStableBaselines3VecEnvWrapper(unittest.TestCase):
"""Test that RSL-RL VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# only pick the first three environments to test
cls.registered_tasks = cls.registered_tasks[:3]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = Sb3VecEnvWrapper(env)
# reset environment
obs = env.reset()
# check signal
self.assertTrue(self._check_valid_array(obs))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = 2 * np.random.rand(env.num_envs, *env.action_space.shape) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_array(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_array(data: np.ndarray | dict | list) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, np.ndarray):
return not np.any(np.isnan(data))
elif isinstance(data, dict):
valid_array = True
for value in data.values():
if isinstance(value, dict):
valid_array &= TestStableBaselines3VecEnvWrapper._check_valid_array(value)
elif isinstance(value, np.ndarray):
valid_array &= not np.any(np.isnan(value))
return valid_array
elif isinstance(data, list):
valid_array = True
for value in data:
valid_array &= TestStableBaselines3VecEnvWrapper._check_valid_array(value)
return valid_array
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
# run main
unittest.main(verbosity=2, exit=False)
# close sim app
simulation_app.close()
| 4,269 |
Python
| 31.846154 | 106 | 0.604123 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/config/extension.toml
|
[package]
# Note: Semantic Versioning is used: https://semver.org/
version = "0.6.0"
# Description
title = "ORBIT Environments"
description="Extension containing suite of environments for robot learning."
readme = "docs/README.md"
repository = "https://github.com/NVIDIA-Omniverse/Orbit"
category = "robotics"
keywords = ["robotics", "rl", "il", "learning"]
[dependencies]
"omni.isaac.orbit" = {}
"omni.isaac.orbit_assets" = {}
"omni.isaac.core" = {}
"omni.isaac.gym" = {}
"omni.replicator.isaac" = {}
[[python.module]]
name = "omni.isaac.orbit_tasks"
| 557 |
TOML
| 23.260869 | 76 | 0.696589 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Package containing task implementations for various robotic environments."""
import os
import toml
# Conveniences to other module directories via relative paths
ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
"""Path to the extension source directory."""
ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml"))
"""Extension metadata dictionary parsed from the extension.toml file."""
# Configure the module-level variables
__version__ = ORBIT_TASKS_METADATA["package"]["version"]
##
# Register Gym environments.
##
from .utils import import_packages
# The blacklist is used to prevent importing configs from sub-packages
_BLACKLIST_PKGS = ["utils"]
# Import all configs in this package
import_packages(__name__, _BLACKLIST_PKGS)
| 946 |
Python
| 29.548386 | 95 | 0.742072 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Classic environments for control.
These environments are based on the MuJoCo environments provided by OpenAI.
Reference:
https://github.com/openai/gym/tree/master/gym/envs/mujoco
"""
| 315 |
Python
| 23.307691 | 75 | 0.75873 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/ant_env_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
import omni.isaac.orbit_tasks.classic.humanoid.mdp as mdp
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with an ant robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="average",
restitution_combine_mode="average",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# robot
robot = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Ant/ant_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=10.0,
enable_gyroscopic_forces=True,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False,
solver_position_iteration_count=4,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.001,
),
copy_from_source=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
joint_pos={".*": 0.0},
),
actuators={
"body": ImplicitActuatorCfg(
joint_names_expr=[".*"],
stiffness=0.0,
damping=0.0,
),
},
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_norm)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.1,
params={
"asset_cfg": SceneEntityCfg(
"robot", body_names=["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"]
)
},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class RandomizationCfg:
"""Configuration for randomization."""
reset_base = RandTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = RandTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=0.5)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005)
# (6) Penalty for energy consumption
energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}})
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}}
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.base_height, params={"minimum_height": 0.31})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class AntEnvCfg(RLTaskEnvCfg):
"""Configuration for the MuJoCo-style Ant walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
randomization: RandomizationCfg = RandomizationCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 7,543 |
Python
| 31.239316 | 116 | 0.636749 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Ant locomotion environment (similar to OpenAI Gym Ant-v2).
"""
import gymnasium as gym
from . import agents, ant_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Ant-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ant_env_cfg.AntEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AntPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 776 |
Python
| 24.899999 | 79 | 0.653351 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AntPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "ant"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,068 |
Python
| 24.45238 | 58 | 0.641386 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/develop/modules/skrl.utils.model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ppo.html
agent:
rollouts: 16
learning_epochs: 8
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "ant"
experiment_name: ""
write_interval: 40
checkpoint_interval: 400
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/modules/skrl.trainers.sequential.html
trainer:
timesteps: 8000
| 1,888 |
YAML
| 27.194029 | 88 | 0.710805 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L161
seed: 42
n_timesteps: !!float 1e7
policy: 'MlpPolicy'
batch_size: 128
n_steps: 512
gamma: 0.99
gae_lambda: 0.9
n_epochs: 20
ent_coef: 0.0
sde_sample_freq: 4
max_grad_norm: 0.5
vf_coef: 0.5
learning_rate: !!float 3e-5
use_sde: True
clip_range: 0.4
policy_kwargs: "dict(
log_std_init=-1,
ortho_init=False,
activation_fn=nn.ReLU,
net_arch=dict(pi=[256, 256], vf=[256, 256])
)"
| 557 |
YAML
| 22.249999 | 93 | 0.597846 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 152 |
Python
| 20.85714 | 56 | 0.736842 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: ant
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 500
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 32768
mini_epochs: 4
critic_coef: 2
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,502 |
YAML
| 18.51948 | 73 | 0.601198 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Cartpole balancing environment.
"""
import gymnasium as gym
from . import agents
from .cartpole_env_cfg import CartpoleEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Cartpole-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 784 |
Python
| 24.32258 | 79 | 0.667092 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/cartpole_env_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import math
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.utils import configclass
import omni.isaac.orbit_tasks.classic.cartpole.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.cartpole import CARTPOLE_CFG # isort:skip
##
# Scene definition
##
@configclass
class CartpoleSceneCfg(InteractiveSceneCfg):
"""Configuration for a cart-pole scene."""
# ground plane
ground = AssetBaseCfg(
prim_path="/World/ground",
spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)),
)
# cartpole
robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# lights
dome_light = AssetBaseCfg(
prim_path="/World/DomeLight",
spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0),
)
distant_light = AssetBaseCfg(
prim_path="/World/DistantLight",
spawn=sim_utils.DistantLightCfg(color=(0.9, 0.9, 0.9), intensity=2500.0),
init_state=AssetBaseCfg.InitialStateCfg(rot=(0.738, 0.477, 0.477, 0.0)),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel)
def __post_init__(self) -> None:
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class RandomizationCfg:
"""Configuration for randomization."""
# reset
reset_cart_position = RandTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]),
"position_range": (-1.0, 1.0),
"velocity_range": (-0.5, 0.5),
},
)
reset_pole_position = RandTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]),
"position_range": (-0.25 * math.pi, 0.25 * math.pi),
"velocity_range": (-0.25 * math.pi, 0.25 * math.pi),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Constant running reward
alive = RewTerm(func=mdp.is_alive, weight=1.0)
# (2) Failure penalty
terminating = RewTerm(func=mdp.is_terminated, weight=-2.0)
# (3) Primary task: keep pole upright
pole_pos = RewTerm(
func=mdp.joint_pos_target_l2,
weight=-1.0,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0},
)
# (4) Shaping tasks: lower cart velocity
cart_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.01,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])},
)
# (5) Shaping tasks: lower pole angular velocity
pole_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.005,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Time out
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Cart out of bounds
cart_out_of_bounds = DoneTerm(
func=mdp.joint_pos_manual_limit,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)},
)
@configclass
class CurriculumCfg:
"""Configuration for the curriculum."""
pass
##
# Environment configuration
##
@configclass
class CartpoleEnvCfg(RLTaskEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
randomization: RandomizationCfg = RandomizationCfg()
# MDP settings
curriculum: CurriculumCfg = CurriculumCfg()
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
# No command generator
commands: CommandsCfg = CommandsCfg()
# Post initialization
def __post_init__(self) -> None:
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 5
# viewer settings
self.viewer.eye = (8.0, 0.0, 5.0)
# simulation settings
self.sim.dt = 1 / 120
| 5,738 |
Python
| 27.132353 | 109 | 0.656849 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class CartpolePPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 150
save_interval = 50
experiment_name = "cartpole"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[32, 32],
critic_hidden_dims=[32, 32],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,065 |
Python
| 24.380952 | 58 | 0.644131 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/develop/modules/skrl.utils.model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ppo.html
agent:
rollouts: 16
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 1.e-3
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.01
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 2.0
kl_threshold: 0
rewards_shaper_scale: 1.0
# logging and checkpoint
experiment:
directory: "cartpole"
experiment_name: ""
write_interval: 12
checkpoint_interval: 120
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/modules/skrl.trainers.sequential.html
trainer:
timesteps: 2400
| 1,865 |
YAML
| 26.850746 | 88 | 0.713673 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L32
seed: 42
n_timesteps: !!float 1e6
policy: 'MlpPolicy'
n_steps: 16
batch_size: 4096
gae_lambda: 0.95
gamma: 0.99
n_epochs: 20
ent_coef: 0.01
learning_rate: !!float 3e-4
clip_range: !!float 0.2
policy_kwargs: "dict(
activation_fn=nn.ELU,
net_arch=[32, 32],
squash_output=False,
)"
vf_coef: 1.0
max_grad_norm: 1.0
| 475 |
YAML
| 21.666666 | 92 | 0.610526 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/agents/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg # noqa: F401, F403
| 172 |
Python
| 23.714282 | 56 | 0.72093 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
# doesn't have this fine grained control but made it close
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [32, 32]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: cartpole
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: False
normalize_value: False
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 1.0
normalize_advantage: False
gamma: 0.99
tau : 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 150
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 8192
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,648 |
YAML
| 19.873417 | 73 | 0.61165 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/mdp/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This sub-module contains the functions that are specific to the cartpole environments."""
from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
| 321 |
Python
| 28.272725 | 92 | 0.735202 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/mdp/rewards.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import wrap_to_pi
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def joint_pos_target_l2(env: RLTaskEnv, target: float, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize joint position deviation from a target value."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# wrap the joint positions to (-pi, pi)
joint_pos = wrap_to_pi(asset.data.joint_pos[:, asset_cfg.joint_ids])
# compute the reward
return torch.sum(torch.square(joint_pos - target), dim=1)
| 907 |
Python
| 32.629628 | 98 | 0.742007 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Humanoid locomotion environment (similar to OpenAI Gym Humanoid-v2).
"""
import gymnasium as gym
from . import agents, humanoid_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Humanoid-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": humanoid_env_cfg.HumanoidEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.HumanoidPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 811 |
Python
| 26.066666 | 79 | 0.668311 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/humanoid_env_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
import omni.isaac.orbit_tasks.classic.humanoid.mdp as mdp
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with a humanoid robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0),
debug_vis=False,
)
# robot
robot = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Humanoid/humanoid_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=None,
max_depenetration_velocity=10.0,
enable_gyroscopic_forces=True,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True,
solver_position_iteration_count=4,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.001,
),
copy_from_source=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 1.34),
joint_pos={".*": 0.0},
),
actuators={
"body": ImplicitActuatorCfg(
joint_names_expr=[".*"],
stiffness={
".*_waist.*": 20.0,
".*_upper_arm.*": 10.0,
"pelvis": 10.0,
".*_lower_arm": 2.0,
".*_thigh:0": 10.0,
".*_thigh:1": 20.0,
".*_thigh:2": 10.0,
".*_shin": 5.0,
".*_foot.*": 2.0,
},
damping={
".*_waist.*": 5.0,
".*_upper_arm.*": 5.0,
"pelvis": 5.0,
".*_lower_arm": 1.0,
".*_thigh:0": 5.0,
".*_thigh:1": 5.0,
".*_thigh:2": 5.0,
".*_shin": 0.1,
".*_foot.*": 1.0,
},
),
},
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(
asset_name="robot",
joint_names=[".*"],
scale={
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_norm)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.01,
params={"asset_cfg": SceneEntityCfg("robot", body_names=["left_foot", "right_foot"])},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class RandomizationCfg:
"""Configuration for randomization."""
reset_base = RandTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = RandTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=2.0)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01)
# (6) Penalty for energy consumption
energy = RewTerm(
func=mdp.power_consumption,
weight=-0.005,
params={
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
}
},
)
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio,
weight=-0.25,
params={
"threshold": 0.98,
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.base_height, params={"minimum_height": 0.8})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class HumanoidEnvCfg(RLTaskEnvCfg):
"""Configuration for the MuJoCo-style Humanoid walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
randomization: RandomizationCfg = RandomizationCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 9,141 |
Python
| 30.633218 | 116 | 0.560551 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class HumanoidPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "humanoid"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,078 |
Python
| 24.690476 | 58 | 0.644712 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/develop/modules/skrl.utils.model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ppo.html
agent:
rollouts: 32
learning_epochs: 8
mini_batches: 8
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "humanoid"
experiment_name: ""
write_interval: 80
checkpoint_interval: 800
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/modules/skrl.trainers.sequential.html
trainer:
timesteps: 16000
| 1,896 |
YAML
| 27.313432 | 88 | 0.712025 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L245
seed: 42
policy: 'MlpPolicy'
n_timesteps: !!float 5e7
batch_size: 256
n_steps: 512
gamma: 0.99
learning_rate: !!float 2.5e-4
ent_coef: 0.0
clip_range: 0.2
n_epochs: 10
gae_lambda: 0.95
max_grad_norm: 1.0
vf_coef: 0.5
policy_kwargs: "dict(
log_std_init=-2,
ortho_init=False,
activation_fn=nn.ReLU,
net_arch=dict(pi=[256, 256], vf=[256, 256])
)"
| 527 |
YAML
| 22.999999 | 93 | 0.590133 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/agents/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg # noqa: F401, F403
| 172 |
Python
| 23.714282 | 56 | 0.72093 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [400, 200, 100]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: humanoid
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
kl_threshold: 0.01
score_to_win: 20000
max_epochs: 1000
save_best_after: 100
save_frequency: 100
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 32
minibatch_size: 32768
mini_epochs: 5
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,483 |
YAML
| 18.526316 | 73 | 0.601483 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/mdp/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This sub-module contains the functions that are specific to the humanoid environment."""
from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403
from .observations import *
from .rewards import *
| 328 |
Python
| 26.416664 | 91 | 0.746951 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/mdp/rewards.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg
from . import observations as obs
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def upright_posture_bonus(
env: RLTaskEnv, threshold: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Reward for maintaining an upright posture."""
up_proj = obs.base_up_proj(env, asset_cfg).squeeze(-1)
return (up_proj > threshold).float()
def move_to_target_bonus(
env: RLTaskEnv,
threshold: float,
target_pos: tuple[float, float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
"""Reward for moving to the target heading."""
heading_proj = obs.base_heading_proj(env, target_pos, asset_cfg).squeeze(-1)
return torch.where(heading_proj > threshold, 1.0, heading_proj / threshold)
class progress_reward(ManagerTermBase):
"""Reward for making progress towards the target."""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# initialize the base class
super().__init__(cfg, env)
# create history buffer
self.potentials = torch.zeros(env.num_envs, device=env.device)
self.prev_potentials = torch.zeros_like(self.potentials)
def reset(self, env_ids: torch.Tensor):
# extract the used quantities (to enable type-hinting)
asset: Articulation = self._env.scene["robot"]
# compute projection of current heading to desired heading vector
target_pos = torch.tensor(self.cfg.params["target_pos"], device=self.device)
to_target_pos = target_pos - asset.data.root_pos_w[env_ids, :3]
# reward terms
self.potentials[env_ids] = -torch.norm(to_target_pos, p=2, dim=-1) / self._env.step_dt
self.prev_potentials[env_ids] = self.potentials[env_ids]
def __call__(
self,
env: RLTaskEnv,
target_pos: tuple[float, float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute vector to target
target_pos = torch.tensor(target_pos, device=env.device)
to_target_pos = target_pos - asset.data.root_pos_w[:, :3]
to_target_pos[:, 2] = 0.0
# update history buffer and compute new potential
self.prev_potentials[:] = self.potentials[:]
self.potentials[:] = -torch.norm(to_target_pos, p=2, dim=-1) / env.step_dt
return self.potentials - self.prev_potentials
class joint_limits_penalty_ratio(ManagerTermBase):
"""Penalty for violating joint limits weighted by the gear ratio."""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# add default argument
if "asset_cfg" not in cfg.params:
cfg.params["asset_cfg"] = SceneEntityCfg("robot")
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[cfg.params["asset_cfg"].name]
# resolve the gear ratio for each joint
self.gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device)
index_list, _, value_list = string_utils.resolve_matching_names_values(
cfg.params["gear_ratio"], asset.joint_names
)
self.gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device)
self.gear_ratio_scaled = self.gear_ratio / torch.max(self.gear_ratio)
def __call__(
self, env: RLTaskEnv, threshold: float, gear_ratio: dict[str, float], asset_cfg: SceneEntityCfg
) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute the penalty over normalized joints
joint_pos_scaled = math_utils.scale_transform(
asset.data.joint_pos, asset.data.soft_joint_pos_limits[..., 0], asset.data.soft_joint_pos_limits[..., 1]
)
# scale the violation amount by the gear ratio
violation_amount = (torch.abs(joint_pos_scaled) - threshold) / (1 - threshold)
violation_amount = violation_amount * self.gear_ratio_scaled
return torch.sum((torch.abs(joint_pos_scaled) > threshold) * violation_amount, dim=-1)
class power_consumption(ManagerTermBase):
"""Penalty for the power consumed by the actions to the environment.
This is computed as commanded torque times the joint velocity.
"""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# add default argument
if "asset_cfg" not in cfg.params:
cfg.params["asset_cfg"] = SceneEntityCfg("robot")
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[cfg.params["asset_cfg"].name]
# resolve the gear ratio for each joint
self.gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device)
index_list, _, value_list = string_utils.resolve_matching_names_values(
cfg.params["gear_ratio"], asset.joint_names
)
self.gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device)
self.gear_ratio_scaled = self.gear_ratio / torch.max(self.gear_ratio)
def __call__(self, env: RLTaskEnv, gear_ratio: dict[str, float], asset_cfg: SceneEntityCfg) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# return power = torque * velocity (here actions: joint torques)
return torch.sum(torch.abs(env.action_manager.action * asset.data.joint_vel * self.gear_ratio_scaled), dim=-1)
| 6,069 |
Python
| 42.985507 | 118 | 0.66782 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/mdp/observations.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
def base_yaw_roll(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Yaw and roll of the base in the simulation world frame."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# extract euler angles (in world frame)
roll, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w)
# normalize angle to [-pi, pi]
roll = torch.atan2(torch.sin(roll), torch.cos(roll))
yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
return torch.cat((yaw.unsqueeze(-1), roll.unsqueeze(-1)), dim=-1)
def base_up_proj(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Projection of the base up vector onto the world up vector."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute base up vector
base_up_vec = math_utils.quat_rotate(asset.data.root_quat_w, -asset.GRAVITY_VEC_W)
return base_up_vec[:, 2].unsqueeze(-1)
def base_heading_proj(
env: BaseEnv, target_pos: tuple[float, float, float], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Projection of the base forward vector onto the world forward vector."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute desired heading direction
to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w[:, :3]
to_target_pos[:, 2] = 0.0
to_target_dir = math_utils.normalize(to_target_pos)
# compute base forward vector
heading_vec = math_utils.quat_rotate(asset.data.root_quat_w, asset.FORWARD_VEC_B)
# compute dot product between heading and target direction
heading_proj = torch.bmm(heading_vec.view(env.num_envs, 1, 3), to_target_dir.view(env.num_envs, 3, 1))
return heading_proj.view(env.num_envs, 1)
def base_angle_to_target(
env: BaseEnv, target_pos: tuple[float, float, float], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Angle between the base forward vector and the vector to the target."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute desired heading direction
to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w[:, :3]
walk_target_angle = torch.atan2(to_target_pos[:, 1], to_target_pos[:, 0])
# compute base forward vector
_, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w)
# normalize angle to target to [-pi, pi]
angle_to_target = walk_target_angle - yaw
angle_to_target = torch.atan2(torch.sin(angle_to_target), torch.cos(angle_to_target))
return angle_to_target.unsqueeze(-1)
| 3,270 |
Python
| 42.039473 | 109 | 0.705505 |
John-Dillermand/Isaac-Orbit/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/__init__.py
|
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Manipulation environments for fixed-arm robots."""
from .reach import * # noqa
| 207 |
Python
| 22.111109 | 56 | 0.729469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.