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
|
---|---|---|---|---|---|---|
tudelft/autoGDMplus/utils.py | import yaml
import json
import os
import math
import csv
import zlib
from typing import Tuple
import numpy as np
from datetime import datetime
from pathlib import Path
HOME_DIR = Path.home()
main_path = os.path.abspath(__file__)
AutoGDM2_dir = os.path.dirname(main_path)
class GDMConfig:
def __init__(self):
self.HOME_DIR = Path.home()
self.main_path = os.path.abspath(__file__)
self.AutoGDM2_dir = os.path.dirname(main_path)
self.config_dir = f'{self.AutoGDM2_dir}/config/'
self.gdm_settings = {} # dict with all the AutoGDM settings
self.sim_settings = {} # dict with all the Isaac Sim/Pegasus settings
def get_current_yaml(self):
with open(f'{self.config_dir}current.yaml', 'r') as file:
return yaml.safe_load(file)
def get_default_yaml(self):
with open(f'{self.config_dir}default.yaml', 'r') as file:
return yaml.safe_load(file)
def set_directory_params(self, yamldict:dict) -> None:
# directory names
self.gdm_settings["asset_dir"] = yamldict["directories"]["asset_dir"].format(HOME_DIR=self.HOME_DIR)
self.gdm_settings["config_dir"] = yamldict["directories"]["config_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["asset_mockup_dir"] = yamldict["directories"]["asset_mockup_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["asset_custom_dir"] = yamldict["directories"]["asset_custom_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["recipe_dir"] = yamldict["directories"]["recipe_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["usd_scene_dir"] = yamldict["directories"]["usd_scene_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["geometry_dir"] = yamldict["directories"]["geometry_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["cfd_dir"] = yamldict["directories"]["cfd_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["gas_data_dir"] = yamldict["directories"]["gas_data_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["wind_data_dir"] = yamldict["directories"]["wind_data_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["occ_data_dir"] = yamldict["directories"]["occ_data_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["empty_ros_dir"] = yamldict["directories"]["empty_ros_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
self.gdm_settings["gaden_env_dir"] = yamldict["directories"]["gaden_env_dir"].format(AutoGDM2_dir=self.AutoGDM2_dir)
def set_application_params(self, yamldict:dict) -> None:
# applications
self.gdm_settings["ISAAC_VERSION"] = yamldict["software"]["isaac_sim"]["version"]
self.gdm_settings["isaac_dir"] = yamldict["software"]["isaac_sim"]["isaac_dir"].format(HOME_DIR=self.HOME_DIR, ISAAC_VERSION=self.gdm_settings["ISAAC_VERSION"])
self.gdm_settings["wh_gen_dir"] = yamldict["software"]["isaac_sim"]["wh_gen_dir"].format(isaac_dir=self.gdm_settings["isaac_dir"])
self.gdm_settings["BLENDER_VERSION"] = yamldict["software"]["blender"]["version"]
self.gdm_settings["blender_dir"] = yamldict["software"]["blender"]["blender_dir"].format(HOME_DIR=self.HOME_DIR, BLENDER_VERSION=self.gdm_settings["BLENDER_VERSION"])
self.gdm_settings["OPENFOAM_VERSION"] = yamldict["software"]["openfoam"]["version"]
self.gdm_settings["openfoam_dir"] = yamldict["software"]["openfoam"]["openfoam_dir"].format(HOME_DIR=self.HOME_DIR, OPENFOAM_VERSION=self.gdm_settings["OPENFOAM_VERSION"])
def set_environment_params(self, yamldict:dict) -> None:
# environment(s)
self.gdm_settings["env_types"] = yamldict["environment"]["env_types"]
self.gdm_settings["env_type"] = self.gdm_settings["env_types"][yamldict["environment"]["env_type"]]
self.gdm_settings["env_amount"] = yamldict["environment"]["env_amount"]
self.gdm_settings["env_size"] = yamldict["environment"]["env_size"]
self.gdm_settings["env_list"] = [f"{self.gdm_settings['env_type']}_{str(i).zfill(4)}" for i in range(self.gdm_settings['env_amount'])]
# if self.gdm_settings["env_type"] == 'wh_empty' or self.gdm_settings["env_type"] == 'wh_simple':
self.gdm_settings["inlet_size"] = yamldict["env_wh"]["inlet_size"]
self.gdm_settings["inlet_vel"] = yamldict["env_wh"]["inlet_vel"]
self.gdm_settings["outlet_size"] = yamldict["env_wh"]["outlet_size"]
self.gdm_settings["emptyfullrackdiv"] = yamldict["env_wh"]["emptyfullrackdiv"]
self.gdm_settings["white_walls"] = yamldict["env_wh"]["white_walls"]
def set_cfd_params(self,yamldict:dict) -> None:
# cfd mesh settings
self.gdm_settings["cfd_mesh_settings"] = {
"minCellSize": yamldict["cfd"]["mesh"]["minCellSize"],
"maxCellSize": yamldict["cfd"]["mesh"]["maxCellSize"],
"boundaryCellSize": yamldict["cfd"]["mesh"]["boundaryCellSize"],
"localRefinement": yamldict["cfd"]["mesh"]["localRefinement"],
}
# threads used for solving
if yamldict["cfd"]["solving"]["threads"] == 0:
threads = len(os.sched_getaffinity(0)) - 2
else:
threads = yamldict["cfd"]["solving"]["threads"]
# relevant cfd solver settings
cfd_k = round(1.5 * (0.05 * math.hypot(self.gdm_settings["inlet_vel"][0],self.gdm_settings["inlet_vel"][1],self.gdm_settings["inlet_vel"][2]))**2,6) # turbulent kinetic energy
cfd_epsilon = round((0.09**0.75 * cfd_k**1.5)/(0.1*self.gdm_settings["inlet_size"][0]),6) # dissipation rate
self.gdm_settings["cfd_settings"] = {
"threads": threads,
"endTime": yamldict["cfd"]["solving"]["endTime"],
"writeInterval": yamldict["cfd"]["solving"]["writeInterval"],
"maxCo": yamldict["cfd"]["solving"]["maxCo"],
"maxDeltaT": yamldict["cfd"]["solving"]["maxDeltaT"],
"nOuterCorrectors": yamldict["cfd"]["solving"]["nOuterCorrectors"],
"k": cfd_k,
"epsilon": cfd_epsilon,
"latestTime": yamldict["cfd"]["solving"]["latestTime"],
"timeRange": yamldict["cfd"]["solving"]["timeRange"]
}
def set_gas_dispersal_params(self, yamldict:dict) -> None:
# gas dispersal settings
self.gdm_settings["src_placement_types"] = yamldict["gas_dispersal"]["src_placement_types"]
self.gdm_settings["src_placement_type"] = self.gdm_settings["src_placement_types"][yamldict["gas_dispersal"]["src_placement_type"]]
self.gdm_settings["src_placement"] = yamldict["gas_dispersal"]["src_placement"] # TODO: add if statement for random settings
self.gdm_settings["gas_type"] = yamldict["gas_dispersal"]["gas_type"]
self.gdm_settings["sim_time"] = yamldict["gas_dispersal"]["sim_time"]
self.gdm_settings["time_step"] = yamldict["gas_dispersal"]["time_step"]
self.gdm_settings["wind_looping"] = yamldict["gas_dispersal"]["wind_looping"]
self.gdm_settings["wind_start_step"] = yamldict["gas_dispersal"]["wind_start_step"]
self.gdm_settings["wind_stop_step"] = yamldict["gas_dispersal"]["wind_stop_step"]
def set_asset_params(self, yamldict: dict) -> None:
# assets
assets = yamldict["assets"]
# 'repair' the 'f-strings'
assets["empty_racks"] = assets["empty_racks"].format(asset_dir=self.gdm_settings["asset_dir"])
assets["filled_racks"] = assets["filled_racks"].format(asset_dir=self.gdm_settings["asset_dir"])
assets["piles"] = assets["piles"].format(asset_dir=self.gdm_settings["asset_dir"])
assets["railings"] = assets["railings"].format(asset_dir=self.gdm_settings["asset_dir"])
assets["isaac_wh_props"] = assets["isaac_wh_props"].format(HOME_DIR=self.HOME_DIR)
assets["isaac_custom"] = assets["isaac_custom"].format(asset_custom_dir=self.gdm_settings["asset_custom_dir"])
assets["forklift"] = assets["forklift_asset"].format(HOME_DIR=self.HOME_DIR)
assets["empty_racks_mockup"] = assets["empty_racks_mockup"].format(asset_mockup_dir=self.gdm_settings["asset_mockup_dir"])
assets["filled_racks_mockup"] = assets["filled_racks_mockup"].format(asset_mockup_dir=self.gdm_settings["asset_mockup_dir"])
assets["forklift_mockup"] = assets["forklift_mockup"].format(asset_mockup_dir=self.gdm_settings["asset_mockup_dir"])
assets["piles_mockup"] = assets["piles_mockup"].format(asset_mockup_dir=self.gdm_settings["asset_mockup_dir"])
self.gdm_settings["assets"] = assets
# pairs of filelocations of assets and their corresponding mockups
self.gdm_settings["file_loc_paired"] = {
"filled_racks": [[assets["filled_racks"] + assets["filled_racks_long_asset"][0], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][1], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][2], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][3], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][4], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][5], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]],
[assets["filled_racks"] + assets["filled_racks_long_asset"][6], assets["filled_racks_mockup"] + assets["filled_racks_long_asset_mockup"]]],
"empty_racks": [[assets["empty_racks"] + assets["empty_racks_long_asset"][0], assets["empty_racks_mockup"] + assets["empty_racks_long_asset_mockup"][0]],
[assets["empty_racks"] + assets["empty_racks_long_asset"][1], assets["empty_racks_mockup"] + assets["empty_racks_long_asset_mockup"][1]]],
"piles": [[assets["piles"] + assets["piles_asset"][3], assets["piles_mockup"] + assets["piles_asset_mockup"][0]], # WarehousePile_A4
[assets["piles"] + assets["piles_asset"][4], assets["piles_mockup"] + assets["piles_asset_mockup"][1]], # WarehousePile_A5
[assets["piles"] + assets["piles_asset"][6], assets["piles_mockup"] + assets["piles_asset_mockup"][2]]], # WarehousePile_A7
"floors": [[assets["isaac_wh_props"] + assets["floor"], None]],
"walls": [[assets["isaac_wh_props"] + assets["walls"][0], None],
[assets["isaac_wh_props"] + assets["walls"][1], None],
[assets["isaac_wh_props"] + assets["walls"][2], None],
[assets["isaac_wh_props"] + assets["walls"][3], None],],
"lights": [[assets["isaac_wh_props"] + assets["lights"][0], None],
[assets["isaac_custom"] + assets["lights"][1], None]],
"forklift": [[assets["forklift"], assets["forklift_mockup"] + assets["forklift_asset_mockup"]]],
}
def pretty(self, conf:dict) -> str:
return json.dumps(conf, indent=2)
def save_gdm_settings(self, comment:str='') -> None:
if comment:
filename = f'{datetime.now().strftime("%Y-%m-%d")}_{datetime.now().strftime("%H:%M:%S")}_{comment}'
else:
filename = f'{datetime.now().strftime("%Y-%m-%d")}_{datetime.now().strftime("%H:%M:%S")}'
with open(f'{self.config_dir}{filename}.yaml', 'w') as file:
yaml.dump(self.gdm_settings, file)
file.close()
def set_gdm_params(self, yamldict:dict) -> None:
self.set_directory_params(yamldict)
self.set_application_params(yamldict)
self.set_environment_params(yamldict)
self.set_cfd_params(yamldict)
self.set_gas_dispersal_params(yamldict)
self.set_asset_params(yamldict)
def current_gdm_settings(self) -> dict:
yamldict = self.get_current_yaml()
self.set_gdm_params(yamldict)
self.save_gdm_settings(yamldict["comment"])
return self.gdm_settings
def default_gdm_settings(self) -> dict:
yamldict = self.get_default_yaml()
self.set_gdm_params(yamldict)
self.save_gdm_settings(yamldict["comment"])
return self.gdm_settings
# TODO improve this implementation
# simple ( probably unnecessary ) class to store a timestep ()
class flow_field:
def __init__(self,id):
self.id = id
def is_float(element:any) -> bool:
#If you expect None to be passed:
if element is None:
return False
try:
float(element)
return True
except ValueError:
return False
# reads compressed gas data
def read_gas_data(file_path) -> Tuple[np.ndarray,np.ndarray]:
with open(file_path, 'rb') as file:
compressed_data = file.read()
# first decompress the file
decompressed_data = zlib.decompress(compressed_data)
# header datatype
header_dtype = np.dtype([('h', np.uint32),
('env_min_x', np.float64),
('env_min_y', np.float64),
('env_min_z', np.float64),
('env_max_x', np.float64),
('env_max_y', np.float64),
('env_max_z', np.float64),
('env_cells_x', np.uint32),
('env_cells_y', np.uint32),
('env_cells_z', np.uint32),
('cell_size_x', np.float64),
('cell_size_y', np.float64),
('cell_size_z', np.float64),
('gas_source_pos_x', np.float64),
('gas_source_pos_y', np.float64),
('gas_source_pos_z', np.float64),
('gas_type', np.uint32),
('filament_num_moles_of_gas', np.float64),
('num_moles_all_gases_in_cm3', np.float64),
('binary_bool', np.uint32)])
# filament datatype
filament_dtype = np.dtype([('id', np.uint32),
('pose_x', np.float64),
('pose_y', np.float64),
('pose_z', np.float64),
('sigma', np.float64)])
# TODO - combine all gas iterations into one array for a potential speed increase
# read data from buffer
filament_header = np.frombuffer(decompressed_data, dtype=header_dtype, count=1)
filament_data = np.frombuffer(decompressed_data, dtype=filament_dtype,
offset=header_dtype.itemsize)
# return the extracted data
return filament_header, filament_data
def read_wind_data(file_paths) -> np.ndarray:
windfields_lst = []
# read files and put into list
for file_path in file_paths:
with open(file_path, 'rb') as file:
data = file.read()
UVW = np.split(np.frombuffer(data, dtype=np.float64), 3)
wind_vectors = np.zeros((np.shape(UVW)[1],3))
wind_vectors[:,0] = UVW[0]
wind_vectors[:,1] = UVW[1]
wind_vectors[:,2] = UVW[2]
windfields_lst.append(wind_vectors)
windfields_arr = np.zeros((len(file_paths), np.shape(windfields_lst[0])[0], 3))
# puts lists into one array
for i, windfield in enumerate(windfields_lst):
windfields_arr[i] = windfield
# return the extracted data
return windfields_arr
def read_occ_csv(filepath) -> Tuple[dict,np.ndarray]:
header = {}
with open(filepath, 'r') as csv_file:
csv_lst = list(csv.reader(csv_file))
# extract header info
header['env_min'] = [float(j) for j in csv_lst[0][0].split(" ")[1:]]
header['env_max'] = [float(j) for j in csv_lst[1][0].split(" ")[1:]]
header['num_cells'] = [int(j) for j in csv_lst[2][0].split(" ")[1:]]
header['cell_size'] = float(csv_lst[3][0].split(" ")[1:][0])
occ_arr = np.zeros((header['num_cells'][2],
header['num_cells'][0],
header['num_cells'][1]), dtype=int)
for z_it in range(header['num_cells'][2]):
x_it = 0
while True:
row = csv_lst[(4 + z_it*(header['num_cells'][0]+1)) + x_it][0]
if row == ';':
break
occ_arr[z_it,x_it,:] = [int(j) for j in row.split(" ")[:-1]]
x_it += 1
return header, occ_arr
| 17,448 | Python | 51.875757 | 185 | 0.579207 |
tudelft/autoGDMplus/layout_gen.py | # Top level layout generator following the Isaac Sim Warehouse generator format
import json
import random
import numpy as np
from typing import Tuple
# TODO: remove member functions such as dx(), dy(), etc. and change them to attributes
class Asset:
def __init__(self,
assetname:str = "Asset",
fname:list = [None, None], # [isaac_sim_asset, mockup_file]
dims:np.ndarray = np.zeros(3),
loc:np.ndarray = np.zeros(3),
ori:np.ndarray = np.zeros(3),
scale:np.ndarray = np.ones(3)
) -> None:
self.id = assetname
self.fname = fname # [isaac_sim_asset, mockup_file]
self.dims = dims
self.ctr = 0.5*dims
self.loc = loc
self.ori = ori
self.scale = scale
def assetname(self) -> str:
return self.id
def set_assetname(self, assetname:str) -> None:
self.id = assetname
return
def set_fname(self, fname:list) -> None:
self.fname = fname
return
def dimensions(self) -> np.ndarray:
return self.dims
def set_dimensions(self, dims:np.ndarray=np.zeros(3)) -> None:
self.dims = dims
return
def dx(self) -> float:
return self.dims[0]
def dy(self) -> float:
return self.dims[1]
def dz(self) -> float:
return self.dims[2]
def center(self) -> np.ndarray:
return self.ctr
def cx(self) -> float:
return self.ctr[0]
def cy(self) -> float:
return self.ctr[1]
def cz(self) -> float:
return self.ctr[2]
def location(self) -> np.ndarray:
return self.loc
def lx(self) -> float:
return self.loc[0]
def ly(self) -> float:
return self.loc[1]
def lz(self) -> float:
return self.loc[2]
def set_location(self, loc:np.ndarray) -> None:
self.loc = loc
return
def translate(self, axis:str, amount:float) -> None:
if axis == 'X':
self.loc[0] = amount
if axis == 'Y':
self.loc[1] = amount
if axis == 'Z':
self.loc[2] = amount
def set_orientation(self, ori:np.ndarray) -> None:
self.ori = ori
return
def set_scale(self, scale:np.ndarray) -> None:
self.scale = scale
return
def get_dict(self) -> dict:
assetdict = {
"asset_id": self.id,
"filename": self.fname[0],
"mockup_file": self.fname[1],
"dimensions": self.dims.tolist(),
"location": self.loc.tolist(),
"orientation": self.ori.tolist(),
"scale": self.scale.tolist()
}
return assetdict
class Warehouse:
def __init__(self,
settings:dict,
wh_dims:np.ndarray = np.array([10.0, 15.0, 9.0]),
inlet_dims:np.ndarray = np.array([0.0,4.0,4.0]),
outlet_dims:np.ndarray = np.array([0.0,4.0,4.0])):
self.settings = settings
self.warehouse = Asset("warehouse_shell", dims=wh_dims)
self.floor = Asset("floor", fname=self.settings['file_loc_paired']["floors"][0], dims=np.array([6.0, 6.0, 0.0]))
self.cornerwall = Asset("cornerwall", dims=np.array([3.0,3.0,3.0]))
self.wall = Asset("wall", dims=np.array([0.0,6.0,3.0]))
self.prop_light = Asset("prop_light", dims=np.array([2.0, 0.3, 3.0]))
self.rect_light = Asset("rect_light", dims=np.array([self.warehouse.dx(), self.warehouse.dy(), 0.0]))
self.rack = Asset("rack", dims=np.array([1.0, 4.0, 3.0])) # default size of rack models
self.rack_aisle = Asset("rack_aisle", dims=np.array([3.0, 0.0, 0.0]))
self.end_aisle = Asset("end_aisle", dims=np.array([0.0, (max(inlet_dims[1], outlet_dims[1]) + 2), 0.0]))
self.forklift = Asset("forklift", fname=self.settings['file_loc_paired']['forklift'][0], dims=np.array([0.8,1.0,2.0]))
self.pile = Asset("pile")
self.inlet = Asset("inlet", dims=inlet_dims)
self.outlet = Asset("outlet", dims=outlet_dims)
# returns arrays of rack positions (centered for each rack)
def rack_positions(self) -> np.ndarray:
rack_orig = np.array([self.rack.cx(), self.rack.cy() + self.end_aisle.dy(), 0.0]) # origin of rack array
rack_rows = int(1 + (self.warehouse.dx()-self.rack.dx()) // (self.rack.dx() + self.rack_aisle.dx()))
rack_segs = int((self.warehouse.dy() - (2 * self.end_aisle.dy())) // self.rack.dy())
rack_stack= int((self.warehouse.dz()) // self.rack.dz()) # height
nx, ny, nz = rack_rows, rack_segs, rack_stack
x = np.linspace(rack_orig[0], self.warehouse.dx() - 0.5 * self.rack.dx(), nx)
y = np.linspace(rack_orig[1], rack_orig[1] + (self.rack.dy() * (ny-1)), ny)
z = np.arange(rack_orig[2], self.rack.dz() * nz, self.rack.dz())
xv, yv, zv = np.meshgrid(x,y,z) # generate grid and reshape array for ease of use
stack = np.stack([xv, yv, zv], -1)
positions = stack.reshape(np.prod(stack.shape[0:-1]),3)
return positions
# divides positions, affects empty/filled rack ratio
def position_division(self, divisor:float ,positions:np.ndarray=np.zeros(3)) -> np.ndarray:
totalSample = positions.shape[0]
minSample = int((totalSample//(divisor**-1)))
sampleSize = np.random.randint(minSample,totalSample)
idx = random.sample(range(totalSample),sampleSize)
filledRackPos, emptyRackPos = positions[idx,:], np.delete(positions, idx, 0)
return filledRackPos, emptyRackPos
# TODO - hardcoded for now, make scalable
def complex_positions(self) -> np.ndarray:
edge_dist = 2.0
x = np.linspace(edge_dist, (15-edge_dist), 4)
y = np.linspace(1.5, (15-1.5), 4)
positions = np.array([[x[0], y[0], 0.0],
[x[0], y[1], 0.0],
[x[0], y[2], 0.0],
[x[0], y[3], 0.0],
[x[1], y[3], 0.0],
[x[2], y[3], 0.0],
[x[3], y[3], 0.0],
[x[3], y[2], 0.0],
[x[3], y[1], 0.0],
[x[3], y[0], 0.0],
[x[2], y[0], 0.0],
[x[1], y[0], 0.0]])
return positions
# interior dict generation
def interior_gen(self, filled:np.ndarray, empty:np.ndarray, comp_loc:np.ndarray=None) -> list:
interior_dicts = []
scale_factor = np.array([0.01, 0.01, 0.01]) # custom scaling factor
# filled racks
for i,loc in enumerate(filled):
self.rack.set_assetname(f"filled_rack_{str(i).zfill(3)}")
self.rack.set_fname(random.choice(self.settings['file_loc_paired']["filled_racks"])) # choose random type of rack and corresponding mockup
self.rack.set_orientation(np.zeros(3,))
self.rack.set_location(loc)
self.rack.set_scale(scale_factor)
if comp_loc is not None and loc[0] > 1.0 and loc[0] < 14.0: # TODO : remove hardcoded orientation
self.rack.set_orientation(np.array([0,0,90]))
interior_dicts.append(self.rack.get_dict())
# empty racks
for i,loc in enumerate(empty):
self.rack.set_assetname(f"empty_rack_{str(i).zfill(3)}")
self.rack.set_fname(random.choice(self.settings['file_loc_paired']["empty_racks"])) # choose random type of rack and corresponding mockup
self.rack.set_orientation(np.zeros(3,))
self.rack.set_location(loc)
self.rack.set_scale(scale_factor)
if comp_loc is not None and loc[0] > 1.0 and loc[0] < 14.0: # TODO : remove hardcoded orientation
self.rack.set_orientation(np.array([0,0,90]))
interior_dicts.append(self.rack.get_dict())
if comp_loc is not None:
# get 4 random indices
idx = np.random.choice(11, 6, replace=False)
forklift_idx = idx[0]
piles_idx = idx[1:]
# add forklift to dict
self.forklift.set_location(comp_loc[forklift_idx])
self.forklift.set_orientation(np.array([0.0,0.0,np.random.randint(0,359)]))
self.forklift.set_scale(scale_factor)
interior_dicts.append(self.forklift.get_dict())
# add piles to dict
for i,loc in enumerate(comp_loc[piles_idx]):
self.pile.set_assetname(f"pile_{str(i).zfill(3)}")
self.pile.set_fname(random.choice(self.settings['file_loc_paired']["piles"])) # choose random type of pile and corresponding mockup
self.pile.set_location(loc)
self.pile.set_orientation(np.array([0.0,0.0,np.random.randint(0,359)]))
self.pile.set_scale(scale_factor)
interior_dicts.append(self.pile.get_dict())
return interior_dicts
################
### CFD MESH ###
################
# The CFD mesh is generated using assets that blender can place and save to .stl
# sides dict generation, these are all planes
def sides_blender(self) -> list:
side_dicts = []
# bottom
bottom = Asset("bottom",dims=np.array([self.warehouse.dx(), self.warehouse.dy(), 0.0]),
loc=0.5*np.array([self.warehouse.dx(), self.warehouse.dy(), 0]))
side_dicts.append(bottom.get_dict())
# top
top = Asset("top",dims=np.array([self.warehouse.dx(), self.warehouse.dy(), 0.0]),
loc=np.array([0.5*self.warehouse.dx(),0.5*self.warehouse.dy(), self.warehouse.dz()]),
ori=np.array([180,0,0])) # important for the face normals to point inside
side_dicts.append(top.get_dict())
# front
front = Asset("front",dims=np.array([self.warehouse.dx(), self.warehouse.dz(), 0.0]),
loc=np.array([0.5*self.warehouse.dx(),0,0.5*self.warehouse.dz()]),
ori=np.array([-90,0,0]))
side_dicts.append(front.get_dict())
# back
back = Asset("back",dims=np.array([self.warehouse.dx(), self.warehouse.dz(), 0.0]),
loc=np.array([0.5*self.warehouse.dx(),self.warehouse.dy(),0.5*self.warehouse.dz()]),
ori=np.array([90,0,0]))
side_dicts.append(back.get_dict())
# inlet side
side1 = Asset("side_001",dims=np.array([self.warehouse.dz(), self.warehouse.dy()-self.inlet.dy(), 0.0]),
loc=np.array([0.0, 0.5*(self.warehouse.dy()+self.inlet.dy()), 0.5*self.warehouse.dz()]),
ori=np.array([0,90,0]))
side_dicts.append(side1.get_dict())
side2 = Asset("side_002",dims=np.array([self.warehouse.dz()-self.inlet.dz(), self.inlet.dy(), 0.0]),
loc=np.array([0.0, 0.5*self.inlet.dy(), 0.5*(self.warehouse.dz()+self.inlet.dz())]),
ori=np.array([0,90,0]))
side_dicts.append(side2.get_dict())
# oulet side
side3 = Asset("side_003",dims=np.array([self.warehouse.dz(), self.warehouse.dy()-self.outlet.dy(), 0.0]),
loc=np.array([self.warehouse.dx(), 0.5*(self.warehouse.dy()-self.outlet.dy()), 0.5*self.warehouse.dz()]),
ori=np.array([0,-90,0]))
side_dicts.append(side3.get_dict())
side4 = Asset("side_004",dims=np.array([self.warehouse.dz()-self.outlet.dz(), self.outlet.dy(), 0.0]),
loc=np.array([self.warehouse.dx(), self.warehouse.dy()-0.5*self.outlet.dy(), 0.5*(self.warehouse.dz()+self.outlet.dz())]),
ori=np.array([0,-90,0]))
side_dicts.append(side4.get_dict())
return side_dicts
def inlets_blender(self) -> list:
inlet_dicts = []
inlet = Asset("inlet001",dims=np.array([self.inlet.dz(), self.inlet.dy(), 0.0]),
loc=np.array([0.0, 0.5*self.inlet.dy(), 0.5*self.inlet.dz()]),
ori=np.array([0,90,0]))
inlet_dicts.append(inlet.get_dict())
return inlet_dicts
def outlets_blender(self) -> list:
outlet_dicts = []
outlet = Asset("outlet001",dims=np.array([self.outlet.dz(), self.outlet.dy(), 0.0]),
loc=np.array([self.warehouse.dx(), self.warehouse.dy()-0.5*self.outlet.dy(), 0.5*self.outlet.dz()]),
ori=np.array([0,-90,0]))
outlet_dicts.append(outlet.get_dict())
return outlet_dicts
################
### GADEN ###
################
# gaden requires additional geometry with thickness such as the walls, inlet and outlets
# for this, blender will need to perform boolean operations
# first all geometry is given. lastly, a separate dict entry is used for the boolean operations
def gaden_geom(self) -> Tuple[list,list]:
gaden_geom_dicts = []
gaden_bools = []
wallthickness = 0.2
walls = Asset("walls", dims=np.array([self.warehouse.dx()+2*wallthickness, self.warehouse.dy()+2*wallthickness, self.warehouse.dz()]),
loc=self.warehouse.center())
gaden_geom_dicts.append(walls.get_dict())
inside = Asset("inside", dims=np.array([self.warehouse.dx(),self.warehouse.dy(),self.warehouse.dz()+1.0]),
loc=self.warehouse.center())
gaden_geom_dicts.append(inside.get_dict())
inlet = Asset("inlet", dims=np.array([wallthickness+0.2, self.inlet.dy(), self.inlet.dz()]),
loc=np.array([-0.5*wallthickness, 0.5*self.inlet.dy(), 0.5*self.inlet.dz()]))
gaden_geom_dicts.append(inlet.get_dict())
outlet = Asset("outlet", dims=np.array([wallthickness+0.2, self.outlet.dy(), self.outlet.dz()]),
loc=np.array([self.warehouse.dx()+ 0.5*wallthickness, self.warehouse.dy()-0.5*self.outlet.dy(), 0.5*self.outlet.dz()]))
gaden_geom_dicts.append(outlet.get_dict())
for asset in [inside, inlet, outlet]:
gaden_bools.append([walls.get_dict(), asset.get_dict(), 'DIFFERENCE'])
return gaden_geom_dicts, gaden_bools
################
### ISAAC ###
################
def isaac_floor_dicts(self) -> list:
floor_orig = np.array([self.floor.cx(), self.floor.cy(), 0.0]) # origin of floor array
floor_rows = int(np.ceil(self.warehouse.dx()/self.floor.dx())) # floor tile rows (round up)
floor_cols = int(np.ceil(self.warehouse.dy()/self.floor.dy())) # floor tile columns (round up)
nx, ny = floor_rows, floor_cols
x = np.linspace(floor_orig[0], floor_orig[0] + self.floor.dx()*(nx-1), nx)
y = np.linspace(floor_orig[1], floor_orig[1] + self.floor.dy()*(ny-1), ny)
xv, yv = np.meshgrid(x,y) # generate grid and reshape array for ease of use
zv = np.zeros_like(xv)
stack = np.stack([xv, yv, zv], -1)
positions = stack.reshape(np.prod(stack.shape[0:-1]),3)
floor_tile_dicts = []
for i,loc in enumerate(positions):
self.floor.set_assetname(f"floor_tile_{str(i).zfill(3)}")
self.floor.set_location(loc)
floor_tile_dicts.append(self.floor.get_dict())
return floor_tile_dicts
def isaac_walls_dicts(self) -> list:
walls_dicts = []
# walls are made higher than env size to accomodate the lighting
ceiling_height = self.warehouse.dz() + self.prop_light.dz()
# corners
nz = int(np.ceil(ceiling_height/self.cornerwall.dz()))
z = np.linspace(0.0, self.wall.dz() * (nz-1), nz)
z[-1] = ceiling_height - self.cornerwall.dz()
if self.settings["white_walls"]:
walltypes = np.zeros(nz, dtype=int) # white walls only
else:
walltypes = np.ones(nz, dtype=int) # default white and yellow walls
walltypes[0] = 0
x = np.linspace(0.0, self.warehouse.dx(), 2)
y = np.linspace(0.0, self.warehouse.dy(), 2)
ori = np.array([[90., 180., 0., 270.]])
xv, yv = np.meshgrid(x,y)
stack = np.stack([xv, yv], -1)
positions = stack.reshape((4,2))
transforms = np.hstack((positions, ori.T)) # [X Y Z-rotation]
for i, (z_pos, walltype) in enumerate(zip(z, walltypes)):
for j,transform in enumerate(transforms):
self.cornerwall.set_assetname(f"wall_corner_{i}_{j}")
self.cornerwall.set_fname(self.settings['file_loc_paired']["walls"][walltype])
self.cornerwall.set_location(np.array([transform[0], transform[1], z_pos]))
self.cornerwall.set_orientation(np.array([0.0,0.0,transform[2]]))
walls_dicts.append(self.cornerwall.get_dict())
# flat walls
nz = int(np.ceil(ceiling_height/self.wall.dz()))
z = np.linspace(0.0, self.wall.dz() * (nz-1), nz)
z[-1] = ceiling_height - self.wall.dz()
if self.settings["white_walls"]:
walltypes = np.zeros(nz, dtype=int) # white walls only
else:
walltypes = np.ones(nz, dtype=int) # default white and yellow walls
walltypes[0] = 0
# check if additional walls are needed for x direction
if self.warehouse.dx() > (2 * self.cornerwall.dx()):
# walls in x-dir
nx = int(np.ceil((self.warehouse.dx()-(2*self.cornerwall.dx()))/self.wall.dy()))
x = np.linspace(self.cornerwall.dx() + self.wall.cy(), self.warehouse.dx() - (self.cornerwall.dx() + self.wall.cy()), nx)
y = np.linspace(0.0, self.warehouse.dy(), 2)
ori = np.linspace(90.0, -90.0, 2)
for i, (z_pos, walltype) in enumerate(zip(z, walltypes)):
for j, (y_pos, orientation) in enumerate(zip(y, ori)):
for k, x_pos in enumerate(x):
self.wall.set_assetname(f"wallX_{i}_{k}_{j}")
self.wall.set_fname(self.settings['file_loc_paired']["walls"][2+walltype])
self.wall.set_location(np.array([x_pos, y_pos, z_pos]))
self.wall.set_orientation(np.array([0.0, 0.0, orientation]))
walls_dicts.append(self.wall.get_dict())
# check if additional walls are needed for y direction
if self.warehouse.dy() > (2 * self.cornerwall.dy()):
# walls in y-dir
ny = int(np.ceil((self.warehouse.dy()-(2*self.cornerwall.dy()))/self.wall.dy()))
y = np.linspace(self.cornerwall.dy() + self.wall.cy(), self.warehouse.dy() - (self.cornerwall.dy() + self.wall.cy()), ny)
x = np.linspace(0.0, self.warehouse.dx(), 2)
ori = np.linspace(0.0, 180, 2)
for i, (z_pos, walltype) in enumerate(zip(z, walltypes)):
for j, (x_pos, orientation) in enumerate(zip(x, ori)):
for k, y_pos in enumerate(y):
self.wall.set_assetname(f"wallY_{i}_{k}_{j}")
self.wall.set_fname(self.settings['file_loc_paired']["walls"][2+walltype])
self.wall.set_location(np.array([x_pos, y_pos, z_pos]))
self.wall.set_orientation(np.array([0.0, 0.0, orientation]))
walls_dicts.append(self.wall.get_dict())
return walls_dicts
def isaac_lights_dicts(self) -> list:
prop_lights_dicts = []
# rect_lights_dicts = []
z_rect_light = self.warehouse.dz()
z_lights = z_rect_light + self.prop_light.dz()
spacing_xy = [2.5, 4.0]
# decorative (prop) lights
nx = int(np.ceil(((self.warehouse.dx()-(2*spacing_xy[0]))/spacing_xy[0])))
ny = int(np.ceil(((self.warehouse.dy()-(2*spacing_xy[1]))/spacing_xy[1])))
x = np.linspace(spacing_xy[0], self.warehouse.dx()-spacing_xy[0], nx)
y = np.linspace(spacing_xy[1], self.warehouse.dy()-spacing_xy[1], ny)
xv, yv = np.meshgrid(x,y) # generate grid and reshape array for ease of use
zv = z_lights * np.ones_like(xv)
stack = np.stack([xv, yv, zv], -1)
positions = stack.reshape(np.prod(stack.shape[0:-1]),3)
for i, pos in enumerate(positions):
self.prop_light.set_assetname(f"light_{str(i).zfill(3)}")
self.prop_light.set_fname(self.settings['file_loc_paired']["lights"][1])
self.prop_light.set_location(np.array([pos[0], pos[1], pos[2]]))
self.prop_light.set_orientation(np.array([0.0,0.0,90.0]))
prop_lights_dicts.append(self.prop_light.get_dict())
# rectangular light over the whole scene TODO: Add temperature and intensity?
# self.rect_light.set_location(np.array([self.warehouse.cx(), self.warehouse.cy(), z_rect_light]))
# self.rect_light.set_scale(self.rect_light.dimensions())
# rect_lights_dicts.append(self.rect_light.get_dict())
return prop_lights_dicts #, rect_lights_dicts
def generate_recipes(settings:dict) -> None:
recipe_dict = {}
if 'wh' in settings["env_type"]:
recipe_dict["env_type"] = settings["env_type"]
recipe_dict["env_size"] = settings["env_size"]
recipe_dict["inlet_size"] = settings["inlet_size"]
recipe_dict["oulet_size"] = settings["outlet_size"]
for i in range(settings["env_amount"]):
env_id = str(i).zfill(4)
recipe_dict["env_id"] = env_id
wh = Warehouse(settings,
wh_dims=np.array([recipe_dict["env_size"][0], recipe_dict["env_size"][1], recipe_dict["env_size"][2]]),
inlet_dims=np.array([0.0,recipe_dict["inlet_size"][0],recipe_dict["inlet_size"][1]]),
outlet_dims=np.array([0.0,recipe_dict["inlet_size"][0],recipe_dict["inlet_size"][1]]))
# CFD mesh geometry
recipe_dict["sides"] = wh.sides_blender()
recipe_dict["inlets"] = wh.inlets_blender()
recipe_dict["outlets"] = wh.outlets_blender()
# CFD mesh and Isaac Sim interior geometry
if 'empty' in settings["env_type"]:
recipe_dict["interior"] = {}
else:
positions = wh.rack_positions()
filled_locs, empty_locs = wh.position_division(settings["emptyfullrackdiv"],positions)
if 'complex' in settings["env_type"]:
complex_pos = wh.complex_positions()
else:
complex_pos = None
recipe_dict["interior"] = wh.interior_gen(filled_locs, empty_locs, comp_loc=complex_pos)
# GADEN geometry
recipe_dict["gaden_geom"], recipe_dict["gaden_bools"] = wh.gaden_geom()
# Isaac Sim geometry
recipe_dict["isaac_floor"] = wh.isaac_floor_dicts()
recipe_dict["isaac_walls"] = wh.isaac_walls_dicts()
recipe_dict["isaac_lights"] = wh.isaac_lights_dicts()
# write dictionary
with open(f'{settings["recipe_dir"]}{settings["env_type"]}_{env_id}.txt', 'w') as convert_file:
convert_file.write(json.dumps(recipe_dict))
# TODO: create more environments
| 23,600 | Python | 43.530189 | 150 | 0.54822 |
tudelft/autoGDMplus/settings.py | import os
from pathlib import Path
import math
HOME_DIR = Path.home()
settings_path = os.path.abspath(__file__)
AutoGDM2_dir = os.path.dirname(settings_path)
# directory locations
asset_dir = f"{HOME_DIR}/Omniverse_content/ov-industrial3dpack-01-100.1.1/" # omniverse content folder
asset_mockup_dir = f"{AutoGDM2_dir}/assets/mockup/" # mockup folder with simple versions of assets
recipe_dir = f"{AutoGDM2_dir}/environments/recipes/" # recipe folder
usd_scene_dir = f"{AutoGDM2_dir}/environments/isaac_sim/" # isaac sim scenes location
geometry_dir = f"{AutoGDM2_dir}/environments/geometry/"# geometry folder
cfd_dir = f"{AutoGDM2_dir}/environments/cfd/" # cfd folder
gas_data_dir = f"{AutoGDM2_dir}/environments/gas_data/"# gas data folder
empty_ros_dir = f"{AutoGDM2_dir}/environments/ROS/empty_project/"
gaden_env_dir = f"{AutoGDM2_dir}/gaden_ws/src/gaden/envs/" # ROS GADEN workspace
# software locations
# omniverse assets and Isaac Sim
ISAAC_VERSION = '2022.2.0'
isaac_dir = f"{HOME_DIR}/.local/share/ov/pkg/isaac_sim-{ISAAC_VERSION}"
wh_gen_dir = f"{isaac_dir}/exts/omni.isaac.examples/omni/isaac/examples/warehouse_gen"
# blender
BLENDER_VERSION = '3.5.0'
blender_dir = f"{HOME_DIR}/Downloads/blender-{BLENDER_VERSION}-linux-x64"
# openfoam
OPENFOAM_VERSION = 'v2212'
openfoam_dir = f"{HOME_DIR}/OpenFOAM/OpenFOAM-{OPENFOAM_VERSION}"
# environment related settings
env_types = ['wh_simple', 'wh_complex']
env_type = env_types[0]
env_amount = 2
env_size = [10.0, 16.0, 8.0] # [X Y Z]
if env_type == 'wh_simple':
inlet_size = [1.2,2.4] # [Y,Z], [m]
inlet_vel = [1.0, 0.0, 0.0] # [X, Y,Z], [m/s]
outlet_size = [1.5,2.4] # [Y,Z], [m]
emptyfullrackdiv = 0.5 # least percentage of filled racks
# relevant CDF meshing settings
cfd_mesh_settings = {
"minCellSize": 0.10, # it is recommended to keep these values uniform
"maxCellSize": 0.10, # for easy of meshing, cfd calculation and mesh quality
"boundaryCellSize": 0.10,
"localRefinement": 0.0, # set to 0.0 to leave inactive
}
# relevant CFD settings
cfd_k = round(1.5 * (0.05 * math.hypot(inlet_vel[0],inlet_vel[1],inlet_vel[2]))**2,6) # turbulent kinetic energy
cfd_epsilon = round((0.09**0.75 * cfd_k**1.5)/(0.1*inlet_size[0]),6) # dissipation rate
cfd_settings = {
"threads": len(os.sched_getaffinity(0)) - 2, # available threads for CFD is total-2 for best performance
"endTime": 1.0,
"writeInterval": 1.0,
"maxCo": 2.0,
"maxDeltaT": 0.0, # set to 0.0 to leave inactive
"k": cfd_k,
"epsilon": cfd_epsilon,
}
# gas dispersal settings
src_placement_types = ['random', 'specific'] # TODO implement types
src_placement = src_placement_types[0]
src_height = 2.0 # [m]
# TODO improve this implementation
# simple ( probably unnecessary ) class to store a timestep ()
class flow_field:
def __init__(self,id):
self.id = id
# max_num_tries = 3
# z_min = 0
#z_max = env_size_x
# asset file-locations
filenames = {
############################# OMNIVERSE ASSETS #############################
# Then, we point to asset paths, to pick one at random and spawn at specific positions
"empty_racks": f"{asset_dir}Shelves/",
"filled_racks": f"{asset_dir}Racks/",
"piles": f"{asset_dir}Piles/",
"railings": f"{asset_dir}Railing/",
# warehouse shell-specific assets (floor, walls, ceiling etc.)
"isaac_wh_props":f"{HOME_DIR}/Omniverse_content/isaac-simple-warehouse/Props/",
"floor": "SM_floor02.usd",
"walls": [
"SM_WallA_InnerCorner.usd",
"SM_WallB_InnerCorner.usd",
"SM_WallA_6M.usd",
"SM_WallB_6M.usd",
],
"lights":[
"SM_LampCeilingA_04.usd", # off
"SM_LampCeilingA_05.usd", # on
],
# we can also have stand-alone assets, that are directly spawned in specific positions
"forklift_asset": ["Forklift_A01_PR_V_NVD_01.usd"],
"robot_asset": ["transporter.usd"],
# We are also adding other assets from the paths above to choose from
"empty_racks_large_asset": ["RackLargeEmpty_A1.usd", "RackLargeEmpty_A2.usd"],
"empty_racks_long_asset": ["RackLongEmpty_A1.usd", "RackLongEmpty_A2.usd"],
"filled_racks_large_asset": [
"RackLarge_A1.usd",
"RackLarge_A2.usd",
"RackLarge_A3.usd",
"RackLarge_A4.usd",
"RackLarge_A5.usd",
"RackLarge_A6.usd",
"RackLarge_A7.usd",
"RackLarge_A8.usd",
"RackLarge_A9.usd",
],
"filled_racks_small_asset": [
"RackSmall_A1.usd",
"RackSmall_A2.usd",
"RackSmall_A3.usd",
"RackSmall_A4.usd",
"RackSmall_A5.usd",
"RackSmall_A6.usd",
"RackSmall_A7.usd",
"RackSmall_A8.usd",
"RackSmall_A9.usd",
],
"filled_racks_long_asset": [
"RackLong_A1.usd",
"RackLong_A2.usd",
"RackLong_A3.usd",
"RackLong_A4.usd",
"RackLong_A5.usd",
"RackLong_A6.usd",
"RackLong_A7.usd",
],
"filled_racks_long_high_asset": ["RackLong_A8.usd", "RackLong_A9.usd"],
"piles_asset": [
"WarehousePile_A1.usd",
"WarehousePile_A2.usd",
"WarehousePile_A3.usd",
"WarehousePile_A4.usd",
"WarehousePile_A5.usd",
"WarehousePile_A6.usd",
"WarehousePile_A7.usd",
],
"railings_asset": ["MetalFencing_A1.usd", "MetalFencing_A2.usd", "MetalFencing_A3.usd"],
############################# MOCKUP ASSETS #############################
"empty_racks_mockup": f"{asset_mockup_dir}Shelves/",
"filled_racks_mockup": f"{asset_mockup_dir}Racks/",
"empty_racks_long_asset_mockup": ["RackLongEmpty_A1.obj", "RackLongEmpty_A2.obj"],
"filled_racks_long_asset_mockup": "RackLong.obj",
}
# pairs of filelocations of assets and their corresponding mockups
file_loc_paired = {
"filled_racks": [[filenames["filled_racks"] + filenames["filled_racks_long_asset"][0], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][1], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][2], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][3], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][4], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][5], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]],
[filenames["filled_racks"] + filenames["filled_racks_long_asset"][6], filenames["filled_racks_mockup"] + filenames["filled_racks_long_asset_mockup"]]],
"empty_racks": [[filenames["empty_racks"] + filenames["empty_racks_long_asset"][0], filenames["empty_racks_mockup"] + filenames["empty_racks_long_asset_mockup"][0]],
[filenames["empty_racks"] + filenames["empty_racks_long_asset"][1], filenames["empty_racks_mockup"] + filenames["empty_racks_long_asset_mockup"][1]]],
"floors": [[filenames["isaac_wh_props"] + filenames["floor"], None]],
"walls": [[filenames["isaac_wh_props"] + filenames["walls"][0], None],
[filenames["isaac_wh_props"] + filenames["walls"][1], None],
[filenames["isaac_wh_props"] + filenames["walls"][2], None],
[filenames["isaac_wh_props"] + filenames["walls"][3], None],],
"lights": [[filenames["isaac_wh_props"] + filenames["lights"][0], None],
[filenames["isaac_wh_props"] + filenames["lights"][1], None]],
} | 7,939 | Python | 43.606741 | 172 | 0.625772 |
tudelft/autoGDMplus/README.md | # AutoGDM+
### Automated Pipeline for 3D Gas Dispersal Modelling and Environment Generation
This repository contains the code of AutoGDM+ based on the same concepts as [AutoGDM](https://github.com/tudelft/AutoGDM/). Please fully read this before proceeding.
## Required
- Tested on `Ubuntu 20.04 LTS`
- [`Isaac Sim`](https://developer.nvidia.com/isaac-sim) (Install with the Omniverse Launcher)
- [`Blender`](https://www.blender.org/)
- [`OpenFOAM`]()
- [`ROS`](http://wiki.ros.org/noetic/Installation/Ubuntu) (noetic)
## Installation
### Omniverse Launcher & Isaac Sim
Follow [these instructions:](https://docs.omniverse.nvidia.com/install-guide/latest/standard-install.html)
1) Download, install and run the [`Omniverse Launcher`](https://www.nvidia.com/en-us/omniverse/). It is strongly recommended you install with the cache enabled. In case of problems see the troubleshooting section.
2) Create a local Nucleus server by going to the 'Nucleus' tab and enabling it. You will have to create an associated local Nucleus account (this is not associated with any other account).
3) Install Isaac Sim version `2022.2.0`. Go to the 'exchange' tab and select Isaac Sim. Note, the default install location of Isaac Sim is `~/.local/share/ov/pkg/isaac_sim-<version>`
4) Download the necessery content:
- From the the exchange tab in the launcher, download both the 'Industrial 3D Models Pack' and the 'USD Physics Sample Pack' by clicking 'Save as...' (right part of the green download button).
- From the Nucleus tab in the launcher, go to `localhost/NVIDIA/Assets/Isaac/<version>/Isaac/Environments/Simple_Warehouse` and download these contents by clicking the download button in the details pane on the right.
- Extract these folders to `~/Omniverse_content` so that AutoGDM+ can find them. Another location can be specified with in the settings of AutoGDM+ if placed somewhere else.
### Blender
- Download and extract the blender.zip to a location of your preference, in this case `~/Downloads/blender-<version>-linux-x64`
### Paraview (optional)
- For visualizing and verify the meshing and CFD results
```
sudo apt-get update && sudo apt-get install paraview
```
### OpenFOAM
1) Check the [system requirements](https://develop.openfoam.com/Development/openfoam/blob/develop/doc/Requirements.md)
2) Download the [OpenFoam](https://develop.openfoam.com/Development/openfoam) v2212 and its [Thirdparty software](https://develop.openfoam.com/Development/ThirdParty-common/) and extract in `~/OpenFOAM` such that the directories are called `OpenFOAM-<version>` and `Thirdparty-<version>`
3) Download and extract the source code of [scotch (v6.1.0)](https://gitlab.inria.fr/scotch/scotch/-/releases/v6.1.0) into the Thirdparty dicectory
4) Open a commandline in the home directory and check the system
```
source OpenFOAM/Openfoam-v2212/etc/bashrc && foamSystemCheck
```
5) `cd` into `~/OpenFOAM/OpenFOAM-v2212` and build:
```
./Allwmake -j -s -q -l
```
6) Add the following lines to your `.bashrc` to add an alias to source your OpenFOAM installation:
```
# >>> OpenFOAM >>>
alias of2212='source $HOME/OpenFOAM/OpenFOAM-v2212/etc/bashrc'
# <<< OpenFOAM <<<
```
### ROS & Catkin Tools
1) Install [ROS noetic](http://wiki.ros.org/noetic/Installation/Ubuntu)
2) Install [catkin tools](https://catkin-tools.readthedocs.io/en/latest/installing.html)
### AutoGDM+
- Clone this repository, preferably in your home directory.
- Install the isaac_asset_placer: Copy and paste the `warehouse_gen` folder into the Isaac Sim examples folder located at `~/.local/share/ov/pkg/isaac_sim-<version>/exts/omni.isaac.examples/omni/isaac/examples/`
- Build the GADEN workspace:
```
source /opt/ros/noetic/setup.bash
cd autoGDMplus/gaden_ws
catkin init
catkin build
```
## Before Running AutoGDM+
1) Check the asset file locations and software versions in `~/autoGDMplus/config/current.yaml`, especially:
- `asset_dir` (line 8)
- `isaac_wh_props` (line 80)
- `forlift_asset` (line 93)
2) Define desired settings in `~/autoGDMplus/config/current.yaml`
3) Source your openfoam installation (with the previously created alias)
```
of2212
```
4) source the GADEN workspace
```
cd autoGDMplus/gaden_ws
source devel/setup.bash
```
## Run AutoGDM+
```
cd autoGDMplus
python3 main.py
```
## Troubleshooting
### Running AutoGDM+
- `could not find .../combined.fms`
- Solution: source your OpenFOAM installation before running
### Omniverse launcher
- [Stuck at login](https://forums.developer.nvidia.com/t/failed-to-login-stuck-after-logging-in-web-browser/260298/6)
- Solution: Search for the `nvidia-omniverse-launcher.desktop` file and copy it to `.config/autostart`
## Contact
Please reach out to us if you encounter any problems or suggestions. AutoGDM+ is a work in progress, we are excited to see it beeing used! Reach out to Hajo for all technical questions.
### Contributors
Hajo Erwich - Student & Maintainer - [email protected] <br />
Bart Duisterhof - Supervisor & PhD Student <br />
Prof. Dr. Guido de Croon | 5,041 | Markdown | 46.566037 | 287 | 0.748661 |
tudelft/autoGDMplus/warehouse_gen/test.py | #launch Isaac Sim before any other imports
#default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False}) # we can also run as headless.
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid
import numpy as np
world = World()
world.scene.add_default_ground_plane()
# fancy_cube = world.scene.add(
# DynamicCuboid(
# prim_path="/World/random_cube",
# name="fancy_cube",
# position=np.array([0, 0, 1.0]),
# scale=np.array([0.5015, 0.5015, 0.5015]),
# color=np.array([0, 0, 1.0]),
# ))
# Resetting the world needs to be called before querying anything related to an articulation specifically.
# Its recommended to always do a reset after adding your assets, for physics handles to be propagated properly
world.reset()
for i in range(1000):
# position, orientation = fancy_cube.get_world_pose()
# linear_velocity = fancy_cube.get_linear_velocity()
# # will be shown on terminal
# print("Cube position is : " + str(position))
# print("Cube's orientation is : " + str(orientation))
# print("Cube's linear velocity is : " + str(linear_velocity))
# we have control over stepping physics and rendering in this workflow
# things run in sync
world.step(render=True) # execute one physics step and one rendering step
simulation_app.close() # close Isaac Sim | 1,448 | Python | 41.617646 | 110 | 0.700967 |
tudelft/autoGDMplus/warehouse_gen/wh_recipes.py | import random, math
NUCLEUS_SERVER_CUSTOM = "/home/hajo/Omniverse_content/ov-industrial3dpack-01-100.1.1/"
SIMPLE_WAREHOUSE = "~/Omniverse_content/isaac-simple-warehouse/"
# This file contains dictionaries for different genration recipes - you can create your own here and expand the database!
# You can also edit existing to see how your rules generate scenes!
# Rule based placers (XYZ Locations based on Procedural or User-selected layout)
# X = columns; distance between racks (675 is width of rack) // Y = height // Z = rows
# R A C K S
divisor = 2
def racks_procedural():
positions = []
for i in range(9):
positions.extend(
[
(2800 - (i * 675), 0, 1888),
(2800 - (i * 675), 0, 962),
(2800 - (i * 675), 0, 513),
(2800 - (i * 675), 0, -1034),
(2800 - (i * 675), 0, -1820),
]
)
totalSample = len(positions)
minSample = math.floor(totalSample/divisor)
sampleSize = random.randint(minSample,totalSample)
filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)]
emptyRackPos = positions
return filledRackPos, emptyRackPos
def empty_racks_Umode():
positions = []
for i in range(9):
if i < 5:
positions.extend([(2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, -1820), (2800 - (i * 675), 0, -2225)])
else:
positions.extend(
[
(2800 - (i * 675), 0, 1888),
(2800 - (i * 675), 0, 962),
(2800 - (i * 675), 0, 513),
(2800 - (i * 675), 0, -1034),
(2800 - (i * 675), 0, -1820),
]
)
totalSample = len(positions)
minSample = math.floor(totalSample/divisor)
sampleSize = random.randint(minSample,totalSample)
filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)]
emptyRackPos = positions
return filledRackPos, emptyRackPos
def empty_racks_Lmode():
positions = []
for i in range(9):
if i < 5:
positions.extend([(2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513)])
else:
positions.extend(
[
(2800 - (i * 675), 0, 1888),
(2800 - (i * 675), 0, 962),
(2800 - (i * 675), 0, 513),
(2800 - (i * 675), 0, -1034),
(2800 - (i * 675), 0, -1820),
]
)
totalSample = len(positions)
minSample = math.floor(totalSample/divisor)
sampleSize = random.randint(minSample,totalSample)
filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)]
emptyRackPos = positions
return filledRackPos, emptyRackPos
def empty_racks_Imode():
positions = []
for i in range(9):
positions.extend(
[
(2800 - (i * 675), 0, 962),
(2800 - (i * 675), 0, 513),
(2800 - (i * 675), 0, -1034)
]
)
totalSample = len(positions)
minSample = math.floor(totalSample/divisor)
sampleSize = random.randint(minSample,totalSample)
filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)]
emptyRackPos = positions
return filledRackPos, emptyRackPos
## P I L E S
def piles_placer_procedural():
positions = []
for i in range(9):
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)])
# print("pile positions (procedural): ", positions)
return positions
def piles_placer_Umode():
positions = []
for i in range(9):
if i < 5:
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, -1440)])
else:
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)])
return positions
def piles_placer_Imode():
positions = []
for i in range(9):
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)])
return positions
def piles_placer_Lmode():
positions = []
for i in range(9):
if i<5:
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35)])
else:
positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)])
return positions
## R A I L I N G S
def railings_placer_procedural():
positions = []
for i in range(17):
positions.extend([(3017 - (i * 337.5), 0, -119)])
return positions
def railings_placer_Lmode():
positions = []
for i in range(17):
positions.extend([(3017 - (i * 337.5), 0, -119)])
return positions
def railings_placer_Umode():
positions = []
for i in range(9,17):
positions.extend([(3017 - (i * 337.5), 0, -119)])
return positions
def railings_placer_Imode():
positions = []
for i in range(17):
positions.extend([(3017 - (i * 337.5), 0, -119)])
return positions
# R O B O T / F O R K L I F T
def robo_fork_placer_procedural(posXYZ):
positions = []
for i in range(17):
positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])])
return positions
def robo_fork_placer_Lmode(posXYZ):
positions = []
for i in range(10,17):
positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])])
return positions
def robo_fork_placer_Umode(posXYZ):
positions = []
for i in range(9,17):
positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])])
return positions
def robo_fork_placer_Imode(posXYZ):
positions = []
for i in range(17):
positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])])
return positions
# Store rack position data
filledProcMode, emptyProcMode = racks_procedural()
filledUMode, emptyUMode = empty_racks_Umode()
filledLMode, emptyLMode = empty_racks_Lmode()
filledIMode, emptyIMode = empty_racks_Imode()
warehouse_recipe_custom = {
# First step is to identify what mode the generation is, we have 4 modes. By default, we will keep it at procedural.
# If it is a customized generation, we can update this value to the layout type chosen from the UI
# P.S : "procedural" mode is basically I-Shaped (Imode) with all objects selected
"mode": "procedural",
# Then, we point to asset paths, to pick one at random and spawn at specific positions
"empty_racks": f"{NUCLEUS_SERVER_CUSTOM}Shelves/",
"filled_racks": f"{NUCLEUS_SERVER_CUSTOM}Racks/",
"piles": f"{NUCLEUS_SERVER_CUSTOM}Piles/",
"railings": f"{NUCLEUS_SERVER_CUSTOM}Railing/",
"forklift": f"/home/hajo/Omniverse_content/ov-sig22-physics-01-100.1.0/Assets/Warehouse/Equipment/Forklifts/Forklift_A/",
"robot": f"http://omniverse-content-staging.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.1/Isaac/Robots/Transporter/",
# we can also have stand-alone assets, that are directly spawned in specific positions
"forklift_asset": ["Forklift_A01_PR_V_NVD_01.usd"],
"robot_asset": ["transporter.usd"],
# We are also adding other assets from the paths above to choose from
"empty_racks_asset": ["RackLargeEmpty_A1.usd", "RackLargeEmpty_A2.usd"],
"filled_racks_asset": [
"RackLarge_A1.usd",
"RackLarge_A2.usd",
"RackLarge_A3.usd",
"RackLarge_A4.usd",
"RackLarge_A5.usd",
"RackLarge_A6.usd",
"RackLarge_A7.usd",
"RackLarge_A8.usd",
"RackLarge_A9.usd",
],
"piles_asset": [
"WarehousePile_A1.usd",
"WarehousePile_A2.usd",
"WarehousePile_A3.usd",
"WarehousePile_A4.usd",
"WarehousePile_A5.usd",
"WarehousePile_A6.usd",
"WarehousePile_A7.usd",
],
"railings_asset": ["MetalFencing_A1.usd", "MetalFencing_A2.usd", "MetalFencing_A3.usd"],
# Now, we have a sample space of positions within the default warehouse shell these objects can go to. We can randomly
# spawn prims into randomly selected positions from this sample space. These are either generated by placer functions,
# or hardcoded for standalone assets
# Empty and Filled racks both have similar dimensions, so we reuse the positions for racks
"filled_racks_procedural": filledProcMode,
"empty_racks_procedural": emptyProcMode,
"filled_racks_Umode": filledUMode,
"empty_racks_Umode": emptyUMode,
"filled_racks_Lmode": filledLMode,
"empty_racks_Lmode": emptyLMode,
"filled_racks_Imode": filledIMode,
"empty_racks_Imode": emptyIMode,
# Piles (Rules doesnt change based on layout mode here. Feel free to update rules)
"piles_procedural": piles_placer_procedural(),
"piles_Umode": piles_placer_Umode(),
"piles_Lmode": piles_placer_Lmode(),
"piles_Imode": piles_placer_Imode(),
# Railings (Similar to piles)
"railings_procedural": railings_placer_procedural(),
"railings_Umode": railings_placer_Umode(),
"railings_Lmode": railings_placer_Lmode(),
"railings_Imode": railings_placer_Imode(),
# Forklift and Robot
"forklift_procedural": robo_fork_placer_procedural((2500, 0, -333)),
"forklift_Umode": robo_fork_placer_Umode((2500, 0, -333)),
"forklift_Lmode": robo_fork_placer_Lmode((2500, 0, -333)),
"forklift_Imode": robo_fork_placer_Imode((2500, 0, -333)),
"robot_procedural": robo_fork_placer_procedural((3017, 8.2, -698)),
"robot_Umode": robo_fork_placer_Umode((3017, 8.2, -698)),
"robot_Lmode": robo_fork_placer_Lmode((3017, 8.2, -698)),
"robot_Imode": robo_fork_placer_Imode((3017, 8.2, -698)),
}
warehouse_recipe_simple = {
# First step is to identify what mode the generation is, we have 4 modes. By default, we will keep it at procedural.
# If it is a customized generation, we can update this value to the layout type chosen from the UI
# P.S : "procedural" mode is basically I-Shaped (Imode) with all objects selected
"mode": "procedural",
# Then, we point to asset paths, to pick one at random and spawn at specific positions
"empty_racks": f"{NUCLEUS_SERVER_CUSTOM}Shelves/",
"filled_racks": f"{NUCLEUS_SERVER_CUSTOM}Racks/",
"piles": f"{NUCLEUS_SERVER_CUSTOM}Piles/",
"railings": f"{NUCLEUS_SERVER_CUSTOM}Railing/",
"forklift": f"/home/hajo/Omniverse_content/ov-sig22-physics-01-100.1.0/Assets/Warehouse/Equipment/Forklifts/Forklift_A/",
"robot": f"http://omniverse-content-staging.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.1/Isaac/Robots/Transporter/",
# we can also have stand-alone assets, that are directly spawned in specific positions
"forklift_asset": ["Forklift_A01_PR_V_NVD_01.usd"],
"robot_asset": ["transporter.usd"],
# We are also adding other assets from the paths above to choose from
"empty_racks_asset": ["RackLargeEmpty_A1.usd", "RackLargeEmpty_A2.usd"],
"filled_racks_asset": [
"RackLarge_A1.usd",
"RackLarge_A2.usd",
"RackLarge_A3.usd",
"RackLarge_A4.usd",
"RackLarge_A5.usd",
"RackLarge_A6.usd",
"RackLarge_A7.usd",
"RackLarge_A8.usd",
"RackLarge_A9.usd",
],
"piles_asset": [
"WarehousePile_A1.usd",
"WarehousePile_A2.usd",
"WarehousePile_A3.usd",
"WarehousePile_A4.usd",
"WarehousePile_A5.usd",
"WarehousePile_A6.usd",
"WarehousePile_A7.usd",
],
"railings_asset": ["MetalFencing_A1.usd", "MetalFencing_A2.usd", "MetalFencing_A3.usd"],
# Now, we have a sample space of positions within the default warehouse shell these objects can go to. We can randomly
# spawn prims into randomly selected positions from this sample space. These are either generated by placer functions,
# or hardcoded for standalone assets
# Empty and Filled racks both have similar dimensions, so we reuse the positions for racks
"filled_racks_procedural": filledProcMode,
"empty_racks_procedural": emptyProcMode,
"filled_racks_Umode": filledUMode,
"empty_racks_Umode": emptyUMode,
"filled_racks_Lmode": filledLMode,
"empty_racks_Lmode": emptyLMode,
"filled_racks_Imode": filledIMode,
"empty_racks_Imode": emptyIMode,
# Piles (Rules doesnt change based on layout mode here. Feel free to update rules)
"piles_procedural": piles_placer_procedural(),
"piles_Umode": piles_placer_Umode(),
"piles_Lmode": piles_placer_Lmode(),
"piles_Imode": piles_placer_Imode(),
# Railings (Similar to piles)
"railings_procedural": railings_placer_procedural(),
"railings_Umode": railings_placer_Umode(),
"railings_Lmode": railings_placer_Lmode(),
"railings_Imode": railings_placer_Imode(),
# Forklift and Robot
"forklift_procedural": robo_fork_placer_procedural((2500, 0, -333)),
"forklift_Umode": robo_fork_placer_Umode((2500, 0, -333)),
"forklift_Lmode": robo_fork_placer_Lmode((2500, 0, -333)),
"forklift_Imode": robo_fork_placer_Imode((2500, 0, -333)),
"robot_procedural": robo_fork_placer_procedural((3017, 8.2, -698)),
"robot_Umode": robo_fork_placer_Umode((3017, 8.2, -698)),
"robot_Lmode": robo_fork_placer_Lmode((3017, 8.2, -698)),
"robot_Imode": robo_fork_placer_Imode((3017, 8.2, -698)),
} | 13,479 | Python | 39.848485 | 125 | 0.617405 |
tudelft/autoGDMplus/warehouse_gen/isaac_asset_placer.py | """ isaac_asset_placer.py
Just like blender_asset_placer.py this script takes in the available recipies and
generates .usd files accordingly.
"""
import sys # get recipe and mockup scene dir
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all the args after " -- "
recipe_dir = argv[0] # recipe folder
usd_dir = argv[1] # isaac sim export folder
# Launch Isaac Sim before any other imports
# Default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": True})
import os, platform
import glob
import json
import random
import numpy as np
import carb
import omni.ext
import omni.ui as ui
from omni.ui.workspace_utils import RIGHT
from pxr import Usd, UsdGeom, UsdLux, Gf
# from wh_recipes import warehouse_recipe_custom as wh_rec
# from wh_recipes import warehouse_recipe_simple as wh_simp
class wh_helpers():
def __init__(self):
# NUCLEUS_SERVER_CUSTOM = "~/Omniverse_content/ov-industrial3dpack-01-100.1.1/"
# SIMPLE_WAREHOUSE = "~/Omniverse_content/isaac-simple-warehouse/"
self._system = platform.system()
self.usd_save_dir = usd_dir
def config_environment(self):
for prim in self._stage.Traverse():
if '/Environment/' in str(prim):
prim.SetActive(False)
# self.create_rectangular_light(translate, scale)
def create_distant_light(self):
environmentPath = '/Environment'
lightPath = environmentPath + '/distantLight'
prim = self._stage.DefinePrim(environmentPath, 'Xform')
distLight = UsdLux.DistantLight.Define(self._stage, lightPath)
distLight.AddRotateXYZOp().Set(Gf.Vec3f(315,0,0))
distLight.CreateColorTemperatureAttr(6500.0)
if self._system == "Linux":
distLight.CreateIntensityAttr(6500.0)
else:
distLight.CreateIntensityAttr(3000.0)
distLight.CreateAngleAttr(1.0)
lightApi = UsdLux.ShapingAPI.Apply(distLight.GetPrim())
lightApi.CreateShapingConeAngleAttr(180)
# TODO: optional, implement this func correctly
def create_rectangular_light(self, translate, scale):
environmentPath = '/Environment'
lightPath = environmentPath + '/rectLight'
prim = self._stage.DefinePrim(environmentPath, 'Xform')
rectLight = UsdLux.RectLight.Define(self._stage, lightPath)
# rectLight = UsdLux.RectLight.Define(prim, lightPath)
# rectLight.AddScaleOp().Set(Gf.Vec3f(scale[0],scale[1],scale[2]))
# rectLight.translateOp().Set(Gf.Vec3f(translate[0],translate[1],translate[2]))
# distLight.AddRotateXYZOp().Set(Gf.Vec3f(315,0,0))
# UsdGeom.XformCommonAPI(rectLight).SetTranslate(translate)
# UsdGeom.XformCommonAPI(rectLight).SetScale(scale)
print("rectlight!!!")
rectLight.CreateColorTemperatureAttr(6500.0)
if self._system == "Linux":
rectLight.CreateIntensityAttr(6500.0)
else:
rectLight.CreateIntensityAttr(3000.0)
#distLight.CreateAngleAttr(1.0)
lightApi = UsdLux.ShapingAPI.Apply(rectLight.GetPrim())
#lightApi.CreateShapingConeAngleAttr(180)
# spawn_prim function takes in a path, XYZ position, orientation, a name and spawns the USD asset in path with
# the input name in the given position and orientation inside the world prim as an XForm
def spawn_prim(self, path, translate, rotate, name, scale=Gf.Vec3f(1.0, 1.0, 1.0)):
world = self._stage.GetDefaultPrim()
# Creating an XForm as a child to the world prim
asset = UsdGeom.Xform.Define(self._stage, f"{str(world.GetPath())}/{name}")
# Checking if asset already has a reference and clearing it
asset.GetPrim().GetReferences().ClearReferences()
# Adding USD in the path as reference to this XForm
asset.GetPrim().GetReferences().AddReference(f"{path}")
# Setting the Translate and Rotate
UsdGeom.XformCommonAPI(asset).SetTranslate(translate)
UsdGeom.XformCommonAPI(asset).SetRotate(rotate)
UsdGeom.XformCommonAPI(asset).SetScale(scale)
# Returning the Xform if needed
return asset
# Clear stage function
def clear_stage_old(self):
#Removing all children of world except distant light
self.get_root()
world = self._stage.GetDefaultPrim()
doesLightExist = self._stage.GetPrimAtPath('/Environment/distantLight').IsValid()
# config environment
if doesLightExist == False:
self.config_environment()
# clear scene
for i in world.GetChildren():
if i.GetPath() == '/Environment/distantLight' or i.GetPath() == '/World':
continue
else:
self._stage.RemovePrim(i.GetPath())
def clear_stage(self):
self.get_root()
# Removing all children of world
world = self._stage.GetDefaultPrim()
for i in world.GetChildren():
if i.GetPath() == '/World':
continue
else:
self._stage.RemovePrim(i.GetPath())
# gets stage
def get_root(self):
self._stage = omni.usd.get_context().get_stage()
#UsdGeom.Tokens.upAxis(self._stage, UsdGeom.Tokens.y) # Set stage upAxis to Y
world_prim = self._stage.DefinePrim('/World', 'Xform') # Create top-level World Xform primitive
self._stage.SetDefaultPrim(world_prim) # Set as default primitive
# save stage to .usd
def save_stage(self, fname):
save_loc = f"{self.usd_save_dir}{fname}.usd"
omni.usd.get_context().save_as_stage(save_loc, None)
if os.path.isfile(save_loc):
print(f"[omni.warehouse] saved .usd file to: {self.usd_save_dir}{fname}.usd")
else:
print(f"[omni.warehouse] .usd export FAILED: {self.usd_save_dir}{fname}.usd")
##################################################################
############################# MAIN ###############################
##################################################################
if __name__ == "__main__":
_wh_helpers = wh_helpers()
recipes = glob.glob(f"{recipe_dir}*.txt") # gather all recipes
for rec_loc in recipes:
with open(rec_loc) as f: # reading the recipe from the file
data = f.read()
recipe = json.loads(data) # reconstructing the data as a dictionary
_wh_helpers.clear_stage()
# place lighting
# for light in recipe["isaac_rect_lights"]:
# _wh_helpers.create_rectangular_light(light["location"], light["scale"])
# place interior props
for recipe_dict in [recipe["isaac_floor"],
recipe["isaac_walls"],
recipe["interior"],
recipe["isaac_lights"]]:
for asset in recipe_dict:
_wh_helpers.spawn_prim(asset["filename"],
asset["location"],
asset["orientation"],
asset["asset_id"],
scale=asset["scale"])
_wh_helpers.save_stage(f"{recipe['env_type']}_{recipe['env_id']}")
simulation_app.close() # close Isaac Sim
| 7,415 | Python | 42.116279 | 114 | 0.604855 |
tudelft/autoGDMplus/warehouse_gen/wh_gen.py | #launch Isaac Sim before any other imports
#default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": True}) # we can also run as headless.
import numpy as np
import os, platform
import random
import carb
import omni.ext
import omni.ui as ui
from omni.ui.workspace_utils import RIGHT
from pxr import Usd, UsdGeom, UsdLux, Gf
from wh_recipes import warehouse_recipe_custom as wh_rec
from wh_recipes import warehouse_recipe_simple as wh_simp
class wh_helpers():
def __init__(self):
USD_SAVE_DIR = "~/AutoGDM2/USD_scenes/"
#USD_SAVE_DIR = "~/Omniverse_content/isaac-simple-warehouse/"
NUCLEUS_SERVER_CUSTOM = "~/Omniverse_content/ov-industrial3dpack-01-100.1.1/"
SIMPLE_WAREHOUSE = "~/Omniverse_content/isaac-simple-warehouse/"
isTest = False
self._system = platform.system()
self.mode = "procedural"
self.objects = ["empty_racks", "filled_racks", "piles", "railings", "forklift", "robot"]
self.objectDict = self.initAssetPositions()
self.objDictList = list(self.objectDict)
self.isaacSimScale = Gf.Vec3f(100,100,100)
self.usd_save_dir = USD_SAVE_DIR
# Shell info is hard-coded for now
# self.shell_path = f"{NUCLEUS_SERVER}Buildings/Warehouse/Warehouse01.usd"
self.shell_path = f"{NUCLEUS_SERVER_CUSTOM}Buildings/Warehouse/Warehouse01.usd"
self.shell_translate = (0, 0, 55.60183)
self.shell_rotate = (-90.0, 0.0, 0.0)
self.shell_name = "WarehouseShell"
self.shell_simple_path = f"{SIMPLE_WAREHOUSE}warehouse.usd"
self.shell_simple_translate = (0, 0, 0)
self.shell_simple_rotate = (0.0, 0.0, 0.0)
self.shell_simple_name = "WarehouseShell"
def config_environment(self):
for prim in self._stage.Traverse():
if '/Environment/' in str(prim):
prim.SetActive(False)
self.create_distant_light()
def create_distant_light(self):
environmentPath = '/Environment'
lightPath = environmentPath + '/distantLight'
prim = self._stage.DefinePrim(environmentPath, 'Xform')
distLight = UsdLux.DistantLight.Define(self._stage, lightPath)
distLight.AddRotateXYZOp().Set(Gf.Vec3f(315,0,0))
distLight.CreateColorTemperatureAttr(6500.0)
if self._system == "Linux":
distLight.CreateIntensityAttr(6500.0)
else:
distLight.CreateIntensityAttr(3000.0)
distLight.CreateAngleAttr(1.0)
lightApi = UsdLux.ShapingAPI.Apply(distLight.GetPrim())
lightApi.CreateShapingConeAngleAttr(180)
def genShell(self):
self.clear_stage()
self.mode = "procedural"
self.spawn_prim(self.shell_path, self.shell_translate, self.shell_rotate, self.shell_name)
print(str("[omni.warehouse] generating shell from: " + self.shell_path))
def gen_shell_simple(self):
self.clear_stage()
self.mode = "procedural"
self.spawn_prim(self.shell_simple_path, self.shell_simple_translate, self.shell_simple_rotate, self.shell_simple_name)
print(str("[omni.warehouse] generating shell from: " + self.shell_simple_path))
# Generate Warehouse w/ user-selected assets
def gen_custom(self, isProcedural, mode, objectButtons):
self.mode = mode
# Clear stage
self.clear_stage()
# Create shell
self.spawn_prim(self.shell_path, self.shell_translate, self.shell_rotate, self.shell_name)
selected_obj = []
# Spawn all objects (procedural) or user-selected objects
if isProcedural:
selected_obj = self.objects
else:
for i in range(len(objectButtons)):
if objectButtons[i].checked == True:
identifier = {
0: "empty_racks",
1: "filled_racks",
2: "piles",
3: "railings",
4: "forklift",
5: "robot",
}
selected_obj.append(identifier.get(i))
objectUsdPathDict = {"empty_racks": [],
"filled_racks":[],
"piles":[],
"railings":[],
"forklift":[],
"robot":[]
}
# Reserved spots are dependent on self.mode (i.e. layout)
numForkLifts = len(wh_rec[self.objects[4] + "_" + self.mode])
spots2RsrvFL = numForkLifts - 1
numRobots = len(wh_rec[self.objects[5] + "_" + self.mode])
spots2RsrvRob = numRobots - 1
self.objParams = {"empty_racks": [(-90,-180,0), (1,1,1), 5],
"filled_racks":[(-90,-180,0), (1,1,1), 5],
"piles":[(-90,-90,0), (1,1,1), 5],
"railings":[(-90,0,0), (1,1,1), 5],
"forklift":[(-90, random.uniform(0, 90), 0), Gf.Vec3f(1,1,1), spots2RsrvFL],
"robot":[(-90, random.uniform(0, 90), 0), self.isaacSimScale, spots2RsrvRob]
}
# Reserve spots for Smart Import feature
for h in range(0,len(selected_obj)):
for i in range(0, len(self.objDictList)):
if selected_obj[h] == self.objDictList[i]:
for j in wh_rec[selected_obj[h] + "_asset"]:
objectUsdPathDict[self.objDictList[i]].append(wh_rec[selected_obj[h]] + j)
rotation = self.objParams[self.objDictList[i]][0]
scale = self.objParams[self.objDictList[i]][1]
spots2Rsrv = self.objParams[self.objDictList[i]][2]
self.objectDict[self.objDictList[i]] = self.reservePositions(objectUsdPathDict[self.objDictList[i]], selected_obj[h], rotation, scale, spots2Rsrv)
# Function to reserve spots/positions for Smart Import feature (after initial generation of assets)
def reservePositions(self, assets, asset_prefix, rotation = (0,0,0), scale = (1,1,1), spots2reserve = 5):
if len(assets) > 0:
rotate = rotation
scale = scale
all_translates = wh_rec[asset_prefix + "_" + self.mode]
#Select all but 5 positions from available positions (reserved for Smart Import functionality)
if spots2reserve >= len(all_translates) and len(all_translates) > 0:
spots2reserve = len(all_translates) - 1
elif len(all_translates) == 0:
spots2reserve = 0
reserved_positions = random.sample(all_translates, spots2reserve)
translates = [t for t in all_translates if t not in reserved_positions]
positions = reserved_positions
for i in range(len(translates)):
name = asset_prefix + str(i)
path = random.choice(assets)
translate = translates[i]
self.spawn_prim(path, translate, rotate, name, scale)
return positions
# spawn_prim function takes in a path, XYZ position, orientation, a name and spawns the USD asset in path with
# the input name in the given position and orientation inside the world prim as an XForm
def spawn_prim(self, path, translate, rotate, name, scale=Gf.Vec3f(1.0, 1.0, 1.0)):
world = self._stage.GetDefaultPrim()
# Creating an XForm as a child to the world prim
asset = UsdGeom.Xform.Define(self._stage, f"{str(world.GetPath())}/{name}")
# Checking if asset already has a reference and clearing it
asset.GetPrim().GetReferences().ClearReferences()
# Adding USD in the path as reference to this XForm
asset.GetPrim().GetReferences().AddReference(f"{path}")
# Setting the Translate and Rotate
UsdGeom.XformCommonAPI(asset).SetTranslate(translate)
UsdGeom.XformCommonAPI(asset).SetRotate(rotate)
UsdGeom.XformCommonAPI(asset).SetScale(scale)
# Returning the Xform if needed
return asset
def initAssetPositions(self):
dictAssetPositions = {
"empty_racks": wh_rec["empty_racks" + "_" + self.mode],
"filled_racks": wh_rec["filled_racks" + "_" + self.mode],
"piles": wh_rec["piles" + "_" + self.mode],
"railings": wh_rec["railings" + "_" + self.mode],
"forklift": wh_rec["forklift" + "_" + self.mode],
"robot": wh_rec["robot" + "_" + self.mode]
}
return dictAssetPositions
# Clear stage function
def clear_stage(self):
#Removing all children of world except distant light
self.get_root()
world = self._stage.GetDefaultPrim()
doesLightExist = self._stage.GetPrimAtPath('/Environment/distantLight').IsValid()
# config environment
if doesLightExist == False:
self.config_environment()
# clear scene
for i in world.GetChildren():
if i.GetPath() == '/Environment/distantLight' or i.GetPath() == '/World':
continue
else:
self._stage.RemovePrim(i.GetPath())
# gets stage
def get_root(self):
self._stage = omni.usd.get_context().get_stage()
#UsdGeom.Tokens.upAxis(self._stage, UsdGeom.Tokens.y) # Set stage upAxis to Y
world_prim = self._stage.DefinePrim('/World', 'Xform') # Create top-level World Xform primitive
self._stage.SetDefaultPrim(world_prim) # Set as default primitive
# save stage to .usd
def save_stage(self, fname):
save_loc = f"{self.usd_save_dir}{fname}.usd"
omni.usd.get_context().save_as_stage(save_loc, None)
if os.path.isfile(save_loc):
print(f"[omni.warehouse] saved .usd file to: {self.usd_save_dir}{fname}.usd")
else:
print(f"[omni.warehouse] .usd export FAILED: {self.usd_save_dir}{fname}.usd")
### M A I N ###
_wh_helper = wh_helpers()
# Arguments for gen_custom
isProcedural = True
genCustomMode = "procedural"
genCustomButtons = ["empty_racks", "filled_racks", "piles", "railings", "forklift", "robot"]
_wh_helper.gen_shell_simple()
# _wh_helper.gen_custom(isProcedural, genCustomMode, genCustomButtons)
_wh_helper.save_stage("test002")
simulation_app.close() # close Isaac Sim
| 10,448 | Python | 44.628821 | 166 | 0.595521 |
tudelft/autoGDMplus/environments/ROS/empty_project/launch/ros/simbot_costmap_global_params.yaml | ########################################################################
# Global parameters for the COSTMAP_2D pkg (navigation stack)
########################################################################
global_costmap:
plugins:
- {name: static_map, type: "costmap_2d::StaticLayer" }
- {name: obstacles, type: "costmap_2d::VoxelLayer"}
- {name: inflation, type: "costmap_2d::InflationLayer" }
#- {name: proxemic, type: "social_navigation_layers::ProxemicLayer" }
global_frame: map
robot_base_frame: base_link
update_frequency: 1.0
publish_frequency: 0.5
static_map: true
rolling_window: false
always_send_full_costmap: true
visualize_potential: true
obstacles:
track_unknown_space: true
inflation:
inflation_radius: 0.75
cost_scaling_factor: 5.0
# proxemic:
# amplitude: 150.0
# covariance: 0.1
# cutoff: 20
# factor: 1.0
| 901 | YAML | 27.187499 | 75 | 0.562708 |
tudelft/autoGDMplus/environments/ROS/empty_project/launch/ros/simbot_costmap_local_params.yaml | ########################################################################
# Local parameters for the COSTMAP_2D pkg (navigation stack)
########################################################################
local_costmap:
plugins:
# - {name: static_map, type: "costmap_2d::StaticLayer" }
- {name: obstacles, type: "costmap_2d::VoxelLayer"}
- {name: inflation, type: "costmap_2d::InflationLayer" }
# - {name: proxemic, type: "social_navigation_layers::ProxemicLayer" }
global_frame: odom
robot_base_frame: base_link
update_frequency: 5.0
publish_frequency: 5.0
static_map: false
rolling_window: true
width: 6.0
height: 6.0
resolution: 0.05
min_obstacle_height: -10
always_send_full_costmap: true
obstacles:
track_unknown_space: true
inflation:
inflation_radius: 0.75
cost_scaling_factor: 5.0
# proxemic:
# amplitude: 150.0
# covariance: 0.1
# cutoff: 20.0
# factor: 1.0
| 940 | YAML | 25.885714 | 72 | 0.565957 |
tudelft/autoGDMplus/environments/ROS/empty_project/launch/ros/simbot_global_planner_params.yaml | NavfnROS:
allow_unknown: false
default_tolerance: 0.0
visualize_potential: true
use_dijkstra: true
use_quadratic: true
use_grid_path: true
old_navfn_behavior: false
# Defaults:
# allow_unknown: true
# default_tolerance: 0.0
# visualize_potential: false
# use_dijkstra: true
# use_quadratic: true
# use_grid_path: false
# old_navfn_behavior: false
| 372 | YAML | 18.631578 | 30 | 0.712366 |
tudelft/autoGDMplus/environments/ROS/empty_project/launch/ros/simbot_local_planner_params.yaml | ###############################################################################################
# Base_local_planner parameters - Trajectory generator based on costmaps
#
# The base_local_planner package provides a controller that drives a mobile base in the plane.
###############################################################################################
# IF use DWA Planner
#-----------------------------------
DWAPlannerROS:
max_trans_vel: 0.8
min_trans_vel: 0.06
max_vel_x: 0.8
min_vel_x: 0.0
max_vel_y: 0.0
min_vel_y: 0.0
max_rot_vel: 1.5 #rad 0.8rad = 45deg (aprox)
min_rot_vel: 0.2
acc_lim_x: 5.0
acc_lim_y: 0.0
acc_lim_theta: 5.0
acc_lim_trans: 0.45
prune_plan: true
xy_goal_tolerance: 0.2 #m
yaw_goal_tolerance: 0.4 #rad
trans_stopped_vel: 0.0
rot_stopped_vel: 0.8
sim_time: 1.0
sim_granularity: 0.05
angular_sim_granularity: 0.05
path_distance_bias: 32
goal_distance_bias: 20
occdist_scale: 0.02
stop_time_buffer: 0.5
oscillation_reset_dist: 0.10
oscillation_reset_angle: 0.1
forward_point_distanvce: 0.325
scalling_speed: 0.1
max_scaling_factor: 0.2
vx_samples: 10
vy_samples: 10
vth_samples: 15
use_dwa: true
# IF use Trajectory Rollout Planner
#-----------------------------------
TrajectoryPlannerROS:
max_vel_x: 0.6 #0.4
min_vel_x: 0.1 #0.0
max_vel_theta: 0.6 #rad 0.8rad = 45deg (aprox)
min_vel_theta: -0.6
min_in_place_vel_theta: 0.1
acc_lim_x: 5.0 #must be high
acc_lim_y: 0.0
acc_lim_theta: 5.0
acc_limit_trans: 0.4
holonomic_robot: false
#Goal Tolerance Parameters
yaw_goal_tolerance: 0.4 #rad
xy_goal_tolerance: 0.3 #m
#Forward Simulation Parameters
sim_time: 5.0
# sim_granularity: 0.05
# angular_sim_granularity: 0.05
# vx_samples: 3
# vtheta_samples: 20
# controller_frequency: 20
#Trajectory Scoring Parameters
# pdist_scale: 0.6 #The weighting for how much the controller should stay close to the path it was given (default 0.6)
# gdist_scale: 0.8 #The weighting for how much the controller should attempt to reach its local goal, also controls speed (default 0.8#)
| 2,209 | YAML | 25.626506 | 150 | 0.578542 |
tudelft/autoGDMplus/environments/ROS/empty_project/launch/ros/simbot_costmap_common_params.yaml | ########################################################################
# Common parameters for the COSTMAP_2D pkg (navigation stack)
########################################################################
obstacle_range: 2.5 #Update costmap with information about obstacles that are within 2.5 meters of the base
raytrace_range: 3.0 #Clear out space (remove obstacles) up to 3.0 meters away given a sensor reading
# FOOTPRINT
#-----------
#footprint: [[0.35,0.25],[0.35,-0.25],[-0.35,-0.25],[-0.35,0.25]]
#A circular footprint of 0.45 diameter
#footprint: [[ 0.225,0.000 ], [ 0.208, 0.086 ],[ 0.159, 0.159 ],[ 0.086, 0.208 ], [ 0.000, 0.225 ], [ -0.086, 0.208 ], [ -0.159, 0.159 ], [ -0.208, 0.086 ], [ -0.225, 0.000 ],[ -0.208, -0.086 ], [ -0.159, -0.159 ], [ -0.086, -0.208 ], [ -0.000, -0.225 ], [ 0.086, -0.208 ], [ 0.159, -0.159 ], [ 0.208, -0.086 ]]
robot_radius: 0.26 #[m] radius of the robot shape for Giraff Robots (instead of the footprint)
#inflation_radius: 0.6
# List of sensors that are going to be passing information to the costmap
observation_sources: laser_scan laser2_scan laser_stage
#sensor_id: {sensor_frame: [], data_type: [LaserScan/PointCloud], topic: [], marking: true, clearing: true}
laser_scan: {sensor_frame: laser_link, data_type: LaserScan, topic: /laser_scan, marking: true, clearing: true}
laser2_scan: {sensor_frame: laser2_link, data_type: LaserScan, topic: /laser2_scan, marking: true, clearing: true}
laser_stage: {sensor_frame: laser_stage, data_type: LaserScan, topic: /laser_scan, marking: true, clearing: true}
#Planners
#---------
base_global_planner: navfn/NavfnROS
base_local_planner: dwa_local_planner/DWAPlannerROS
#base_local_planner: base_local_planner/TrajectoryPlannerROS
planner_frequency: 1.0
controller_frequency: 20.0
planner_patience: 5.0
controller_patience: 5.0
| 1,845 | YAML | 50.277776 | 315 | 0.627642 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_anemometer/package.xml | <package>
<name>simulated_anemometer</name>
<version>1.0.0</version>
<description> This package simulates the response of a digital anemometer deployed within the gas_dispersion_simulation pkg.</description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<author>Javier Monroy</author>
<!-- Dependencies which this package needs to build itself. -->
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>roscpp</build_depend>
<build_depend>visualization_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<build_depend>olfaction_msgs</build_depend>
<build_depend>tf</build_depend>
<build_depend>gaden_player</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>roscpp</run_depend>
<run_depend>visualization_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>nav_msgs</run_depend>
<run_depend>olfaction_msgs</run_depend>
<run_depend>tf</run_depend>
<run_depend>gaden_player</run_depend>
</package>
| 1,142 | XML | 34.718749 | 140 | 0.732925 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_anemometer/src/fake_anemometer.h | #include <ros/ros.h>
//#include <nav_msgs/Odometry.h>
//#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_listener.h>
//#include <std_msgs/Float32.h>
//#include <std_msgs/Float32MultiArray.h>
#include <visualization_msgs/Marker.h>
#include <olfaction_msgs/anemometer.h>
#include <gaden_player/WindPosition.h>
#include <angles/angles.h>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <fstream>
#include <iostream>
// Sensor Parameters
std::string input_sensor_frame;
std::string input_fixed_frame;
double noise_std;
bool use_map_ref_system;
// Vars
bool first_reading = true;
bool notified = false;
//functions:
void loadNodeParameters(ros::NodeHandle private_nh);
| 739 | C | 20.764705 | 54 | 0.725304 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_anemometer/src/fake_anemometer.cpp |
#include "fake_anemometer.h"
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
typedef boost::normal_distribution<double> NormalDistribution;
typedef boost::mt19937 RandomGenerator;
typedef boost::variate_generator<RandomGenerator&, \
NormalDistribution> GaussianGenerator;
int main( int argc, char** argv )
{
ros::init(argc, argv, "simulated_anemometer");
ros::NodeHandle n;
ros::NodeHandle pn("~");
srand (time(NULL));
//Read parameters
loadNodeParameters(pn);
//Publishers
//ros::Publisher sensor_read_pub = n.advertise<std_msgs::Float32MultiArray>("WindSensor_reading", 500);
ros::Publisher sensor_read_pub = n.advertise<olfaction_msgs::anemometer>("WindSensor_reading", 500);
ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("WindSensor_display", 100);
//Service to request wind values to simulator
ros::ServiceClient client = n.serviceClient<gaden_player::WindPosition>("/wind_value");
tf::TransformListener tf_;
// Init Visualization data (marker)
//----------------------------------------------------------------
// sensor = sphere
// conector = stick from the floor to the sensor
visualization_msgs::Marker sensor;
visualization_msgs::Marker connector;
visualization_msgs::Marker connector_inv;
visualization_msgs::Marker wind_point;
visualization_msgs::Marker wind_point_inv;
sensor.header.frame_id = input_fixed_frame.c_str();
sensor.ns = "sensor_visualization";
sensor.action = visualization_msgs::Marker::ADD;
sensor.type = visualization_msgs::Marker::SPHERE;
sensor.id = 0;
sensor.scale.x = 0.1;
sensor.scale.y = 0.1;
sensor.scale.z = 0.1;
sensor.color.r = 0.0f;
sensor.color.g = 0.0f;
sensor.color.b = 1.0f;
sensor.color.a = 1.0;
connector.header.frame_id = input_fixed_frame.c_str();
connector.ns = "sensor_visualization";
connector.action = visualization_msgs::Marker::ADD;
connector.type = visualization_msgs::Marker::CYLINDER;
connector.id = 1;
connector.scale.x = 0.1;
connector.scale.y = 0.1;
connector.color.a = 1.0;
connector.color.r = 1.0f;
connector.color.b = 1.0f;
connector.color.g = 1.0f;
// Init Marker: arrow to display the wind direction measured.
wind_point.header.frame_id = input_sensor_frame.c_str();
wind_point.action = visualization_msgs::Marker::ADD;
wind_point.ns = "measured_wind";
wind_point.type = visualization_msgs::Marker::ARROW;
// Init Marker: arrow to display the inverted wind direction measured.
wind_point_inv.header.frame_id = input_sensor_frame.c_str();
wind_point_inv.action = visualization_msgs::Marker::ADD;
wind_point_inv.ns = "measured_wind_inverted";
wind_point_inv.type = visualization_msgs::Marker::ARROW;
// LOOP
//----------------------------------------------------------------
tf::TransformListener listener;
ros::Rate r(2);
while (ros::ok())
{
//Vars
tf::StampedTransform transform;
bool know_sensor_pose = true;
//Get pose of the sensor in the /map reference
try
{
listener.lookupTransform(input_fixed_frame.c_str(), input_sensor_frame.c_str(),
ros::Time(0), transform);
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s",ex.what());
know_sensor_pose = false;
ros::Duration(1.0).sleep();
}
if (know_sensor_pose)
{
//Current sensor pose
float x_pos = transform.getOrigin().x();
float y_pos = transform.getOrigin().y();
float z_pos = transform.getOrigin().z();
//ROS_INFO("[fake anemometer]: loc x y z: %f, %f, %f", x_pos, y_pos, z_pos);
// Get Wind vectors (u,v,w) at current position
// Service request to the simulator
gaden_player::WindPosition srv;
srv.request.x.push_back(x_pos);
srv.request.y.push_back(y_pos);
srv.request.z.push_back(z_pos);
float u,v,w;
olfaction_msgs::anemometer anemo_msg;
if (client.call(srv))
{
double wind_speed;
double wind_direction;
//GT Wind vector Value (u,v,w)[m/s]
//From OpenFoam this is the DownWind direction in the map
u = (float)srv.response.u[0];
v = (float)srv.response.v[0];
w = (float)srv.response.w[0];
wind_speed = sqrt(pow(u,2)+pow(v,2));
//ROS_INFO("[fake anemometer]: U V W: [%f, %f, %f]", u, v, w);
float downWind_direction_map;
if (u !=0 || v!=0)
downWind_direction_map = atan2(v,u);
else
downWind_direction_map = 0.0;
if (!use_map_ref_system)
{
// (IMPORTANT) Follow standards on wind measurement (real anemometers):
//return the upwind direction in the anemometer reference system
//range [-pi,pi]
//positive to the right, negative to the left (opposed to ROS poses :s)
float upWind_direction_map = angles::normalize_angle(downWind_direction_map + 3.14159);
//Transform from map ref_system to the anemometer ref_system using TF
geometry_msgs::PoseStamped anemometer_upWind_pose, map_upWind_pose;
try
{
map_upWind_pose.header.frame_id = input_fixed_frame.c_str();
map_upWind_pose.pose.position.x = 0.0;
map_upWind_pose.pose.position.y = 0.0;
map_upWind_pose.pose.position.z = 0.0;
map_upWind_pose.pose.orientation = tf::createQuaternionMsgFromYaw(upWind_direction_map);
tf_.transformPose(input_sensor_frame.c_str(), map_upWind_pose, anemometer_upWind_pose);
}
catch(tf::TransformException &ex)
{
ROS_ERROR("FakeAnemometer - %s - Error: %s", __FUNCTION__, ex.what());
}
double upwind_direction_anemo = tf::getYaw(anemometer_upWind_pose.pose.orientation);
wind_direction = upwind_direction_anemo;
}
else
{
// for simulations
wind_direction = angles::normalize_angle(downWind_direction_map);
}
// Adding Noise
static RandomGenerator rng(static_cast<unsigned> (time(0)));
NormalDistribution gaussian_dist(0.0,noise_std);
GaussianGenerator generator(rng, gaussian_dist);
wind_direction = wind_direction + generator();
wind_speed = wind_speed + generator();
//Publish 2D Anemometer readings
//------------------------------
anemo_msg.header.stamp = ros::Time::now();
if (use_map_ref_system)
anemo_msg.header.frame_id = input_fixed_frame.c_str();
else
anemo_msg.header.frame_id = input_sensor_frame.c_str();
anemo_msg.sensor_label = "Fake_Anemo";
anemo_msg.wind_direction = wind_direction; //rad
anemo_msg.wind_speed = wind_speed; //m/s
//Publish fake_anemometer reading (m/s)
sensor_read_pub.publish(anemo_msg);
//Add wind marker ARROW for Rviz (2D) --> Upwind
/*
wind_point.header.stamp = ros::Time::now();
wind_point.points.clear();
wind_point.id = 1; //unique identifier for each arrow
wind_point.pose.position.x = 0.0;
wind_point.pose.position.y = 0.0;
wind_point.pose.position.z = 0.0;
wind_point.pose.orientation = tf::createQuaternionMsgFromYaw(wind_direction_with_noise);
wind_point.scale.x = 2*sqrt(pow(u,2)+pow(v,2)); //arrow lenght
wind_point.scale.y = 0.1; //arrow width
wind_point.scale.z = 0.1; //arrow height
wind_point.color.r = 0.0;
wind_point.color.g = 1.0;
wind_point.color.b = 0.0;
wind_point.color.a = 1.0;
marker_pub.publish(wind_point);
*/
//Add inverted wind marker --> DownWind
wind_point_inv.header.stamp = ros::Time::now();
wind_point_inv.header.frame_id=anemo_msg.header.frame_id;
wind_point_inv.points.clear();
wind_point_inv.id = 1; //unique identifier for each arrow
if(use_map_ref_system){
wind_point_inv.pose.position.x = x_pos;
wind_point_inv.pose.position.y = y_pos;
wind_point_inv.pose.position.z = z_pos;
}else{
wind_point_inv.pose.position.x = 0.0;
wind_point_inv.pose.position.y = 0.0;
wind_point_inv.pose.position.z = 0.0;
}
wind_point_inv.pose.orientation = tf::createQuaternionMsgFromYaw(wind_direction+3.1416);
// ROS_INFO("[fake anemometer]: wind readings u v: %f, %f", u, v);
wind_point_inv.scale.x = 2*sqrt(pow(u,2)+pow(v,2)); //arrow lenght
wind_point_inv.scale.y = 0.1; //arrow width
wind_point_inv.scale.z = 0.1; //arrow height
wind_point_inv.color.r = 0.0;
wind_point_inv.color.g = 1.0;
wind_point_inv.color.b = 0.0;
wind_point_inv.color.a = 1.0;
marker_pub.publish(wind_point_inv);
notified = false;
}
else
{
if (!notified)
{
ROS_WARN("[fake_anemometer] Cannot read Wind Vector from simulated data.");
notified = true;
}
}
//Publish RVIZ sensor pose (a sphere)
/*
sensor.header.stamp = ros::Time::now();
sensor.pose.position.x = x_pos;
sensor.pose.position.y = y_pos;
sensor.pose.position.z = z_pos;
marker_pub.publish(sensor);
*/
// PUBLISH ANEMOMETER Stick
/*
connector.header.stamp = ros::Time::now();
connector.scale.z = z_pos;
connector.pose.position.x = x_pos;
connector.pose.position.y = y_pos;
connector.pose.position.z = float(z_pos)/2;
marker_pub.publish(connector);
*/
}
ros::spinOnce();
r.sleep();
}
}
//Load Sensor parameters
void loadNodeParameters(ros::NodeHandle private_nh)
{
//sensor_frame
private_nh.param<std::string>("sensor_frame", input_sensor_frame, "anemometer_link");
//fixed frame
private_nh.param<std::string>("fixed_frame", input_fixed_frame, "map");
//Noise
private_nh.param<double>("noise_std", noise_std, 0.1);
//What ref system to use for publishing measurements
private_nh.param<bool>("use_map_ref_system", use_map_ref_system, false);
ROS_INFO("[fake anemometer]: wind noise: %f", noise_std);
}
| 10,648 | C++ | 32.487421 | 112 | 0.590627 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_environment/package.xml | <package>
<name>gaden_environment</name>
<version>1.0.0</version>
<description>Package for visualizing on RVIZ the simulation environment (walls, obstacles and gas source).</description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<!-- Dependencies which this package needs to build itself. -->
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>visualization_msgs</build_depend>
<build_depend>tf</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>geometry_msgs</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>visualization_msgs</run_depend>
<run_depend>tf</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>geometry_msgs</run_depend>
</package>
| 928 | XML | 33.407406 | 122 | 0.727371 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_environment/src/environment.cpp | /*
* The only goal of this Node is to display the simulation environment and gas source location in RVIZ.
*
* 1. Loads the simulation environment (usually from CFD in the file format .env), and displays it as RVIZ markers.
* 2. Displays the Gas-Source Location as two cylinders.
*/
#include "environment/environment.h"
// ===============================//
// MAIN //
// ===============================//
int main( int argc, char** argv )
{
//Init
ros::init(argc, argv, "environment");
Environment environment;
//Load Parameters
environment.run();
}
void Environment::run()
{
ros::NodeHandle n;
ros::NodeHandle pnh("~");
loadNodeParameters(pnh);
// Publishers
ros::Publisher gas_source_pub = n.advertise<visualization_msgs::MarkerArray>("source_visualization", 10);
ros::Publisher environmnet_pub = n.advertise<visualization_msgs::MarkerArray>("environment_visualization", 100);
ros::Publisher environmnet_cad_pub = n.advertise<visualization_msgs::MarkerArray>("environment_cad_visualization", 100);
ros::ServiceServer occupancyMapService = n.advertiseService("gaden_environment/occupancyMap3D", &Environment::occupancyMapServiceCB, this);
// Subscribers
preprocessing_done =false;
ros::Subscriber sub = n.subscribe("preprocessing_done", 1, &Environment::PreprocessingCB, this);
// 1. ENVIRONMNET AS CAD MODELS
//-------------------------------
visualization_msgs::MarkerArray CAD_model_markers;
for (int i=0;i<number_of_CAD;i++)
{
// CAD model in Collada (.dae) format
visualization_msgs::Marker cad;
cad.header.frame_id = fixed_frame;
cad.header.stamp = ros::Time::now();
cad.ns = "part_" + std::to_string(i);
cad.id = i;
cad.type = visualization_msgs::Marker::MESH_RESOURCE;
cad.action = visualization_msgs::Marker::ADD;
cad.mesh_resource = CAD_models[i];
cad.scale.x = 1.0;
cad.scale.y = 1.0;
cad.scale.z = 1.0;
cad.pose.position.x = 0.0; //CAD models have the object pose within the file!
cad.pose.position.y = 0.0;
cad.pose.position.z = 0.0;
cad.pose.orientation.x = 0.0;
cad.pose.orientation.y = 0.0;
cad.pose.orientation.z = 0.0;
cad.pose.orientation.w = 1.0;
//Color (Collada has no color)
cad.color.r = CAD_color[i][0];
cad.color.g = CAD_color[i][1];
cad.color.b = CAD_color[i][2];
cad.color.a = 1.0;
//Add Marker to array
CAD_model_markers.markers.push_back(cad);
}
// 2. ENVIRONMNET AS Occupancy3D file
//------------------------------------
//Display Environment as an array of Cube markers (Rviz)
visualization_msgs::MarkerArray environment;
if (occupancy3D_data != "")
loadEnvironment(environment);
if (verbose) ROS_INFO("[env]loadEnvironment completed, line 85");
// 3. GAS SOURCES
//----------------
//Generate Gas Source Markers
//The shape are cylinders from the floor to the given z_size.
visualization_msgs::MarkerArray gas_source_markers;
for (int i=0;i<number_of_sources;i++)
{
visualization_msgs::Marker source;
source.header.frame_id = fixed_frame;
source.header.stamp = ros::Time::now();
source.id = i;
source.ns = "gas_source_visualization";
source.action = visualization_msgs::Marker::ADD;
//source.type = visualization_msgs::Marker::CYLINDER;
source.type = visualization_msgs::Marker::CUBE;
source.scale.x = gas_source_scale[i];
source.scale.y = gas_source_scale[i];
source.scale.z = gas_source_pos_z[i];
source.color.r = gas_source_color[i][0];
source.color.g = gas_source_color[i][1];
source.color.b = gas_source_color[i][2];
source.color.a = 1.0;
source.pose.position.x = gas_source_pos_x[i];
source.pose.position.y = gas_source_pos_y[i];
source.pose.position.z = gas_source_pos_z[i]/2;
source.pose.orientation.x = 0.0;
source.pose.orientation.y = 0.0;
source.pose.orientation.z = 1.0;
source.pose.orientation.w = 1.0;
//Add Marker to array
gas_source_markers.markers.push_back(source);
}
// Small sleep to allow RVIZ to startup
ros::Duration(1.0).sleep();
//---------------
// LOOP
//---------------
ros::Rate r(0.3); //Just to refresh from time to time
while (ros::ok())
{
//Publish CAD Markers
environmnet_cad_pub.publish(CAD_model_markers);
// Publish 3D Occupancy
if (occupancy3D_data != "")
environmnet_pub.publish(environment);
//Publish Gas Sources
gas_source_pub.publish(gas_source_markers);
ros::spinOnce();
r.sleep();
}
}
// ===============================//
// Load Node parameters //
// ===============================//
void Environment::loadNodeParameters(ros::NodeHandle private_nh)
{
private_nh.param<bool>("verbose", verbose, false);
if (verbose) ROS_INFO("[env] The data provided in the roslaunch file is:");
private_nh.param<bool>("wait_preprocessing", wait_preprocessing, false);
if (verbose) ROS_INFO("[env] wait_preprocessing: %u",wait_preprocessing);
private_nh.param<std::string>("fixed_frame", fixed_frame, "map");
if (verbose) ROS_INFO("[env] Fixed Frame: %s",fixed_frame.c_str());
private_nh.param<int>("number_of_sources", number_of_sources, 0);
if (verbose) ROS_INFO("[env] number_of_sources: %i",number_of_sources);
gas_source_pos_x.resize(number_of_sources);
gas_source_pos_y.resize(number_of_sources);
gas_source_pos_z.resize(number_of_sources);
gas_source_scale.resize(number_of_sources);
gas_source_color.resize(number_of_sources);
for(int i=0;i<number_of_sources;i++)
{
//Get location of soruce for instance (i)
std::string paramNameX = boost::str( boost::format("source_%i_position_x") % i);
std::string paramNameY = boost::str( boost::format("source_%i_position_y") % i);
std::string paramNameZ = boost::str( boost::format("source_%i_position_z") % i);
std::string scale = boost::str( boost::format("source_%i_scale") % i);
std::string color = boost::str( boost::format("source_%i_color") % i);
private_nh.param<double>(paramNameX.c_str(), gas_source_pos_x[i], 0.0);
private_nh.param<double>(paramNameY.c_str(), gas_source_pos_y[i], 0.0);
private_nh.param<double>(paramNameZ.c_str(), gas_source_pos_z[i], 0.0);
private_nh.param<double>(scale.c_str(), gas_source_scale[i], 0.1);
gas_source_color[i].resize(3);
private_nh.getParam(color.c_str(),gas_source_color[i]);
if (verbose) ROS_INFO("[env] Gas_source(%i): pos=[%0.2f %0.2f %0.2f] scale=%.2f color=[%0.2f %0.2f %0.2f]",
i, gas_source_pos_x[i], gas_source_pos_y[i], gas_source_pos_z[i],
gas_source_scale[i],
gas_source_color[i][0],gas_source_color[i][1],gas_source_color[i][2]);
}
// CAD MODELS
//-------------
//CAD model files
private_nh.param<int>("number_of_CAD", number_of_CAD, 0);
if (verbose) ROS_INFO("[env] number_of_CAD: %i",number_of_CAD);
CAD_models.resize(number_of_CAD);
CAD_color.resize(number_of_CAD);
for(int i=0;i<number_of_CAD;i++)
{
//Get location of CAD file for instance (i)
std::string paramName = boost::str( boost::format("CAD_%i") % i);
std::string paramColor = boost::str( boost::format("CAD_%i_color") % i);
private_nh.param<std::string>(paramName.c_str(), CAD_models[i], "");
CAD_color[i].resize(3);
private_nh.getParam(paramColor.c_str(),CAD_color[i]);
if (verbose) ROS_INFO("[env] CAD_models(%i): %s",i, CAD_models[i].c_str());
}
//Occupancy 3D gridmap
//---------------------
private_nh.param<std::string>("occupancy3D_data", occupancy3D_data, "");
if (verbose) ROS_INFO("[env] Occupancy3D file location: %s",occupancy3D_data.c_str());
}
//=========================//
// PreProcessing CallBack //
//=========================//
void Environment::PreprocessingCB(const std_msgs::Bool& b)
{
preprocessing_done = true;
}
void Environment::readEnvFile()
{
if(occupancy3D_data==""){
ROS_ERROR(" [GADEN_PLAYER] No occupancy file specified. Use the parameter \"occupancyFile\" to input the path to the OccupancyGrid3D.csv file.\n");
return;
}
//open file
std::ifstream infile(occupancy3D_data.c_str());
std::string line;
//read the header
{
//Line 1 (min values of environment)
std::getline(infile, line);
size_t pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_min_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_min_y = atof(line.substr(0, pos).c_str());
env_min_z = atof(line.substr(pos+1).c_str());
//Line 2 (max values of environment)
std::getline(infile, line);
pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_max_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_max_y = atof(line.substr(0, pos).c_str());
env_max_z = atof(line.substr(pos+1).c_str());
//Line 3 (Num cells on eahc dimension)
std::getline(infile, line);
pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_cells_x = atoi(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_cells_y = atof(line.substr(0, pos).c_str());
env_cells_z = atof(line.substr(pos+1).c_str());
//Line 4 cell_size (m)
std::getline(infile, line);
pos = line.find(" ");
cell_size = atof(line.substr(pos+1).c_str());
if (verbose) ROS_INFO("[env]Env dimensions (%.2f,%.2f,%.2f)-(%.2f,%.2f,%.2f)",env_min_x, env_min_y, env_min_z, env_max_x, env_max_y, env_max_z );
if (verbose) ROS_INFO("[env]Env size in cells (%d,%d,%d) - with cell size %f [m]",env_cells_x,env_cells_y,env_cells_z, cell_size);
}
Env.resize(env_cells_x * env_cells_y * env_cells_z);
if (verbose) ROS_INFO("[env]Env.resize command, line 283");
int x_idx = 0;
int y_idx = 0;
int z_idx = 0;
while ( std::getline(infile, line) )
{
std::stringstream ss(line);
if (z_idx >=env_cells_z)
{
ROS_ERROR("Trying to read:[%s]",line.c_str());
}
if (line == ";")
{
if (verbose) ROS_INFO("[env] z_idx: %d", z_idx);
//New Z-layer
z_idx++;
x_idx = 0;
y_idx = 0;
}
else
{ //New line with constant x_idx and all the y_idx values
while (ss)
{
int f;
ss >> std::skipws >> f;
Env[indexFrom3D(x_idx,y_idx,z_idx)] = f;
y_idx++;
}
//Line has ended
x_idx++;
if (verbose) ROS_INFO("[env] x_idx: %d", x_idx);
y_idx = 0;
}
}
if (verbose) ROS_INFO("[env]before infile.close line 327");
infile.close();
if (verbose) ROS_INFO("[env]after infile.close line 329");
}
/* Load environment from 3DOccupancy.csv GridMap
* Loads the environment file containing a description of the simulated environment in the CFD (for the estimation of the wind flows), and displays it.
* As a general rule, environment files set a value of "0" for a free cell, "1" for a ocuppiedd cell and "2" for outlet.
* This function creates a cube marker for every occupied cell, with the corresponding dimensions
*/
void Environment::loadEnvironment(visualization_msgs::MarkerArray &env_marker)
{
// Wait for the GADEN_preprocessin node to finish?
if( wait_preprocessing )
{
while(ros::ok() && !preprocessing_done)
{
ros::Duration(0.5).sleep();
ros::spinOnce();
if (verbose) ROS_INFO("[environment] Waiting for node GADEN_preprocessing to end.");
}
}
readEnvFile();
if (verbose) ROS_INFO("[env]readEnvFile completed, line 342");
for ( int i = 0; i<env_cells_x; i++)
{
for ( int j = 0; j<env_cells_y; j++)
{
for ( int k = 0; k<env_cells_z; k++)
{
//Color
if (!Env[indexFrom3D(i,j,k)])
{
//Add a new cube marker for this occupied cell
visualization_msgs::Marker new_marker;
new_marker.header.frame_id = fixed_frame;
new_marker.header.stamp = ros::Time::now();
new_marker.ns = "environment_visualization";
new_marker.id = indexFrom3D(i,j,k); //unique identifier
new_marker.type = visualization_msgs::Marker::CUBE;
new_marker.action = visualization_msgs::Marker::ADD;
//Center of the cell
new_marker.pose.position.x = env_min_x + ( (i + 0.5) * cell_size);
new_marker.pose.position.y = env_min_y + ( (j + 0.5) * cell_size);
new_marker.pose.position.z = env_min_z + ( (k + 0.5) * cell_size);
new_marker.pose.orientation.x = 0.0;
new_marker.pose.orientation.y = 0.0;
new_marker.pose.orientation.z = 0.0;
new_marker.pose.orientation.w = 1.0;
//Size of the cell
new_marker.scale.x = cell_size;
new_marker.scale.y = cell_size;
new_marker.scale.z = cell_size;
new_marker.color.r = 0.9f;
new_marker.color.g = 0.1f;
new_marker.color.b = 0.1f;
new_marker.color.a = 1.0;
env_marker.markers.push_back(new_marker);
}
}
}
}
}
bool Environment::occupancyMapServiceCB(gaden_environment::OccupancyRequest& request, gaden_environment::OccupancyResponse& response)
{
response.origin.x = env_min_x;
response.origin.y = env_min_y;
response.origin.z = env_min_z;
response.numCellsX = env_cells_x;
response.numCellsY = env_cells_y;
response.numCellsZ = env_cells_z;
response.resolution = cell_size;
response.occupancy = Env;
return true;
}
int Environment::indexFrom3D(int x, int y, int z){
return x + y*env_cells_x + z*env_cells_x*env_cells_y;
}
| 14,700 | C++ | 34.509662 | 155 | 0.566599 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_environment/include/environment/environment.h | #pragma once
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
#include <resource_retriever/retriever.h>
#include <cmath>
#include <vector>
#include <fstream>
#include <boost/format.hpp>
#include <gaden_environment/Occupancy.h>
class Environment
{
public:
void run();
private:
//Gas Sources
int number_of_sources;
std::vector<double> gas_source_pos_x;
std::vector<double> gas_source_pos_y;
std::vector<double> gas_source_pos_z;
std::vector<double> gas_source_scale;
std::vector< std::vector<double> > gas_source_color;
//CAD models
int number_of_CAD;
std::vector<std::string> CAD_models;
std::vector< std::vector<double> > CAD_color;
//Environment 3D
std::vector<uint8_t> Env;
std::string occupancy3D_data; //Location of the 3D Occupancy GridMap of the environment
std::string fixed_frame; //Frame where to publish the markers
int env_cells_x; //cells
int env_cells_y; //cells
int env_cells_z; //cells
double env_min_x; //[m]
double env_max_x; //[m]
double env_min_y; //[m]
double env_max_y; //[m]
double env_min_z; //[m]
double env_max_z; //[m]
double cell_size; //[m]
bool verbose;
bool wait_preprocessing;
bool preprocessing_done;
//Methods
void loadNodeParameters(ros::NodeHandle);
void loadEnvironment(visualization_msgs::MarkerArray &env_marker);
void readEnvFile();
bool occupancyMapServiceCB(gaden_environment::OccupancyRequest& request, gaden_environment::OccupancyResponse& response);
int indexFrom3D(int x, int y, int z);
void PreprocessingCB(const std_msgs::Bool& b);
};
| 2,074 | C | 31.936507 | 125 | 0.562681 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package map_server
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.17.3 (2023-01-10)
-------------------
* [ROS-O] various patches (`#1225 <https://github.com/ros-planning/navigation/issues/1225>`_)
* do not specify obsolete c++11 standard
this breaks with current versions of log4cxx.
* update pluginlib include paths
the non-hpp headers have been deprecated since kinetic
* use lambdas in favor of boost::bind
Using boost's _1 as a global system is deprecated since C++11.
The ROS packages in Debian removed the implicit support for the global symbols,
so this code fails to compile there without the patch.
* Contributors: Michael Görner
1.17.2 (2022-06-20)
-------------------
* Change_map service to map_server [Rebase/Noetic] (`#1029 <https://github.com/ros-planning/navigation/issues/1029>`_)
* Refactored map loading from constructor to three methods
* Added change_map service using LoadMap.srv
* map_server: Initialise a NodeHandle in main. (`#1122 <https://github.com/ros-planning/navigation/issues/1122>`_)
* Add debug output regarding waiting for time (`#1078 <https://github.com/ros-planning/navigation/issues/1078>`_)
Added debug messages suggested in https://github.com/ros-planning/navigation/issues/1074#issuecomment-751557177. Makes it easier to discover if use_sim_time is true but no clock server is running
* crop_map: Fix extra pixel origin shift up every cropping (`#1064 <https://github.com/ros-planning/navigation/issues/1064>`_) (`#1067 <https://github.com/ros-planning/navigation/issues/1067>`_)
Co-authored-by: Pavlo Kolomiiets <[email protected]>
* (map_server) add rtest dependency to tests (`#1061 <https://github.com/ros-planning/navigation/issues/1061>`_)
* [noetic] MapServer variable cleanup: Precursor for `#1029 <https://github.com/ros-planning/navigation/issues/1029>`_ (`#1043 <https://github.com/ros-planning/navigation/issues/1043>`_)
* Contributors: Christian Fritz, David V. Lu!!, Matthijs van der Burgh, Nikos Koukis, Pavlo Kolomiiets
1.17.1 (2020-08-27)
-------------------
* Initial map_server map_mode tests (`#1006 <https://github.com/ros-planning/navigation/issues/1006>`_)
* [noetic] Adding CMake way to find yaml-cpp (`#998 <https://github.com/ros-planning/navigation/issues/998>`_)
* Contributors: David V. Lu!!, Sean Yen
1.17.0 (2020-04-02)
-------------------
* Merge pull request `#982 <https://github.com/ros-planning/navigation/issues/982>`_ from ros-planning/noetic_prep
Noetic Migration
* increase required cmake version
* Contributors: Michael Ferguson
1.16.6 (2020-03-18)
-------------------
1.16.5 (2020-03-15)
-------------------
* [melodic] updated install for better portability. (`#973 <https://github.com/ros-planning/navigation/issues/973>`_)
* Contributors: Sean Yen
1.16.4 (2020-03-04)
-------------------
1.16.3 (2019-11-15)
-------------------
* Merge branch 'melodic-devel' into layer_clear_area-melodic
* Merge pull request `#850 <https://github.com/ros-planning/navigation/issues/850>`_ from seanyen/map_server_windows_fix
[Windows][melodic] map_server Windows build bring up
* map_server Windows build bring up
* Fix install location for Windows build. (On Windows build, shared library uses RUNTIME location, but not LIBRARY)
* Use boost::filesystem::path to handle path logic and remove the libgen.h dependency for better cross platform.
* Fix gtest hard-coded and add YAML library dir in CMakeList.txt.
* Contributors: Michael Ferguson, Sean Yen, Steven Macenski
1.16.2 (2018-07-31)
-------------------
1.16.1 (2018-07-28)
-------------------
1.16.0 (2018-07-25)
-------------------
* Merge pull request `#735 <https://github.com/ros-planning/navigation/issues/735>`_ from ros-planning/melodic_708
Allow specification of free/occupied thresholds for map_saver (`#708 <https://github.com/ros-planning/navigation/issues/708>`_)
* Allow specification of free/occupied thresholds for map_saver (`#708 <https://github.com/ros-planning/navigation/issues/708>`_)
* add occupied threshold command line parameter to map_saver (--occ)
* add free threshold command line parameter to map_saver (--free)
* Merge pull request `#704 <https://github.com/ros-planning/navigation/issues/704>`_ from DLu/fix573_lunar
Map server wait for a valid time fix [lunar]
* Map server wait for a valid time, fix `#573 <https://github.com/ros-planning/navigation/issues/573>`_ (`#700 <https://github.com/ros-planning/navigation/issues/700>`_)
When launching the map_server with Gazebo, the current time is picked
before the simulation is started and then has a value of 0.
Later when querying the stamp of the map, a value of has a special
signification on tf transform for example.
* Contributors: Michael Ferguson, Romain Reignier, ipa-fez
1.15.2 (2018-03-22)
-------------------
* Merge pull request `#673 <https://github.com/ros-planning/navigation/issues/673>`_ from ros-planning/email_update_lunar
update maintainer email (lunar)
* Merge pull request `#649 <https://github.com/ros-planning/navigation/issues/649>`_ from aaronhoy/lunar_add_ahoy
Add myself as a maintainer.
* Rebase PRs from Indigo/Kinetic (`#637 <https://github.com/ros-planning/navigation/issues/637>`_)
* Respect planner_frequency intended behavior (`#622 <https://github.com/ros-planning/navigation/issues/622>`_)
* Only do a getRobotPose when no start pose is given (`#628 <https://github.com/ros-planning/navigation/issues/628>`_)
Omit the unnecessary call to getRobotPose when the start pose was
already given, so that move_base can also generate a path in
situations where getRobotPose would fail.
This is actually to work around an issue of getRobotPose randomly
failing.
* Update gradient_path.cpp (`#576 <https://github.com/ros-planning/navigation/issues/576>`_)
* Update gradient_path.cpp
* Update navfn.cpp
* update to use non deprecated pluginlib macro (`#630 <https://github.com/ros-planning/navigation/issues/630>`_)
* update to use non deprecated pluginlib macro
* multiline version as well
* Print SDL error on IMG_Load failure in server_map (`#631 <https://github.com/ros-planning/navigation/issues/631>`_)
* Use occupancy values when saving a map (`#613 <https://github.com/ros-planning/navigation/issues/613>`_)
* Closes `#625 <https://github.com/ros-planning/navigation/issues/625>`_ (`#627 <https://github.com/ros-planning/navigation/issues/627>`_)
* Contributors: Aaron Hoy, David V. Lu!!, Hunter Allen, Michael Ferguson
1.15.1 (2017-08-14)
-------------------
* remove offending library export (fixes `#612 <https://github.com/ros-planning/navigation/issues/612>`_)
* Contributors: Michael Ferguson
1.15.0 (2017-08-07)
-------------------
* Fix compiler warning for GCC 8.
* convert packages to format2
* Merge pull request `#596 <https://github.com/ros-planning/navigation/issues/596>`_ from ros-planning/lunar_548
* refactor to not use tf version 1 (`#561 <https://github.com/ros-planning/navigation/issues/561>`_)
* Fix CMakeLists + package.xmls (`#548 <https://github.com/ros-planning/navigation/issues/548>`_)
* Merge pull request `#560 <https://github.com/ros-planning/navigation/issues/560>`_ from wjwwood/map_server_fixup_cmake
* update to support Python 2 and 3 (`#559 <https://github.com/ros-planning/navigation/issues/559>`_)
* remove duplicate and unreferenced file (`#558 <https://github.com/ros-planning/navigation/issues/558>`_)
* remove trailing whitespace from map_server package (`#557 <https://github.com/ros-planning/navigation/issues/557>`_)
* fix cmake use of yaml-cpp and sdl / sdl-image
* Fix CMake warnings
* Contributors: Hunter L. Allen, Martin Günther, Michael Ferguson, Mikael Arguedas, Vincent Rabaud, William Woodall
1.14.0 (2016-05-20)
-------------------
* Corrections to alpha channel detection and usage.
Changing to actually detect whether the image has an alpha channel instead of
inferring based on the number of channels.
Also reverting to legacy behavior of trinary mode overriding alpha removal.
This will cause the alpha channel to be averaged in with the others in trinary
mode, which is the current behavior before this PR.
* Removing some trailing whitespace.
* Use enum to control map interpretation
* Contributors: Aaron Hoy, David Lu
1.13.1 (2015-10-29)
-------------------
1.13.0 (2015-03-17)
-------------------
* rename image_loader library, fixes `#208 <https://github.com/ros-planning/navigation/issues/208>`_
* Contributors: Michael Ferguson
1.12.0 (2015-02-04)
-------------------
* update maintainer email
* Contributors: Michael Ferguson
1.11.15 (2015-02-03)
--------------------
1.11.14 (2014-12-05)
--------------------
* prevent inf loop
* Contributors: Jeremie Deray
1.11.13 (2014-10-02)
--------------------
1.11.12 (2014-10-01)
--------------------
* map_server: [style] alphabetize dependencies
* map_server: remove vestigial export line
the removed line does not do anything in catkin
* Contributors: William Woodall
1.11.11 (2014-07-23)
--------------------
1.11.10 (2014-06-25)
--------------------
1.11.9 (2014-06-10)
-------------------
1.11.8 (2014-05-21)
-------------------
* fix build, was broken by `#175 <https://github.com/ros-planning/navigation/issues/175>`_
* Contributors: Michael Ferguson
1.11.7 (2014-05-21)
-------------------
* make rostest in CMakeLists optional
* Contributors: Lukas Bulwahn
1.11.5 (2014-01-30)
-------------------
* install crop map
* removing .py from executable script
* Map Server can serve maps with non-lethal values
* Added support for YAML-CPP 0.5+.
The new yaml-cpp API removes the "node >> outputvar;" operator, and
it has a new way of loading documents. There's no version hint in the
library's headers, so I'm getting the version number from pkg-config.
* check for CATKIN_ENABLE_TESTING
* Change maintainer from Hersh to Lu
1.11.4 (2013-09-27)
-------------------
* prefix utest target to not collide with other targets
* Package URL Updates
* unique target names to avoid conflicts (e.g. with map-store)
| 10,034 | reStructuredText | 46.112676 | 197 | 0.70012 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/rtest.cpp | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Author: Brian Gerkey */
#include <gtest/gtest.h>
#include <ros/service.h>
#include <ros/ros.h>
#include <ros/package.h>
#include <nav_msgs/GetMap.h>
#include <nav_msgs/OccupancyGrid.h>
#include <nav_msgs/MapMetaData.h>
#include <nav_msgs/LoadMap.h>
#include "test_constants.h"
int g_argc;
char** g_argv;
class MapClientTest : public testing::Test
{
public:
// A node is needed to make a service call
ros::NodeHandle* n_;
MapClientTest()
{
ros::init(g_argc, g_argv, "map_client_test");
n_ = new ros::NodeHandle();
got_map_ = false;
got_map_metadata_ = false;
}
~MapClientTest()
{
delete n_;
}
bool got_map_;
boost::shared_ptr<nav_msgs::OccupancyGrid const> map_;
void mapCallback(const boost::shared_ptr<nav_msgs::OccupancyGrid const>& map)
{
map_ = map;
got_map_ = true;
}
bool got_map_metadata_;
boost::shared_ptr<nav_msgs::MapMetaData const> map_metadata_;
void mapMetaDataCallback(const boost::shared_ptr<nav_msgs::MapMetaData const>& map_metadata)
{
map_metadata_ = map_metadata;
got_map_metadata_ = true;
}
};
/* Try to retrieve the map via service, and compare to ground truth */
TEST_F(MapClientTest, call_service)
{
nav_msgs::GetMap::Request req;
nav_msgs::GetMap::Response resp;
ASSERT_TRUE(ros::service::waitForService("static_map", 5000));
ASSERT_TRUE(ros::service::call("static_map", req, resp));
ASSERT_FLOAT_EQ(resp.map.info.resolution, g_valid_image_res);
ASSERT_EQ(resp.map.info.width, g_valid_image_width);
ASSERT_EQ(resp.map.info.height, g_valid_image_height);
ASSERT_STREQ(resp.map.header.frame_id.c_str(), "map");
for(unsigned int i=0; i < resp.map.info.width * resp.map.info.height; i++)
ASSERT_EQ(g_valid_image_content[i], resp.map.data[i]);
}
/* Try to retrieve the map via topic, and compare to ground truth */
TEST_F(MapClientTest, subscribe_topic)
{
ros::Subscriber sub = n_->subscribe<nav_msgs::OccupancyGrid>("map", 1, [this](auto& map){ mapCallback(map); });
// Try a few times, because the server may not be up yet.
int i=20;
while(!got_map_ && i > 0)
{
ros::spinOnce();
ros::Duration d = ros::Duration().fromSec(0.25);
d.sleep();
i--;
}
ASSERT_TRUE(got_map_);
ASSERT_FLOAT_EQ(map_->info.resolution, g_valid_image_res);
ASSERT_EQ(map_->info.width, g_valid_image_width);
ASSERT_EQ(map_->info.height, g_valid_image_height);
ASSERT_STREQ(map_->header.frame_id.c_str(), "map");
for(unsigned int i=0; i < map_->info.width * map_->info.height; i++)
ASSERT_EQ(g_valid_image_content[i], map_->data[i]);
}
/* Try to retrieve the metadata via topic, and compare to ground truth */
TEST_F(MapClientTest, subscribe_topic_metadata)
{
ros::Subscriber sub = n_->subscribe<nav_msgs::MapMetaData>("map_metadata", 1, [this](auto& map_metadata){ mapMetaDataCallback(map_metadata); });
// Try a few times, because the server may not be up yet.
int i=20;
while(!got_map_metadata_ && i > 0)
{
ros::spinOnce();
ros::Duration d = ros::Duration().fromSec(0.25);
d.sleep();
i--;
}
ASSERT_TRUE(got_map_metadata_);
ASSERT_FLOAT_EQ(map_metadata_->resolution, g_valid_image_res);
ASSERT_EQ(map_metadata_->width, g_valid_image_width);
ASSERT_EQ(map_metadata_->height, g_valid_image_height);
}
/* Change the map, retrieve the map via topic, and compare to ground truth */
TEST_F(MapClientTest, change_map)
{
ros::Subscriber sub = n_->subscribe<nav_msgs::OccupancyGrid>("map", 1, [this](auto& map){ mapCallback(map); });
// Try a few times, because the server may not be up yet.
for (int i = 20; i > 0 && !got_map_; i--)
{
ros::spinOnce();
ros::Duration d = ros::Duration().fromSec(0.25);
d.sleep();
}
ASSERT_TRUE(got_map_);
// Now change the map
got_map_ = false;
nav_msgs::LoadMap::Request req;
nav_msgs::LoadMap::Response resp;
req.map_url = ros::package::getPath("map_server") + "/test/testmap2.yaml";
ASSERT_TRUE(ros::service::waitForService("change_map", 5000));
ASSERT_TRUE(ros::service::call("change_map", req, resp));
ASSERT_EQ(0u, resp.result);
for (int i = 20; i > 0 && !got_map_; i--)
{
ros::spinOnce();
ros::Duration d = ros::Duration().fromSec(0.25);
d.sleep();
}
ASSERT_FLOAT_EQ(tmap2::g_valid_image_res, map_->info.resolution);
ASSERT_EQ(tmap2::g_valid_image_width, map_->info.width);
ASSERT_EQ(tmap2::g_valid_image_height, map_->info.height);
ASSERT_STREQ("map", map_->header.frame_id.c_str());
for(unsigned int i=0; i < map_->info.width * map_->info.height; i++)
ASSERT_EQ(tmap2::g_valid_image_content[i], map_->data[i]) << "idx:" << i;
//Put the old map back so the next test isn't broken
got_map_ = false;
req.map_url = ros::package::getPath("map_server") + "/test/testmap.yaml";
ASSERT_TRUE(ros::service::call("change_map", req, resp));
ASSERT_EQ(0u, resp.result);
for (int i = 20; i > 0 && !got_map_; i--)
{
ros::spinOnce();
ros::Duration d = ros::Duration().fromSec(0.25);
d.sleep();
}
ASSERT_TRUE(got_map_);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
g_argc = argc;
g_argv = argv;
return RUN_ALL_TESTS();
}
| 6,837 | C++ | 33.361809 | 146 | 0.668568 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/testmap2.yaml | image: testmap2.png
resolution: 0.1
origin: [-2.0, -3.0, -1.0]
negate: 1
occupied_thresh: 0.5
free_thresh: 0.2
| 111 | YAML | 14.999998 | 26 | 0.675676 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/testmap.yaml | image: testmap.png
resolution: 0.1
origin: [2.0, 3.0, 1.0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196
| 110 | YAML | 14.857141 | 23 | 0.7 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/utest.cpp | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Author: Brian Gerkey */
#include <stdexcept> // for std::runtime_error
#include <gtest/gtest.h>
#include "map_server/image_loader.h"
#include "test_constants.h"
/* Try to load a valid PNG file. Succeeds if no exception is thrown, and if
* the loaded image matches the known dimensions and content of the file.
*
* This test can fail on OS X, due to an apparent limitation of the
* underlying SDL_Image library. */
TEST(MapServer, loadValidPNG)
{
try
{
nav_msgs::GetMap::Response map_resp;
double origin[3] = { 0.0, 0.0, 0.0 };
map_server::loadMapFromFile(&map_resp, g_valid_png_file, g_valid_image_res, false, 0.65, 0.1, origin);
EXPECT_FLOAT_EQ(map_resp.map.info.resolution, g_valid_image_res);
EXPECT_EQ(map_resp.map.info.width, g_valid_image_width);
EXPECT_EQ(map_resp.map.info.height, g_valid_image_height);
for(unsigned int i=0; i < map_resp.map.info.width * map_resp.map.info.height; i++)
EXPECT_EQ(g_valid_image_content[i], map_resp.map.data[i]);
}
catch(...)
{
ADD_FAILURE() << "Uncaught exception : " << "This is OK on OS X";
}
}
/* Try to load a valid BMP file. Succeeds if no exception is thrown, and if
* the loaded image matches the known dimensions and content of the file. */
TEST(MapServer, loadValidBMP)
{
try
{
nav_msgs::GetMap::Response map_resp;
double origin[3] = { 0.0, 0.0, 0.0 };
map_server::loadMapFromFile(&map_resp, g_valid_bmp_file, g_valid_image_res, false, 0.65, 0.1, origin);
EXPECT_FLOAT_EQ(map_resp.map.info.resolution, g_valid_image_res);
EXPECT_EQ(map_resp.map.info.width, g_valid_image_width);
EXPECT_EQ(map_resp.map.info.height, g_valid_image_height);
for(unsigned int i=0; i < map_resp.map.info.width * map_resp.map.info.height; i++)
EXPECT_EQ(g_valid_image_content[i], map_resp.map.data[i]);
}
catch(...)
{
ADD_FAILURE() << "Uncaught exception";
}
}
/* Try to load an invalid file. Succeeds if a std::runtime_error exception
* is thrown. */
TEST(MapServer, loadInvalidFile)
{
try
{
nav_msgs::GetMap::Response map_resp;
double origin[3] = { 0.0, 0.0, 0.0 };
map_server::loadMapFromFile(&map_resp, "foo", 0.1, false, 0.65, 0.1, origin);
}
catch(std::runtime_error &e)
{
SUCCEED();
return;
}
catch(...)
{
FAIL() << "Uncaught exception";
}
ADD_FAILURE() << "Didn't throw exception as expected";
}
std::vector<unsigned int> countValues(const nav_msgs::GetMap::Response& map_resp)
{
std::vector<unsigned int> counts(256, 0);
for (unsigned int i = 0; i < map_resp.map.data.size(); i++)
{
unsigned char value = static_cast<unsigned char>(map_resp.map.data[i]);
counts[value]++;
}
return counts;
}
TEST(MapServer, testMapMode)
{
nav_msgs::GetMap::Response map_resp;
double origin[3] = { 0.0, 0.0, 0.0 };
map_server::loadMapFromFile(&map_resp, g_spectrum_png_file, 0.1, false, 0.65, 0.1, origin, TRINARY);
std::vector<unsigned int> trinary_counts = countValues(map_resp);
EXPECT_EQ(90u, trinary_counts[100]);
EXPECT_EQ(26u, trinary_counts[0]);
EXPECT_EQ(140u, trinary_counts[255]);
map_server::loadMapFromFile(&map_resp, g_spectrum_png_file, 0.1, false, 0.65, 0.1, origin, SCALE);
std::vector<unsigned int> scale_counts = countValues(map_resp);
EXPECT_EQ(90u, scale_counts[100]);
EXPECT_EQ(26u, scale_counts[0]);
unsigned int scaled_values = 0;
for (unsigned int i = 1; i < 100; i++)
{
scaled_values += scale_counts[i];
}
EXPECT_EQ(140u, scaled_values);
map_server::loadMapFromFile(&map_resp, g_spectrum_png_file, 0.1, false, 0.65, 0.1, origin, RAW);
std::vector<unsigned int> raw_counts = countValues(map_resp);
for (unsigned int i = 0; i < raw_counts.size(); i++)
{
EXPECT_EQ(1u, raw_counts[i]) << i;
}
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 5,484 | C++ | 35.566666 | 106 | 0.684537 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/test_constants.cpp | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Author: Brian Gerkey */
/* This file contains global constants shared among tests */
/* Note that these must be changed if the test image changes */
#include "test_constants.h"
const unsigned int g_valid_image_width = 10;
const unsigned int g_valid_image_height = 10;
// Note that the image content is given in row-major order, with the
// lower-left pixel first. This is different from a graphics coordinate
// system, which starts with the upper-left pixel. The loadMapFromFile
// call converts from the latter to the former when it loads the image, and
// we want to compare against the result of that conversion.
const char g_valid_image_content[] = {
0,0,0,0,0,0,0,0,0,0,
100,100,100,100,0,0,100,100,100,0,
100,100,100,100,0,0,100,100,100,0,
100,0,0,0,0,0,0,0,0,0,
100,0,0,0,0,0,0,0,0,0,
100,0,0,0,0,0,100,100,0,0,
100,0,0,0,0,0,100,100,0,0,
100,0,0,0,0,0,100,100,0,0,
100,0,0,0,0,0,100,100,0,0,
100,0,0,0,0,0,0,0,0,0,
};
const char* g_valid_png_file = "test/testmap.png";
const char* g_valid_bmp_file = "test/testmap.bmp";
const char* g_spectrum_png_file = "test/spectrum.png";
const float g_valid_image_res = 0.1;
// Constants for testmap2
namespace tmap2
{
const char g_valid_image_content[] = {
100,100,100,100,100,100,100,100,100,100,100,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,100,100,100,100,100,100,100,100,0,100,
100,0,100,0,0,0,0,0,0,100,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,0,100,0,0,0,0,0,0,100,0,100,
100,0,0,0,0,0,0,0,0,0,0,100,
100,100,100,100,100,100,100,100,100,100,100,100,
};
const float g_valid_image_res = 0.1;
const unsigned int g_valid_image_width = 12;
const unsigned int g_valid_image_height = 12;
}
| 3,407 | C++ | 39.094117 | 78 | 0.709715 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/rtest.xml | <launch>
<node name="map_server" pkg="map_server" type="map_server" args="$(find map_server)/test/testmap.yaml"/>
<test test-name="map_server_test" pkg="map_server" type="rtest"/>
</launch>
| 197 | XML | 23.749997 | 106 | 0.670051 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/test_constants.h | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MAP_SERVER_TEST_CONSTANTS_H
#define MAP_SERVER_TEST_CONSTANTS_H
/* Author: Brian Gerkey */
/* This file externs global constants shared among tests */
extern const unsigned int g_valid_image_width;
extern const unsigned int g_valid_image_height;
extern const char g_valid_image_content[];
extern const char* g_valid_png_file;
extern const char* g_valid_bmp_file;
extern const float g_valid_image_res;
extern const char* g_spectrum_png_file;
namespace tmap2 {
extern const char g_valid_image_content[];
extern const float g_valid_image_res;
extern const unsigned int g_valid_image_width;
extern const unsigned int g_valid_image_height;
}
#endif
| 2,276 | C | 42.788461 | 78 | 0.755272 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/test/consumer.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Willow Garage nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
from __future__ import print_function
PKG = 'static_map_server'
NAME = 'consumer'
import sys
import unittest
import time
import rospy
import rostest
from nav_msgs.srv import GetMap
class TestConsumer(unittest.TestCase):
def __init__(self, *args):
super(TestConsumer, self).__init__(*args)
self.success = False
def callback(self, data):
print(rospy.get_caller_id(), "I heard %s" % data.data)
self.success = data.data and data.data.startswith('hello world')
rospy.signal_shutdown('test done')
def test_consumer(self):
rospy.wait_for_service('static_map')
mapsrv = rospy.ServiceProxy('static_map', GetMap)
resp = mapsrv()
self.success = True
print(resp)
while not rospy.is_shutdown() and not self.success: # and time.time() < timeout_t: <== timeout_t doesn't exists??
time.sleep(0.1)
self.assert_(self.success)
rospy.signal_shutdown('test done')
if __name__ == '__main__':
rostest.rosrun(PKG, NAME, TestConsumer, sys.argv)
| 2,688 | Python | 36.347222 | 122 | 0.718378 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/src/image_loader.cpp | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This file contains helper functions for loading images as maps.
*
* Author: Brian Gerkey
*/
#include <cstring>
#include <stdexcept>
#include <stdlib.h>
#include <stdio.h>
// We use SDL_image to load the image from disk
#include <SDL/SDL_image.h>
// Use Bullet's Quaternion object to create one from Euler angles
#include <LinearMath/btQuaternion.h>
#include "map_server/image_loader.h"
// compute linear index for given map coords
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
namespace map_server
{
void
loadMapFromFile(nav_msgs::GetMap::Response* resp,
const char* fname, double res, bool negate,
double occ_th, double free_th, double* origin,
MapMode mode)
{
SDL_Surface* img;
unsigned char* pixels;
unsigned char* p;
unsigned char value;
int rowstride, n_channels, avg_channels;
unsigned int i,j;
int k;
double occ;
int alpha;
int color_sum;
double color_avg;
// Load the image using SDL. If we get NULL back, the image load failed.
if(!(img = IMG_Load(fname)))
{
std::string errmsg = std::string("failed to open image file \"") +
std::string(fname) + std::string("\": ") + IMG_GetError();
throw std::runtime_error(errmsg);
}
// Copy the image data into the map structure
resp->map.info.width = img->w;
resp->map.info.height = img->h;
resp->map.info.resolution = res;
resp->map.info.origin.position.x = *(origin);
resp->map.info.origin.position.y = *(origin+1);
resp->map.info.origin.position.z = 0.0;
btQuaternion q;
// setEulerZYX(yaw, pitch, roll)
q.setEulerZYX(*(origin+2), 0, 0);
resp->map.info.origin.orientation.x = q.x();
resp->map.info.origin.orientation.y = q.y();
resp->map.info.origin.orientation.z = q.z();
resp->map.info.origin.orientation.w = q.w();
// Allocate space to hold the data
resp->map.data.resize(resp->map.info.width * resp->map.info.height);
// Get values that we'll need to iterate through the pixels
rowstride = img->pitch;
n_channels = img->format->BytesPerPixel;
// NOTE: Trinary mode still overrides here to preserve existing behavior.
// Alpha will be averaged in with color channels when using trinary mode.
if (mode==TRINARY || !img->format->Amask)
avg_channels = n_channels;
else
avg_channels = n_channels - 1;
// Copy pixel data into the map structure
pixels = (unsigned char*)(img->pixels);
for(j = 0; j < resp->map.info.height; j++)
{
for (i = 0; i < resp->map.info.width; i++)
{
// Compute mean of RGB for this pixel
p = pixels + j*rowstride + i*n_channels;
color_sum = 0;
for(k=0;k<avg_channels;k++)
color_sum += *(p + (k));
color_avg = color_sum / (double)avg_channels;
if (n_channels == 1)
alpha = 1;
else
alpha = *(p+n_channels-1);
if(negate)
color_avg = 255 - color_avg;
if(mode==RAW){
value = color_avg;
resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
continue;
}
// If negate is true, we consider blacker pixels free, and whiter
// pixels occupied. Otherwise, it's vice versa.
occ = (255 - color_avg) / 255.0;
// Apply thresholds to RGB means to determine occupancy values for
// map. Note that we invert the graphics-ordering of the pixels to
// produce a map with cell (0,0) in the lower-left corner.
if(occ > occ_th)
value = +100;
else if(occ < free_th)
value = 0;
else if(mode==TRINARY || alpha < 1.0)
value = -1;
else {
double ratio = (occ - free_th) / (occ_th - free_th);
value = 1 + 98 * ratio;
}
resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
}
}
SDL_FreeSurface(img);
}
}
| 5,472 | C++ | 31.969879 | 96 | 0.654971 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/src/map_saver.cpp | /*
* map_saver
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <ORGANIZATION> nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include "ros/ros.h"
#include "ros/console.h"
#include "nav_msgs/GetMap.h"
#include "tf2/LinearMath/Matrix3x3.h"
#include "geometry_msgs/Quaternion.h"
using namespace std;
/**
* @brief Map generation node.
*/
class MapGenerator
{
public:
MapGenerator(const std::string& mapname, int threshold_occupied, int threshold_free)
: mapname_(mapname), saved_map_(false), threshold_occupied_(threshold_occupied), threshold_free_(threshold_free)
{
ros::NodeHandle n;
ROS_INFO("Waiting for the map");
map_sub_ = n.subscribe("map", 1, &MapGenerator::mapCallback, this);
}
void mapCallback(const nav_msgs::OccupancyGridConstPtr& map)
{
ROS_INFO("Received a %d X %d map @ %.3f m/pix",
map->info.width,
map->info.height,
map->info.resolution);
std::string mapdatafile = mapname_ + ".pgm";
ROS_INFO("Writing map occupancy data to %s", mapdatafile.c_str());
FILE* out = fopen(mapdatafile.c_str(), "w");
if (!out)
{
ROS_ERROR("Couldn't save map file to %s", mapdatafile.c_str());
return;
}
fprintf(out, "P5\n# CREATOR: map_saver.cpp %.3f m/pix\n%d %d\n255\n",
map->info.resolution, map->info.width, map->info.height);
for(unsigned int y = 0; y < map->info.height; y++) {
for(unsigned int x = 0; x < map->info.width; x++) {
unsigned int i = x + (map->info.height - y - 1) * map->info.width;
if (map->data[i] >= 0 && map->data[i] <= threshold_free_) { // [0,free)
fputc(254, out);
} else if (map->data[i] >= threshold_occupied_) { // (occ,255]
fputc(000, out);
} else { //occ [0.25,0.65]
fputc(205, out);
}
}
}
fclose(out);
std::string mapmetadatafile = mapname_ + ".yaml";
ROS_INFO("Writing map occupancy data to %s", mapmetadatafile.c_str());
FILE* yaml = fopen(mapmetadatafile.c_str(), "w");
/*
resolution: 0.100000
origin: [0.000000, 0.000000, 0.000000]
#
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196
*/
geometry_msgs::Quaternion orientation = map->info.origin.orientation;
tf2::Matrix3x3 mat(tf2::Quaternion(
orientation.x,
orientation.y,
orientation.z,
orientation.w
));
double yaw, pitch, roll;
mat.getEulerYPR(yaw, pitch, roll);
fprintf(yaml, "image: %s\nresolution: %f\norigin: [%f, %f, %f]\nnegate: 0\noccupied_thresh: 0.65\nfree_thresh: 0.196\n\n",
mapdatafile.c_str(), map->info.resolution, map->info.origin.position.x, map->info.origin.position.y, yaw);
fclose(yaml);
ROS_INFO("Done\n");
saved_map_ = true;
}
std::string mapname_;
ros::Subscriber map_sub_;
bool saved_map_;
int threshold_occupied_;
int threshold_free_;
};
#define USAGE "Usage: \n" \
" map_saver -h\n"\
" map_saver [--occ <threshold_occupied>] [--free <threshold_free>] [-f <mapname>] [ROS remapping args]"
int main(int argc, char** argv)
{
ros::init(argc, argv, "map_saver");
std::string mapname = "map";
int threshold_occupied = 65;
int threshold_free = 25;
for(int i=1; i<argc; i++)
{
if(!strcmp(argv[i], "-h"))
{
puts(USAGE);
return 0;
}
else if(!strcmp(argv[i], "-f"))
{
if(++i < argc)
mapname = argv[i];
else
{
puts(USAGE);
return 1;
}
}
else if (!strcmp(argv[i], "--occ"))
{
if (++i < argc)
{
threshold_occupied = std::atoi(argv[i]);
if (threshold_occupied < 1 || threshold_occupied > 100)
{
ROS_ERROR("threshold_occupied must be between 1 and 100");
return 1;
}
}
else
{
puts(USAGE);
return 1;
}
}
else if (!strcmp(argv[i], "--free"))
{
if (++i < argc)
{
threshold_free = std::atoi(argv[i]);
if (threshold_free < 0 || threshold_free > 100)
{
ROS_ERROR("threshold_free must be between 0 and 100");
return 1;
}
}
else
{
puts(USAGE);
return 1;
}
}
else
{
puts(USAGE);
return 1;
}
}
if (threshold_occupied <= threshold_free)
{
ROS_ERROR("threshold_free must be smaller than threshold_occupied");
return 1;
}
MapGenerator mg(mapname, threshold_occupied, threshold_free);
while(!mg.saved_map_ && ros::ok())
ros::spinOnce();
return 0;
}
| 6,226 | C++ | 27.56422 | 128 | 0.598458 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/src/main.cpp | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Author: Brian Gerkey */
#define USAGE "\nUSAGE: map_server <map.yaml>\n" \
" map.yaml: map description file\n" \
"DEPRECATED USAGE: map_server <map> <resolution>\n" \
" map: image file to load\n"\
" resolution: map resolution [meters/pixel]"
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <boost/filesystem.hpp>
#include "ros/ros.h"
#include "ros/console.h"
#include "map_server/image_loader.h"
#include "nav_msgs/MapMetaData.h"
#include "nav_msgs/LoadMap.h"
#include "yaml-cpp/yaml.h"
#ifdef HAVE_YAMLCPP_GT_0_5_0
// The >> operator disappeared in yaml-cpp 0.5, so this function is
// added to provide support for code written under the yaml-cpp 0.3 API.
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
i = node.as<T>();
}
#endif
class MapServer
{
public:
/** Trivial constructor */
MapServer(const std::string& fname, double res)
{
std::string mapfname = "";
double origin[3];
int negate;
double occ_th, free_th;
MapMode mode = TRINARY;
ros::NodeHandle private_nh("~");
private_nh.param("frame_id", frame_id_, std::string("map"));
//When called this service returns a copy of the current map
get_map_service_ = nh_.advertiseService("static_map", &MapServer::mapCallback, this);
//Change the currently published map
change_map_srv_ = nh_.advertiseService("change_map", &MapServer::changeMapCallback, this);
// Latched publisher for metadata
metadata_pub_ = nh_.advertise<nav_msgs::MapMetaData>("map_metadata", 1, true);
// Latched publisher for data
map_pub_ = nh_.advertise<nav_msgs::OccupancyGrid>("map", 1, true);
deprecated_ = (res != 0);
if (!deprecated_) {
if (!loadMapFromYaml(fname))
{
exit(-1);
}
} else {
if (!loadMapFromParams(fname, res))
{
exit(-1);
}
}
}
private:
ros::NodeHandle nh_;
ros::Publisher map_pub_;
ros::Publisher metadata_pub_;
ros::ServiceServer get_map_service_;
ros::ServiceServer change_map_srv_;
bool deprecated_;
std::string frame_id_;
/** Callback invoked when someone requests our service */
bool mapCallback(nav_msgs::GetMap::Request &req,
nav_msgs::GetMap::Response &res )
{
// request is empty; we ignore it
// = operator is overloaded to make deep copy (tricky!)
res = map_resp_;
ROS_INFO("Sending map");
return true;
}
/** Callback invoked when someone requests to change the map */
bool changeMapCallback(nav_msgs::LoadMap::Request &request,
nav_msgs::LoadMap::Response &response )
{
if (loadMapFromYaml(request.map_url))
{
response.result = response.RESULT_SUCCESS;
ROS_INFO("Changed map to %s", request.map_url.c_str());
}
else
{
response.result = response.RESULT_UNDEFINED_FAILURE;
}
return true;
}
/** Load a map given all the values needed to understand it
*/
bool loadMapFromValues(std::string map_file_name, double resolution,
int negate, double occ_th, double free_th,
double origin[3], MapMode mode)
{
ROS_INFO("Loading map from image \"%s\"", map_file_name.c_str());
try {
map_server::loadMapFromFile(&map_resp_, map_file_name.c_str(),
resolution, negate, occ_th, free_th,
origin, mode);
} catch (std::runtime_error& e) {
ROS_ERROR("%s", e.what());
return false;
}
// To make sure get a consistent time in simulation
ros::Time::waitForValid();
map_resp_.map.info.map_load_time = ros::Time::now();
map_resp_.map.header.frame_id = frame_id_;
map_resp_.map.header.stamp = ros::Time::now();
ROS_INFO("Read a %d X %d map @ %.3lf m/cell",
map_resp_.map.info.width,
map_resp_.map.info.height,
map_resp_.map.info.resolution);
meta_data_message_ = map_resp_.map.info;
//Publish latched topics
metadata_pub_.publish( meta_data_message_ );
map_pub_.publish( map_resp_.map );
return true;
}
/** Load a map using the deprecated method
*/
bool loadMapFromParams(std::string map_file_name, double resolution)
{
ros::NodeHandle private_nh("~");
int negate;
double occ_th;
double free_th;
double origin[3];
private_nh.param("negate", negate, 0);
private_nh.param("occupied_thresh", occ_th, 0.65);
private_nh.param("free_thresh", free_th, 0.196);
origin[0] = origin[1] = origin[2] = 0.0;
return loadMapFromValues(map_file_name, resolution, negate, occ_th, free_th, origin, TRINARY);
}
/** Load a map given a path to a yaml file
*/
bool loadMapFromYaml(std::string path_to_yaml)
{
std::string mapfname;
MapMode mode;
double res;
int negate;
double occ_th;
double free_th;
double origin[3];
std::ifstream fin(path_to_yaml.c_str());
if (fin.fail()) {
ROS_ERROR("Map_server could not open %s.", path_to_yaml.c_str());
return false;
}
#ifdef HAVE_YAMLCPP_GT_0_5_0
// The document loading process changed in yaml-cpp 0.5.
YAML::Node doc = YAML::Load(fin);
#else
YAML::Parser parser(fin);
YAML::Node doc;
parser.GetNextDocument(doc);
#endif
try {
doc["resolution"] >> res;
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain a resolution tag or it is invalid.");
return false;
}
try {
doc["negate"] >> negate;
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain a negate tag or it is invalid.");
return false;
}
try {
doc["occupied_thresh"] >> occ_th;
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain an occupied_thresh tag or it is invalid.");
return false;
}
try {
doc["free_thresh"] >> free_th;
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain a free_thresh tag or it is invalid.");
return false;
}
try {
std::string modeS = "";
doc["mode"] >> modeS;
if(modeS=="trinary")
mode = TRINARY;
else if(modeS=="scale")
mode = SCALE;
else if(modeS=="raw")
mode = RAW;
else{
ROS_ERROR("Invalid mode tag \"%s\".", modeS.c_str());
return false;
}
} catch (YAML::Exception &) {
ROS_DEBUG("The map does not contain a mode tag or it is invalid... assuming Trinary");
mode = TRINARY;
}
try {
doc["origin"][0] >> origin[0];
doc["origin"][1] >> origin[1];
doc["origin"][2] >> origin[2];
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain an origin tag or it is invalid.");
return false;
}
try {
doc["image"] >> mapfname;
// TODO: make this path-handling more robust
if(mapfname.size() == 0)
{
ROS_ERROR("The image tag cannot be an empty string.");
return false;
}
boost::filesystem::path mapfpath(mapfname);
if (!mapfpath.is_absolute())
{
boost::filesystem::path dir(path_to_yaml);
dir = dir.parent_path();
mapfpath = dir / mapfpath;
mapfname = mapfpath.string();
}
} catch (YAML::InvalidScalar &) {
ROS_ERROR("The map does not contain an image tag or it is invalid.");
return false;
}
return loadMapFromValues(mapfname, res, negate, occ_th, free_th, origin, mode);
}
/** The map data is cached here, to be sent out to service callers
*/
nav_msgs::MapMetaData meta_data_message_;
nav_msgs::GetMap::Response map_resp_;
/*
void metadataSubscriptionCallback(const ros::SingleSubscriberPublisher& pub)
{
pub.publish( meta_data_message_ );
}
*/
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "map_server", ros::init_options::AnonymousName);
ros::NodeHandle nh("~");
if(argc != 3 && argc != 2)
{
ROS_ERROR("%s", USAGE);
exit(-1);
}
if (argc != 2) {
ROS_WARN("Using deprecated map server interface. Please switch to new interface.");
}
std::string fname(argv[1]);
double res = (argc == 2) ? 0.0 : atof(argv[2]);
try
{
MapServer ms(fname, res);
ros::spin();
}
catch(std::runtime_error& e)
{
ROS_ERROR("map_server exception: %s", e.what());
return -1;
}
return 0;
}
| 10,488 | C++ | 31.076453 | 100 | 0.596396 |
tudelft/autoGDMplus/gaden_ws/src/gaden/map_server/include/map_server/image_loader.h | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MAP_SERVER_MAP_SERVER_H
#define MAP_SERVER_MAP_SERVER_H
/*
* Author: Brian Gerkey
*/
#include "nav_msgs/GetMap.h"
/** Map mode
* Default: TRINARY -
* value >= occ_th - Occupied (100)
* value <= free_th - Free (0)
* otherwise - Unknown
* SCALE -
* alpha < 1.0 - Unknown
* value >= occ_th - Occupied (100)
* value <= free_th - Free (0)
* otherwise - f( (free_th, occ_th) ) = (0, 100)
* (linearly map in between values to (0,100)
* RAW -
* value = value
*/
enum MapMode {TRINARY, SCALE, RAW};
namespace map_server
{
/** Read the image from file and fill out the resp object, for later
* use when our services are requested.
*
* @param resp The map wil be written into here
* @param fname The image file to read from
* @param res The resolution of the map (gets stored in resp)
* @param negate If true, then whiter pixels are occupied, and blacker
* pixels are free
* @param occ_th Threshold above which pixels are occupied
* @param free_th Threshold below which pixels are free
* @param origin Triple specifying 2-D pose of lower-left corner of image
* @param mode Map mode
* @throws std::runtime_error If the image file can't be loaded
* */
void loadMapFromFile(nav_msgs::GetMap::Response* resp,
const char* fname, double res, bool negate,
double occ_th, double free_th, double* origin,
MapMode mode=TRINARY);
}
#endif
| 3,099 | C | 38.743589 | 78 | 0.693127 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor_array/package.xml | <package>
<name>simulated_gas_sensor_array</name>
<version>1.0.0</version>
<description>Pkg for the simulation of the response of a gas sensor array composed of N gas_sensors (MOX, EQ, PID, etc) </description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<!-- Dependencies which this package needs to build itself. -->
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>roscpp</build_depend>
<build_depend>visualization_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<build_depend>olfaction_msgs</build_depend>
<build_depend>tf</build_depend>
<build_depend>gaden_player</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>roscpp</run_depend>
<run_depend>visualization_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>tf</run_depend>
<run_depend>nav_msgs</run_depend>
<run_depend>olfaction_msgs</run_depend>
<run_depend>gaden_player</run_depend>
</package>
| 1,111 | XML | 34.870967 | 136 | 0.723672 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor_array/src/fake_gas_sensor_array.h | #include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <visualization_msgs/Marker.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_listener.h>
#include <olfaction_msgs/gas_sensor_array.h>
#include <gaden_player/GasPosition.h>
#include <boost/format.hpp>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <fstream>
#include <iostream>
//Gas Types
#define ETHANOL_ID 0
#define METHANE_ID 1
#define HYDROGEN_ID 2
#define PROPANOL_ID 3
#define CHLORIDE_ID 4
#define FLURORINE_ID 5
#define ACETONE_ID 6
#define NEON_ID 7
#define HELIUM_ID 8
#define HOTAIR_ID 9
//Sensor Types
#define TGS2620_ID 0
#define TGS2600_ID 1
#define TGS2611_ID 2
#define TGS2610_ID 3
#define TGS2612_ID 4
#define PID_ID 30
// Parameters
int num_sensors; //number of sensors in the array
std::vector<int> sensor_models;
double pub_rate;
std::string topic_id;
std::string frame_id;
std::string fixed_frame;
bool use_PID_correction_factors;
//Parameters to model the MOX response
struct gas_sensor
{
bool first_reading; //First reading is set to baseline always
float RS_R0; //Ideal sensor response based on sensitivity
float sensor_output; //MOX model response
float previous_sensor_output; //The response in (t-1)
};
std::vector<gas_sensor> sensor_array;
// Vars
int ch_id; //Chemical ID
bool notified; //to notifiy about erros just once
//functions:
void loadNodeParameters(ros::NodeHandle private_nh);
float simulate_mox_as_line_loglog(gaden_player::GasPositionResponse GT_gas_concentrations, int s_idx);
float simulate_pid(gaden_player::GasPositionResponse GT_gas_concentrations);
//------------------------ SENSOR CHARACTERIZATION PARAMS ----------------------------------//
std::string labels[5] = {"TGS2620", "TGS2600", "TGS2611", "TGS2610", "TGS2612"};
float R0[5] = {3000, 50000, 3740, 3740, 4500}; //[Ohms] Reference resistance (see datasheets)
//Time constants (Rise, Decay)
float tau_value[5][7][2] = //5 sensors, 7 gases , 2 Time Constants
{
{ //TGS2620
{2.96, 15.71}, //ethanol
{2.96, 15.71}, //methane
{2.96, 15.71}, //hydrogen
{2.96, 15.71}, //propanol
{2.96, 15.71}, //chlorine
{2.96, 15.71}, //fluorine
{2.96, 15.71} //Acetone
},
{ //TGS2600
{4.8, 18.75}, //ethanol
{4.8, 18.75}, //methane
{4.8, 18.75}, //hydrogen
{4.8, 18.75}, //propanol
{4.8, 18.75}, //chlorine
{4.8, 18.75}, //fluorine
{4.8, 18.75} //Acetone
},
{ //TGS2611
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
},
{ //TGS2610
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
},
{ //TGS2612
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
}
};
// MOX sensitivity. Extracted from datasheets and curve fitting
//--------------------------------------------------------------
float Sensitivity_Air[5] = {21, 1, 8.8, 10.3, 19.5}; //RS/R0 when exposed to clean air (datasheet)
// RS/R0 = A*conc^B (a line in the loglog scale)
float sensitivity_lineloglog[5][7][2]={ //5 Sensors, 7 Gases, 2 Constants: A, B
{ //TGS2620
{62.32, -0.7155}, //Ethanol
{120.6, -0.4877}, //Methane
{24.45, -0.5546}, //Hydrogen
{120.6, -0.4877}, //propanol (To review)
{120.6, -0.4877}, //chlorine (To review)
{120.6, -0.4877}, //fluorine (To review)
{120.6, -0.4877} //Acetone (To review)
},
{ //TGS2600
{0.6796, -0.3196}, //ethanol
{1.018, -0.07284}, //methane
{0.6821, -0.3532}, //hydrogen
{1.018, -0.07284}, //propanol (To review)
{1.018, -0.07284}, //chlorine (To review)
{1.018, -0.07284}, //fluorine (To review)
{1.018, -0.07284} //Acetone (To review)
},
{ //TGS2611
{51.11, -0.3658}, //ethanol
{38.46, -0.4289}, //methane
{41.3, -0.3614}, //hydrogen
{38.46, -0.4289}, //propanol (To review)
{38.46, -0.4289}, //chlorine (To review)
{38.46, -0.4289}, //fluorine (To review)
{38.46, -0.4289} //Acetone (To review)
},
{ //TGS2610
{106.1, -0.5008}, //ethanol
{63.91, -0.5372}, //methane
{66.78, -0.4888}, //hydrogen
{63.91, -0.5372}, //propanol (To review)
{63.91, -0.5372}, //chlorine (To review)
{63.91, -0.5372}, //fluorine (To review)
{63.91, -0.5372} //Acetone (To review)
},
{ //TGS2612
{31.35, -0.09115}, //ethanol
{146.2, -0.5916}, //methane
{19.5, 0.0}, //hydrogen
{146.2, -0.5916}, //propanol (To review)
{146.2, -0.5916}, //chlorine (To review)
{146.2, -0.5916}, //fluorine (To review)
{146.2, -0.5916} //Acetone (To review)
}
};
//PID correction factors for gas concentration
//--------------------------------------------
//Ethanol, Methane, Hydrogen, Propanol, Chlorine, Fluorine, Acetone
// http://www.intlsensor.com/pdf/pidcorrectionfactors.pdf
// Here we simulate a lamp of 11.7eV to increase the range of detectable gases
// A 0.0 means the PID is not responsive to that gas
float PID_correction_factors[7] = {10.47, 0.0, 0.0, 2.7, 1.0, 0.0, 1.4};
| 5,945 | C | 29.649484 | 103 | 0.5455 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor_array/src/fake_gas_sensor_array.cpp | /*-------------------------------------------------------------------------------
* This node simulates the response of a MOX gas sensor given the GT gas concentration
* of the gases it is exposed to (request to simulation_player or dispersion_simulation)
* - Gas concentration should be given in [ppm]
* - The Pkg response can be set to: Resistance of the sensor (Rs), Resistance-ratio (Rs/R0), or Voltage (0-5V)
* - Sensitivity to different gases is set based on manufacter datasheet
* - Time constants for the dynamic response are set based on real experiments
*
* - Response to mixture of gases is set based on datasheet.
* -----------------------------------------------------------------------------------------------*/
#include "fake_gas_sensor_array.h"
int main( int argc, char** argv )
{
ros::init(argc, argv, "fake_gas_sensor_aray");
ros::NodeHandle n;
ros::NodeHandle pn("~");
//Read parameters
loadNodeParameters(pn);
//Publishers
ros::Publisher enose_pub = n.advertise<olfaction_msgs::gas_sensor_array>(topic_id, 500);
//Service to request gas concentration
ros::ServiceClient client = n.serviceClient<gaden_player::GasPosition>("/odor_value");
//Configure sensor_array
sensor_array.resize(num_sensors);
for (int i=0;i<num_sensors; i++)
{
sensor_array[i].first_reading = true;
}
// Loop
tf::TransformListener listener;
ros::Rate r(pub_rate);
notified = false;
while (ros::ok())
{
//Vars
tf::StampedTransform transform;
bool know_sensor_pose = true;
//Get pose of the sensor_aray in the /map reference
try
{
listener.lookupTransform(fixed_frame.c_str(), frame_id.c_str(),
ros::Time(0), transform);
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s",ex.what());
know_sensor_pose = false;
ros::Duration(1.0).sleep();
}
if (know_sensor_pose)
{
//Current sensor pose
float x_pos = transform.getOrigin().x();
float y_pos = transform.getOrigin().y();
float z_pos = transform.getOrigin().z();
// Get Gas concentration at current position (for each gas present)
// Service request to the simulator
gaden_player::GasPosition srv;
srv.request.x.push_back(x_pos);
srv.request.y.push_back(y_pos);
srv.request.z.push_back(z_pos);
if (client.call(srv))
{
/*
for (int i=0; i<srv.response.gas_type.size(); i++)
{
ROS_INFO("[FakeMOX] %s:%.4f at (%.2f,%.2f,%.2f)",srv.response.gas_type[i].c_str(), srv.response.gas_conc[i],srv.request.x, srv.request.y, srv.request.z );
}
*/
olfaction_msgs::gas_sensor_array enose_msg;
enose_msg.header.frame_id = frame_id;
enose_msg.header.stamp = ros::Time::now();
//For each sensor in the array, simulate its response
for (int s=0; s<num_sensors; s++)
{
//Simulate Gas_Sensor response given this GT values of the concentration!
olfaction_msgs::gas_sensor sensor_msg;
sensor_msg.header.frame_id = frame_id;
sensor_msg.header.stamp = ros::Time::now();
switch (sensor_models[s])
{
case 0: //MOX TGS2620
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2620;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response, s);
sensor_msg.raw_air = Sensitivity_Air[sensor_models[s]]*R0[sensor_models[s]];
sensor_msg.calib_A = sensitivity_lineloglog[sensor_models[s]][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[sensor_models[s]][0][1]; //Calib for Ethanol
break;
case 1: //MOX TGS2600
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2600;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response, s);
sensor_msg.raw_air = Sensitivity_Air[sensor_models[s]]*R0[sensor_models[s]];
sensor_msg.calib_A = sensitivity_lineloglog[sensor_models[s]][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[sensor_models[s]][0][1]; //Calib for Ethanol
break;
case 2: //MOX TGS2611
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2611;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response, s);
sensor_msg.raw_air = Sensitivity_Air[sensor_models[s]]*R0[sensor_models[s]];
sensor_msg.calib_A = sensitivity_lineloglog[sensor_models[s]][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[sensor_models[s]][0][1]; //Calib for Ethanol
break;
case 3: //MOX TGS2610
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2610;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response, s);
sensor_msg.raw_air = Sensitivity_Air[sensor_models[s]]*R0[sensor_models[s]];
sensor_msg.calib_A = sensitivity_lineloglog[sensor_models[s]][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[sensor_models[s]][0][1]; //Calib for Ethanol
break;
case 4: //MOX TGS2612
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2612;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response, s);
sensor_msg.raw_air = Sensitivity_Air[sensor_models[s]]*R0[sensor_models[s]];
sensor_msg.calib_A = sensitivity_lineloglog[sensor_models[s]][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[sensor_models[s]][0][1]; //Calib for Ethanol
break;
case 30: //PID miniRaeLite
sensor_msg.technology = sensor_msg.TECH_PID;
sensor_msg.manufacturer = sensor_msg.MANU_RAE;
sensor_msg.mpn = sensor_msg.MPN_MINIRAELITE;
sensor_msg.raw_units = sensor_msg.UNITS_PPM;
sensor_msg.raw = simulate_pid(srv.response);
sensor_msg.raw_air = 0.0;
sensor_msg.calib_A = 0.0;
sensor_msg.calib_B = 0.0;
break;
default:
break;
}
//append sensor observation to the array
enose_msg.sensors.push_back(sensor_msg);
}//end for each sensor in the array
//Publish simulated enose (Array of sensors)
enose_pub.publish(enose_msg);
notified = false;
}
else
{
if (!notified)
{
ROS_WARN("[fake_gas_sensor_array] Cannot read Gas Concentrations from GADEN simulator.");
notified = true;
}
}
}
ros::spinOnce();
r.sleep();
}
}
// Simulate MOX response: Sensitivity + Dynamic response
// RS = R0*( A * conc^B )
// This method employes a curve fitting based on a line in the loglog scale to set the sensitivity
float simulate_mox_as_line_loglog(gaden_player::GasPositionResponse GT_gas_concentrations, int s_idx)
{
if (sensor_array[s_idx].first_reading)
{
//Init sensor to its Baseline lvl
sensor_array[s_idx].sensor_output = Sensitivity_Air[sensor_models[s_idx]]; //RS_R0 value at air
sensor_array[s_idx].previous_sensor_output = sensor_array[s_idx].sensor_output;
sensor_array[s_idx].first_reading = false;
}
else
{
//1. Set Sensor Output based on gas concentrations (gas type dependent)
//---------------------------------------------------------------------
// RS/R0 = A*conc^B (a line in the loglog scale)
float resistance_variation = 0.0;
//Handle multiple gases
for (int i=0; i<GT_gas_concentrations.positions[0].concentration.size(); i++)
{
int gas_id;
if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"ethanol"))
gas_id = 0;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"methane"))
gas_id = 1;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"hydrogen"))
gas_id = 2;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"propanol"))
gas_id = 3;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"chlorine"))
gas_id = 4;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"fluorine"))
gas_id = 5;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"acetone"))
gas_id = 6;
else
{
ROS_ERROR("[fake_mox] MOX response is not configured for this gas type!");
return 0.0;
}
//JUST FOR VIDEO DEMO
/*
if (input_sensor_model == 0)
{
GT_gas_concentrations.gas_conc[i] *= 10;
}
else if (input_sensor_model ==2)
{
GT_gas_concentrations.gas_conc[i] *= 20;
}
*/
//Value of RS/R0 for the given gas and concentration
sensor_array[s_idx].RS_R0 = sensitivity_lineloglog[sensor_models[s_idx]][gas_id][0] * pow(GT_gas_concentrations.positions[0].concentration[i], sensitivity_lineloglog[sensor_models[s_idx]][gas_id][1]);
//Ensure we never overpass the baseline level (max allowed)
if (sensor_array[s_idx].RS_R0 > Sensitivity_Air[sensor_models[s_idx]])
sensor_array[s_idx].RS_R0= Sensitivity_Air[sensor_models[s_idx]];
//Increment with respect the Baseline
resistance_variation += Sensitivity_Air[sensor_models[s_idx]] - sensor_array[s_idx].RS_R0;
}
//Calculate final RS_R0 given the final resistance variation
sensor_array[s_idx].RS_R0 = Sensitivity_Air[sensor_models[s_idx]] - resistance_variation;
//Ensure a minimum sensor resitance
if (sensor_array[s_idx].RS_R0 <= 0.0)
sensor_array[s_idx].RS_R0 = 0.01;
//2. Simulate transient response (dynamic behaviour, tau_r and tau_d)
//---------------------------------------------------------------------
float tau;
if (sensor_array[s_idx].RS_R0 < sensor_array[s_idx].previous_sensor_output) //rise
tau = tau_value[sensor_models[s_idx]][0][0];
else //decay
tau = tau_value[sensor_models[s_idx]][0][1];
// Use a low pass filter
//alpha value = At/(tau+At)
float alpha = (1/pub_rate) / (tau+(1/pub_rate));
//filtered response (uses previous estimation):
sensor_array[s_idx].sensor_output = (alpha*sensor_array[s_idx].RS_R0) + (1-alpha)*sensor_array[s_idx].previous_sensor_output;
//Update values
sensor_array[s_idx].previous_sensor_output = sensor_array[s_idx].sensor_output;
}
// Return Sensor response for current time instant as the Sensor Resistance in Ohms
return (sensor_array[s_idx].sensor_output * R0[sensor_models[s_idx]]);
}
// Simulate PID response : Weighted Sum of all gases
float simulate_pid(gaden_player::GasPositionResponse GT_gas_concentrations)
{
//Handle multiple gases
float accumulated_conc = 0.0;
for (int i=0; i<GT_gas_concentrations.positions[0].concentration.size(); i++)
{
if (use_PID_correction_factors)
{
int gas_id;
if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"ethanol"))
gas_id = 0;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"methane"))
gas_id = 1;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"hydrogen"))
gas_id = 2;
else
{
ROS_ERROR("[fake_PID] PID response is not configured for this gas type!");
return 0.0;
}
if (PID_correction_factors[gas_id] != 0)
accumulated_conc += GT_gas_concentrations.positions[0].concentration[i] / PID_correction_factors[gas_id];
}
else
accumulated_conc += GT_gas_concentrations.positions[0].concentration[i];
}
return accumulated_conc;
}
//Load Sensor parameters
void loadNodeParameters(ros::NodeHandle private_nh)
{
//Num sensors in the array
private_nh.param<int>("num_sensors", num_sensors, 1);
//Sensor models
sensor_models.resize(num_sensors);
for (int i=0;i<num_sensors; i++)
{
//Get model of sensor (i)
std::string paramName = boost::str( boost::format("sensor_model_%i") % i);
private_nh.param<int>(paramName.c_str(),sensor_models[i], TGS2620_ID);
}
//Publication rate (Hz)
private_nh.param<double>("pub_rate", pub_rate, 5.0);
//sensor_array_topic_id
private_nh.param<std::string>("topic_id", topic_id, "/enose");
//sensor_array_frame_id
private_nh.param<std::string>("frame_id", frame_id, "enose_frame");
//fixed frame
private_nh.param<std::string>("fixed_frame", fixed_frame, "/map");
//PID_correction_factors
private_nh.param<bool>("use_PID_correction_factors", use_PID_correction_factors, false);
}
| 15,192 | C++ | 41.557423 | 212 | 0.534426 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_preprocessing/src/preprocessing.cpp | #include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <sstream>
#include <iostream>
#include <eigen3/Eigen/Dense>
#include <boost/format.hpp>
#include <boost/thread/mutex.hpp>
#include <queue>
#include <stack>
#include <TriangleBoxIntersection.h>
#include <stdint.h>
enum cell_state {non_initialized=0, empty=1, occupied=2, outlet=3, edge=4};
struct Point{
float x; float y; float z;
Point(){}
Point(float x, float y, float z){
this->x = x; this->y =y; this->z=z;
}
};
struct Triangle{
Point p1; Point p2; Point p3;
Triangle(){}
Triangle(Point p1, Point p2, Point p3){
this->p1=p1; this->p2=p2; this->p3=p3;
}
Point& operator[](int i){
if(i==0)
return p1;
else if (i==1)
return p2;
else if(i==2)
return p3;
else{
std::cout<<"Indexing error when accessing the points in triangle! Index must be >= 2";
return p1;
}
}
};
//dimensions of the enviroment [m]
float env_min_x;
float env_min_y;
float env_min_z;
float env_max_x;
float env_max_y;
float env_max_z;
float roundFactor;
//length of the sides of the cell [m]
float cell_size;
float floor_height;
std::vector<std::vector<std::vector<int> > > env;
bool compare_cell(int x, int y, int z, cell_state value){
if(x<0 || x>=env.size() ||
y<0 || y>=env[0].size() ||
z<0 || z>=env[0][0].size()){
return false;
}
else{
return env[x][y][z]==value;
}
}
void changeWorldFile(std::string filename){
std::ifstream input(filename);
std::stringstream ss;
std::string line;
while(getline(input, line)){
if(line.substr(0,8)=="floorMap"){
//ignore the floorMap bit, we are replacing it entirely
while(getline(input, line) && line!=")"){}
ss<<
"floorMap # load an environment bitmap\n"<<
"(\n"<<
" name \"SimulatedMap\"\n"<<
" bitmap \"../../occupancy.pgm\"\n"<<
" size ["<<(env_max_x-env_min_x)<<" "<<(env_max_y-env_min_y)<<" "<<(env_max_z-env_min_z) <<"] #m \n"<<
" pose ["<<(env_max_x-env_min_x)/2+env_min_x<<" "<<(env_max_y-env_min_y)/2+env_min_y<<" "<<floor_height<<" 0] #Coordinates (m) of the Center of the image_map\n"<<
")\n";
}
else{
ss<<line<<"\n";
}
}
input.close();
std::ofstream out(filename);
out<<ss.rdbuf();
out.close();
}
void printMap(std::string filename, int scale, bool block_outlets){
std::ofstream outfile(filename.c_str());
outfile << "P2\n"
<< scale * env[0].size() << " " << scale * env.size() << "\n" <<"1\n";
//things are repeated to scale them up (the image is too small!)
int height = (floor_height-env_min_z)/cell_size; //a xy slice of the 3D environment is used as a geometric map for navigation
for (int row = env.size()-1; row >= 0; row--)
{
for (int j = 0; j < scale; j++)
{
for (int col = 0; col <env[0].size() ; col++)
{
for (int i = 0; i < scale; i++)
{
auto& cell = env[row][col][height];
bool outletTerm = cell == cell_state::outlet && !block_outlets;
outfile << ( cell == cell_state::empty || outletTerm ? 1 : 0) << " ";
}
}
outfile << "\n";
}
}
outfile.close();
}
void printEnv(std::string filename, int scale)
{
std::ofstream outfile(filename.c_str());
outfile << "#env_min(m) " << env_min_x << " " << env_min_y << " " << env_min_z << "\n";
outfile << "#env_max(m) " << env_max_x << " " << env_max_y << " " << env_max_z << "\n";
outfile << "#num_cells " << env[0].size() << " " << env.size() << " " << env[0][0].size() << "\n";
outfile << "#cell_size(m) " << cell_size << "\n";
//things are repeated to scale them up (the image is too small!)
for (int height = 0; height < env[0][0].size(); height++)
{
for (int col = 0; col <env[0].size(); col++)
{
for (int j = 0; j < scale; j++)
{
for (int row = 0; row <env.size(); row++)
{
for (int i = 0; i < scale; i++)
{
outfile << (env[row][col][height]==cell_state::empty? 0 :
(env[row][col][height]==cell_state::outlet? 2 :
1))
<< " ";
}
}
outfile << "\n";
}
}
outfile << ";\n";
}
outfile.close();
}
void printWind(std::vector<double> U,
std::vector<double> V,
std::vector<double> W, std::string filename){
std::ofstream fileU(boost::str(boost::format("%s_U") % filename).c_str());
std::ofstream fileV(boost::str(boost::format("%s_V") % filename).c_str());
std::ofstream fileW(boost::str(boost::format("%s_W") % filename).c_str());
//this code is a header to let the filament_simulator know the file is in binary
int code=999;
fileU.write((char*) &code, sizeof(int));
fileV.write((char*) &code, sizeof(int));
fileW.write((char*) &code, sizeof(int));
fileU.write((char*) U.data(), sizeof(double) * U.size());
fileV.write((char*) V.data(), sizeof(double) * V.size());
fileW.write((char*) W.data(), sizeof(double) * W.size());
fileU.close();
fileV.close();
fileW.close();
}
void printYaml(std::string output){
std::ofstream yaml(boost::str(boost::format("%s/occupancy.yaml") % output.c_str()));
yaml << "image: occupancy.pgm\n"
<< "resolution: " << cell_size/10
<< "\norigin: [" << env_min_x << ", " << env_min_y << ", " << 0 << "]\n"
<< "occupied_thresh: 0.9\n"
<< "free_thresh: 0.1\n"
<< "negate: 0";
yaml.close();
}
float min_val(float x, float y, float z) {
float min =x;
if (y < min)
min=y;
if(z < min)
min=z;
return min;
}
float max_val(float x, float y, float z) {
float max= x;
if (y > max)
max=y;
if(z > max)
max=z;
return max;
}
bool eq(float x, float y){
return std::abs(x-y)<0.01;
}
std::vector<Eigen::Vector3d> cubePoints(const Eigen::Vector3d &query_point){
std::vector<Eigen::Vector3d> points;
points.push_back(query_point);
points.push_back(Eigen::Vector3d(query_point.x()-cell_size/2,
query_point.y()-cell_size/2,
query_point.z()-cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()-cell_size/2,
query_point.y()-cell_size/2,
query_point.z()+cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()-cell_size/2,
query_point.y()+cell_size/2,
query_point.z()-cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()-cell_size/2,
query_point.y()+cell_size/2,
query_point.z()+cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()+cell_size/2,
query_point.y()-cell_size/2,
query_point.z()-cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()+cell_size/2,
query_point.y()-cell_size/2,
query_point.z()+cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()+cell_size/2,
query_point.y()+cell_size/2,
query_point.z()-cell_size/2));
points.push_back(Eigen::Vector3d(query_point.x()+cell_size/2,
query_point.y()+cell_size/2,
query_point.z()+cell_size/2));
return points;
}
bool pointInTriangle(const Eigen::Vector3d& query_point,
const Eigen::Vector3d& triangle_vertex_0,
const Eigen::Vector3d& triangle_vertex_1,
const Eigen::Vector3d& triangle_vertex_2)
{
// u=P2−P1
Eigen::Vector3d u = triangle_vertex_1 - triangle_vertex_0;
// v=P3−P1
Eigen::Vector3d v = triangle_vertex_2 - triangle_vertex_0;
// n=u×v
Eigen::Vector3d n = u.cross(v);
bool anyProyectionInTriangle=false;
std::vector<Eigen::Vector3d> cube= cubePoints(query_point);
for(const Eigen::Vector3d &vec : cube){
// w=P−P1
Eigen::Vector3d w = vec - triangle_vertex_0;
// Barycentric coordinates of the projection P′of P onto T:
// γ=[(u×w)⋅n]/n²
float gamma = u.cross(w).dot(n) / n.dot(n);
// β=[(w×v)⋅n]/n²
float beta = w.cross(v).dot(n) / n.dot(n);
float alpha = 1 - gamma - beta;
// The point P′ lies inside T if:
bool proyectionInTriangle= ((0 <= alpha) && (alpha <= 1) &&
(0 <= beta) && (beta <= 1) &&
(0 <= gamma) && (gamma <= 1));
anyProyectionInTriangle=anyProyectionInTriangle||proyectionInTriangle;
}
n.normalize();
//we consider that the triangle goes through the cell if the proyection of the center
//is inside the triangle AND the plane of the triangle intersects the cube of the cell
return anyProyectionInTriangle;
}
bool parallel (const Point &vec){
return (eq(vec.y,0)
&&eq(vec.z,0))||
(eq(vec.x,0)
&&eq(vec.z,0))||
(eq(vec.x,0)
&&eq(vec.y,0));
}
void occupy(std::vector<Triangle> &triangles,
const std::vector<Point> &normals,
cell_state value_to_write){
std::cout<<"Processing the mesh...\n0%\n";
int numberOfProcessedTriangles=0; //for logging, doesn't actually do anything
boost::mutex mtx;
//Let's occupy the enviroment!
#pragma omp parallel for
for(int i= 0;i<triangles.size();i++){
//We try to find all the cells that some triangle goes through
int x1 = roundf((triangles[i].p1.x-env_min_x)*(roundFactor))/(cell_size*(roundFactor));
int y1 = roundf((triangles[i].p1.y-env_min_y)*(roundFactor))/(cell_size*(roundFactor));
int z1 = roundf((triangles[i].p1.z-env_min_z)*(roundFactor))/(cell_size*(roundFactor));
int x2 = roundf((triangles[i].p2.x-env_min_x)*(roundFactor))/(cell_size*(roundFactor));
int y2 = roundf((triangles[i].p2.y-env_min_y)*(roundFactor))/(cell_size*(roundFactor));
int z2 = roundf((triangles[i].p2.z-env_min_z)*(roundFactor))/(cell_size*(roundFactor));
int x3 = roundf((triangles[i].p3.x-env_min_x)*(roundFactor))/(cell_size*(roundFactor));
int y3 = roundf((triangles[i].p3.y-env_min_y)*(roundFactor))/(cell_size*(roundFactor));
int z3 = roundf((triangles[i].p3.z-env_min_z)*(roundFactor))/(cell_size*(roundFactor));
int min_x = min_val(x1,x2,x3);
int min_y = min_val(y1,y2,y3);
int min_z = min_val(z1,z2,z3);
int max_x = max_val(x1,x2,x3);
int max_y = max_val(y1,y2,y3);
int max_z = max_val(z1,z2,z3);
//is the triangle right at the boundary between two cells (in any axis)?
bool xLimit = eq(std::fmod(max_val(triangles[i][0].x,triangles[i][1].x,triangles[i][2].x)-env_min_x, cell_size),0)
||eq(std::fmod(max_val(triangles[i][0].x,triangles[i][1].x,triangles[i][2].x)-env_min_x, cell_size),cell_size);
bool yLimit = eq(std::fmod(max_val(triangles[i][0].y,triangles[i][1].y,triangles[i][2].y)-env_min_y, cell_size),0)
||eq(std::fmod(max_val(triangles[i][0].y,triangles[i][1].y,triangles[i][2].y)-env_min_y, cell_size),cell_size);
bool zLimit = eq(std::fmod(max_val(triangles[i][0].z,triangles[i][1].z,triangles[i][2].z)-env_min_z, cell_size),0)
||eq(std::fmod(max_val(triangles[i][0].z,triangles[i][1].z,triangles[i][2].z)-env_min_z, cell_size),cell_size);
bool isParallel =parallel(normals[i]);
for (int row = min_x; row <= max_x && row < env[0].size(); row++)
{
for (int col = min_y; col <= max_y && col < env.size(); col++)
{
for (int height = min_z; height <= max_z && height < env[0][0].size(); height++)
{
//check if the triangle goes through this cell
//special case for triangles that are parallel to the coordinate axes because the discretization can cause
//problems if they fall right on the boundary of two cells
if (
(isParallel && pointInTriangle(Eigen::Vector3d(row * cell_size + env_min_x+cell_size/2,
col * cell_size + env_min_y+cell_size/2,
height * cell_size + env_min_z+cell_size/2),
Eigen::Vector3d(triangles[i][0].x, triangles[i][0].y, triangles[i][0].z),
Eigen::Vector3d(triangles[i][1].x, triangles[i][1].y, triangles[i][1].z),
Eigen::Vector3d(triangles[i][2].x, triangles[i][2].y, triangles[i][2].z)))
||
triBoxOverlap(
Eigen::Vector3d(row * cell_size + env_min_x+cell_size/2,
col * cell_size + env_min_y+cell_size/2,
height * cell_size + env_min_z+cell_size/2),
Eigen::Vector3d(cell_size/2, cell_size/2, cell_size/2),
Eigen::Vector3d(triangles[i][0].x, triangles[i][0].y, triangles[i][0].z),
Eigen::Vector3d(triangles[i][1].x, triangles[i][1].y, triangles[i][1].z),
Eigen::Vector3d(triangles[i][2].x, triangles[i][2].y, triangles[i][2].z)))
{
mtx.lock();
env[col][row][height] = value_to_write;
if(value_to_write==cell_state::occupied){
//if the "limit" flags are activated, AND we are on the offending cells,
//AND the cell has not previously marked as normally occupied by a different triangle
//AND the cells are not on the very limit of the environment, mark the cell as "edge" for later cleanup
bool limitOfproblematicTriangle=(xLimit&&row==max_x)||
(yLimit&&col==max_y)||
(zLimit&&height==max_z);
bool endOfTheEnvironment = (col>0 || col<env.size() ||
row>0 || row<env[0].size() ||
height>0 || height<env[0][0].size());
if( !endOfTheEnvironment &&
limitOfproblematicTriangle &&
env[col][row][height]!=cell_state::occupied){
env[col][row][height]=cell_state::edge;
}
}
mtx.unlock();
}
}
}
}
//log progress
if(i>numberOfProcessedTriangles+triangles.size()/10){
mtx.lock();
std::cout<<(100*i)/triangles.size()<<"%\n";
numberOfProcessedTriangles=i;
mtx.unlock();
}
}
}
void parse(std::string filename, cell_state value_to_write){
bool ascii = false;
if (FILE *file = fopen(filename.c_str(), "r"))
{
//File exists!, keep going!
char buffer[6];
fgets(buffer, 6, file);
if(std::string(buffer).find("solid")!=std::string::npos)
ascii=true;
fclose(file);
}else{
std::cout<< "File " << filename << " does not exist\n";
return;
}
std::vector<Triangle> triangles;
std::vector<Point> normals;
if(ascii){
//first, we count how many triangles there are (we need to do this before reading the data
// to create a vector of the right size)
std::ifstream countfile(filename.c_str());
std::string line;
int count = 0;
while (std::getline(countfile, line)){
if(line.find("facet normal") != std::string::npos){
count++;
}
}
countfile.close();
//each points[i] contains one the three vertices of triangle i
triangles.resize(count);
normals.resize(count);
//let's read the data
std::ifstream infile(filename.c_str());
std::getline(infile, line);
int i =0;
while (line.find("endsolid")==std::string::npos)
{
while (line.find("facet normal") == std::string::npos){std::getline(infile, line);}
size_t pos = line.find("facet");
line.erase(0, pos + 12);
float aux;
std::stringstream ss(line);
ss >> std::skipws >> aux;
normals[i].x = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
normals[i].y = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
normals[i].z = roundf(aux * roundFactor) / roundFactor;
std::getline(infile, line);
for(int j=0;j<3;j++){
std::getline(infile, line);
size_t pos = line.find("vertex ");
line.erase(0, pos + 7);
std::stringstream ss(line);
ss >> std::skipws >> aux;
triangles[i][j].x = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
triangles[i][j].y = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
triangles[i][j].z = roundf(aux * roundFactor) / roundFactor;
}
i++;
//skipping lines here makes checking for the end of the file more convenient
std::getline(infile, line);
std::getline(infile, line);
while(std::getline(infile, line)&&line.length()==0);
}
infile.close();
}
else{
std::ifstream infile(filename.c_str(), std::ios_base::binary);
infile.seekg(80 * sizeof(uint8_t), std::ios_base::cur); //skip the header
uint32_t num_triangles;
infile.read((char*) &num_triangles, sizeof(uint32_t));
triangles.resize(num_triangles);
normals.resize(num_triangles);
for(int i = 0; i < num_triangles; i++){
infile.read((char*) &normals[i], 3 * sizeof(float)); //read the normal vector
for(int j=0; j<3;j++){
infile.read((char*) &triangles[i][j], 3 * sizeof(float)); //read the point
}
infile.seekg(sizeof(uint16_t), std::ios_base::cur); //skip the attribute data
}
infile.close();
}
//OK, we have read the data, let's do something with it
occupy(triangles, normals, value_to_write);
}
void findDimensions(std::string filename){
bool ascii = false;
if (FILE *file = fopen(filename.c_str(), "r"))
{
//File exists!, keep going!
char buffer[6];
fgets(buffer, 6, file);
if(std::string(buffer).find("solid")!=std::string::npos)
ascii=true;
fclose(file);
}else{
std::cout<< "File " << filename << " does not exist\n";
return;
}
if(ascii){
//let's read the data
std::string line;
std::ifstream infile(filename.c_str());
std::getline(infile, line);
int i =0;
while (line.find("endsolid")==std::string::npos)
{
while (std::getline(infile, line) && line.find("outer loop") == std::string::npos);
for(int j=0;j<3;j++){
float x, y, z;
std::getline(infile, line);
size_t pos = line.find("vertex ");
line.erase(0, pos + 7);
std::stringstream ss(line);
float aux;
ss >> std::skipws >> aux;
x = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
y = roundf(aux * roundFactor) / roundFactor;
ss >> std::skipws >> aux;
z = roundf(aux * roundFactor) / roundFactor;
env_max_x = env_max_x>=x?env_max_x:x;
env_max_y = env_max_y>=y?env_max_y:y;
env_max_z = env_max_z>=z?env_max_z:z;
env_min_x = env_min_x<=x?env_min_x:x;
env_min_y = env_min_y<=y?env_min_y:y;
env_min_z = env_min_z<=z?env_min_z:z;
}
i++;
//skipping three lines here makes checking for the end of the file more convenient
std::getline(infile, line);
std::getline(infile, line);
while(std::getline(infile, line)&&line.length()==0);
}
infile.close();
}
else{
std::ifstream infile(filename.c_str(), std::ios_base::binary);
infile.seekg(80 * sizeof(uint8_t), std::ios_base::cur); //skip the header
uint32_t num_triangles;
infile.read((char*) &num_triangles, sizeof(uint32_t));
for(int i = 0; i < num_triangles; i++){
infile.seekg(3 * sizeof(float), std::ios_base::cur); //skip the normal vector
for(int j=0; j<3;j++){
float x, y ,z;
infile.read((char*) &x, sizeof(float));
infile.read((char*) &y, sizeof(float));
infile.read((char*) &z, sizeof(float));
env_max_x = env_max_x>=x?env_max_x:x;
env_max_y = env_max_y>=y?env_max_y:y;
env_max_z = env_max_z>=z?env_max_z:z;
env_min_x = env_min_x<=x?env_min_x:x;
env_min_y = env_min_y<=y?env_min_y:y;
env_min_z = env_min_z<=z?env_min_z:z;
}
infile.seekg(sizeof(uint16_t), std::ios_base::cur); //skip the attribute data
}
}
std::cout<<"Dimensions are:\n"<<
"x: ("<<env_min_x<<", "<<env_max_x<<")\n"<<
"y: ("<<env_min_y<<", "<<env_max_y<<")\n"<<
"z: ("<<env_min_z<<", "<<env_max_z<<")\n";
}
int indexFrom3D(int x, int y, int z){
return x + y*env[0].size() + z*env[0].size()*env.size();
}
void openFoam_to_gaden(std::string filename)
{
//let's parse the file
std::ifstream infile(filename.c_str());
std::string line;
//ignore the first line (column names)
std::getline(infile, line);
std::vector<double> U(env[0].size()*env.size()*env[0][0].size());
std::vector<double> V(env[0].size()*env.size()*env[0][0].size());
std::vector<double> W(env[0].size()*env.size()*env[0][0].size());
std::vector<double> v(6);
int x_idx = 0;
int y_idx = 0;
int z_idx = 0;
while (std::getline(infile, line))
{
if (line.length()!=0)
{
for (int i = 0; i < 6; i++)
{
size_t pos = line.find(",");
v[i] = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
}
//assign each of the points we have information about to the nearest cell
x_idx = (int)roundf((v[3] - env_min_x) / cell_size*roundFactor)/roundFactor;
y_idx = (int)roundf((v[4] - env_min_y) / cell_size*roundFactor)/roundFactor;
z_idx = (int)roundf((v[5] - env_min_z) / cell_size*roundFactor)/roundFactor;
U[ indexFrom3D(x_idx, y_idx,z_idx) ] = v[0];
V[ indexFrom3D(x_idx, y_idx,z_idx) ] = v[1];
W[ indexFrom3D(x_idx, y_idx,z_idx) ] = v[2];
}
}
std::cout << "env_size: " << env.size() << ' ' << env[0].size() << ' ' << env[0][0].size() << '\n';
std::cout << "U.size():" << U.size()<< '\n';
std::cout << "V.size():" << V.size()<< '\n';
std::cout << "W.size():" << W.size()<< '\n';
infile.close();
printWind(U,V,W,filename);
}
void fill(int x, int y, int z, cell_state new_value, cell_state value_to_overwrite){
std::queue<Eigen::Vector3i> q;
q.push(Eigen::Vector3i(x, y, z));
env[x][y][z]=new_value;
while(!q.empty()){
Eigen::Vector3i point = q.front();
q.pop();
if(compare_cell(point.x()+1, point.y(), point.z(), value_to_overwrite)){ // x+1, y, z
env[point.x()+1][point.y()][point.z()]=new_value;
q.push(Eigen::Vector3i(point.x()+1, point.y(), point.z()));
}
if(compare_cell(point.x()-1, point.y(), point.z(), value_to_overwrite)){ // x-1, y, z
env[point.x()-1][point.y()][point.z()]=new_value;
q.push(Eigen::Vector3i(point.x()-1, point.y(), point.z()));
}
if(compare_cell(point.x(), point.y()+1, point.z(), value_to_overwrite)){ // x, y+1, z
env[point.x()][point.y()+1][point.z()]=new_value;
q.push(Eigen::Vector3i(point.x(), point.y()+1, point.z()));
}
if(compare_cell(point.x(), point.y()-1, point.z(), value_to_overwrite)){ // x, y-1, z
env[point.x()][point.y()-1][point.z()]=new_value;
q.push(Eigen::Vector3i(point.x(), point.y()-1, point.z()));
}
if(compare_cell(point.x(), point.y(), point.z()+1, value_to_overwrite)){ // x, y, z+1
env[point.x()][point.y()][point.z()+1]=new_value;
q.push(Eigen::Vector3i(point.x(), point.y(), point.z()+1));
}
if(compare_cell(point.x(), point.y(), point.z()-1, value_to_overwrite)){ // x, y, z-1
env[point.x()][point.y()][point.z()-1]=new_value;
q.push(Eigen::Vector3i(point.x(), point.y(), point.z()-1));
}
}
}
void clean(){
for(int col=0;col<env.size();col++){
for(int row=0;row<env[0].size();row++){
for(int height=0;height<env[0][0].size();height++){
if(env[col][row][height]==cell_state::edge){
if(compare_cell(col+1, row, height, cell_state::empty)||
compare_cell(col, row+1, height, cell_state::empty)||
compare_cell(col, row, height+1, cell_state::empty)||
(compare_cell(col+1, row+1, height, cell_state::empty)
&&env[col][row+1][height]==cell_state::edge
&&env[col+1][row][height]==cell_state::edge))
{
env[col][row][height]=cell_state::empty;
}else
{
env[col][row][height]=cell_state::occupied;
}
}
}
}
}
}
int main(int argc, char **argv){
ros::init(argc, argv, "preprocessing");
int numModels;
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
ros::Publisher pub = nh.advertise<std_msgs::Bool>("preprocessing_done",5,true);
private_nh.param<float>("cell_size", cell_size, 1); //size of the cells
roundFactor=100.0/cell_size;
//stl file with the model of the outlets
std::string outlet; int numOutletModels;
//path to the csv file where we want to write the occupancy map
std::string output;
private_nh.param<std::string>("output_path", output, "");
//--------------------------
//OCCUPANCY
//--------------------------
private_nh.param<int>("number_of_models", numModels, 2); // number of CAD models
std::vector<std::string> CADfiles;
for(int i = 0; i< numModels; i++){
std::string paramName = boost::str( boost::format("model_%i") % i); //each of the stl models
std::string filename;
private_nh.param<std::string>(paramName, filename, "");
CADfiles.push_back(filename.c_str());
}
for (int i = 0; i < CADfiles.size(); i++)
{
findDimensions(CADfiles[i]);
}
// eliminate floating point error rounding error, resulitng in incorrect cell amounts
// float y_cells_float =((env_max_y-env_min_y)*(roundFactor)/(cell_size*(roundFactor)));
// float y_cells_round = roundf(y_cells_float*100)/100;
// float x_cells_float =((env_max_x-env_min_x)*(roundFactor)/(cell_size*(roundFactor)));
// float x_cells_round = roundf(x_cells_float*100)/100;
// float z_cells_float =((env_max_z-env_min_z)*(roundFactor)/(cell_size*(roundFactor)));
// float z_cells_round = roundf(z_cells_float*100)/100;
//x and y are interchanged!!!!!! it goes env[y][x][z]
//I cannot for the life of me remember why I did that, but there must have been a reason
// env = std::vector<std::vector<std::vector<int> > > (ceil(y_cells_round),
// std::vector<std::vector<int> >(ceil(x_cells_round),
// std::vector<int>(ceil(z_cells_round), 0)));
env = std::vector<std::vector<std::vector<int> > > (ceil((env_max_y-env_min_y)*(roundFactor)/(cell_size*(roundFactor))),
std::vector<std::vector<int> >(ceil((env_max_x - env_min_x)*(roundFactor)/(cell_size*(roundFactor))),
std::vector<int>(ceil((env_max_z - env_min_z)*(roundFactor)/(cell_size*(roundFactor))), 0)));
ros::Time start = ros::Time::now();
for (int i = 0; i < numModels; i++)
{
parse(CADfiles[i], cell_state::occupied);
}
std::cout <<"Took "<< ros::Time::now().toSec()-start.toSec()<<" seconds \n";
float empty_point_x;
private_nh.param<float>("empty_point_x", empty_point_x, 1);
float empty_point_y;
private_nh.param<float>("empty_point_y", empty_point_y, 1);
float empty_point_z;
private_nh.param<float>("empty_point_z", empty_point_z, 1);
//--------------------------
//OUTLETS
//--------------------------
private_nh.param<int>("number_of_outlet_models", numOutletModels, 1); // number of CAD models
std::vector<std::string> outletFiles;
for(int i = 0; i< numOutletModels; i++){
std::string paramName = boost::str( boost::format("outlets_model_%i") % i); //each of the stl models
std::string filename;
private_nh.param<std::string>(paramName, filename, "");
outletFiles.push_back(filename.c_str());
}
for (int i=0;i<numOutletModels; i++){
parse(outletFiles[i], cell_state::outlet);
}
std::cout<<"Filling...\n";
//Mark all the empty cells reachable from the empty_point as aux_empty
//the ones that cannot be reached will be marked as occupied when printing
fill((empty_point_y-env_min_y)/cell_size,
(empty_point_x-env_min_x)/cell_size,
(empty_point_z-env_min_z)/cell_size,
cell_state::empty, cell_state::non_initialized);
//get rid of the cells marked as "edge", since those are not truly occupied
clean();
private_nh.param<float>("floor_height", floor_height, 0); // number of CAD models
printMap(boost::str(boost::format("%s/occupancy.pgm") % output.c_str()), 10, private_nh.param<bool>("block_outlets", false) );
std::string worldFile;
private_nh.param<std::string>("worldFile", worldFile, ""); // number of CAD models
if(worldFile!="")
changeWorldFile(worldFile);
//output - path, occupancy vector, scale
printEnv(boost::str(boost::format("%s/OccupancyGrid3D.csv") % output.c_str()), 1);
printYaml(output);
//-------------------------
//WIND
//-------------------------
bool uniformWind;
private_nh.param<bool>("uniformWind", uniformWind, false);
//path to the point cloud files with the wind data
std::string windFileName;
private_nh.param<std::string>("wind_files", windFileName, "");
int idx = 0;
if(uniformWind){
//let's parse the file
std::ifstream infile(windFileName);
std::string line;
std::vector<double> U(env[0].size()*env.size()*env[0][0].size());
std::vector<double> V(env[0].size()*env.size()*env[0][0].size());
std::vector<double> W(env[0].size()*env.size()*env[0][0].size());
while(std::getline(infile, line)){
std::vector<double> v;
for (int i = 0; i < 3; i++)
{
size_t pos = line.find(",");
v.push_back(atof(line.substr(0, pos).c_str()));
line.erase(0, pos + 1);
}
for(int i = 0; i< env[0].size();i++){
for(int j = 0; j< env.size();j++){
for(int k = 0; k< env[0][0].size();k++){
if(env[j][i][k]==cell_state::empty){
U[ indexFrom3D(i, j, k) ] = v[0];
V[ indexFrom3D(i, j, k) ] = v[1];
W[ indexFrom3D(i, j, k) ] = v[2];
}
}
}
}
infile.close();
printWind(U,V,W, boost::str(boost::format("%s_%i.csv") % windFileName % idx).c_str());
idx++;
}
}else{
while (FILE *file = fopen(boost::str(boost::format("%s_%i.csv") % windFileName % idx).c_str(), "r"))
{
fclose(file);
openFoam_to_gaden(boost::str(boost::format("%s_%i.csv") % windFileName % idx).c_str());
idx++;
}
}
ROS_INFO("Preprocessing done");
std_msgs::Bool b;
b.data=true;
pub.publish(b);
}
| 34,170 | C++ | 38.097254 | 182 | 0.504712 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_preprocessing/include/TriangleBoxIntersection.h | #pragma once
/*------------------------------------------------
Adapted from https://gist.github.com/jflipts/fc68d4eeacfcc04fbdb2bf38e0911850#file-triangleboxintersection-h
--------------------------------------------------*/
#include <cmath>
#include <eigen3/Eigen/Dense>
inline void findMinMax(float x0, float x1, float x2, float &min, float &max) {
min = max = x0;
if (x1 < min)
min = x1;
if (x1 > max)
max = x1;
if (x2 < min)
min = x2;
if (x2 > max)
max = x2;
}
inline bool planeBoxOverlap(Eigen::Vector3d normal, Eigen::Vector3d vert, Eigen::Vector3d maxbox) {
Eigen::Vector3d vmin, vmax;
float v;
for (size_t q = 0; q < 3; q++) {
v = vert[q];
if (normal[q] > 0.0f) {
vmin[q] = -maxbox[q] - v;
vmax[q] = maxbox[q] - v;
} else {
vmin[q] = maxbox[q] - v;
vmax[q] = -maxbox[q] - v;
}
}
if (normal.dot(vmin) > 0.0f)
return false;
if (normal.dot(vmax) >= 0.0f)
return true;
return false;
}
/*======================== X-tests ========================*/
inline bool axisTestX01(float a, float b, float fa, float fb, const Eigen::Vector3d &v0,
const Eigen::Vector3d &v2, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p0, float &p2) {
p0 = a * v0.y() - b * v0.z();
p2 = a * v2.y() - b * v2.z();
if (p0 < p2) {
min = p0;
max = p2;
} else {
min = p2;
max = p0;
}
rad = fa * boxhalfsize.y() + fb * boxhalfsize.z();
if (min > rad || max < -rad)
return false;
return true;
}
inline bool axisTestX2(float a, float b, float fa, float fb, const Eigen::Vector3d &v0,
const Eigen::Vector3d &v1, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p0, float &p1) {
p0 = a * v0.y() - b * v0.z();
p1 = a * v1.y() - b * v1.z();
if (p0 < p1) {
min = p0;
max = p1;
} else {
min = p1;
max = p0;
}
rad = fa * boxhalfsize.y() + fb * boxhalfsize.z();
if (min > rad || max < -rad)
return false;
return true;
}
/*======================== Y-tests ========================*/
inline bool axisTestY02(float a, float b, float fa, float fb, const Eigen::Vector3d &v0,
const Eigen::Vector3d &v2, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p0, float &p2) {
p0 = -a * v0.x() + b * v0.z();
p2 = -a * v2.x() + b * v2.z();
if (p0 < p2) {
min = p0;
max = p2;
} else {
min = p2;
max = p0;
}
rad = fa * boxhalfsize.x() + fb * boxhalfsize.z();
if (min > rad || max < -rad)
return false;
return true;
}
inline bool axisTestY1(float a, float b, float fa, float fb, const Eigen::Vector3d &v0,
const Eigen::Vector3d &v1, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p0, float &p1) {
p0 = -a * v0.x() + b * v0.z();
p1 = -a * v1.x() + b * v1.z();
if (p0 < p1) {
min = p0;
max = p1;
} else {
min = p1;
max = p0;
}
rad = fa * boxhalfsize.x() + fb * boxhalfsize.z();
if (min > rad || max < -rad)
return false;
return true;
}
/*======================== Z-tests ========================*/
inline bool axisTestZ12(float a, float b, float fa, float fb, const Eigen::Vector3d &v1,
const Eigen::Vector3d &v2, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p1, float &p2) {
p1 = a * v1.x() - b * v1.y();
p2 = a * v2.x() - b * v2.y();
if (p1 < p2) {
min = p1;
max = p2;
} else {
min = p2;
max = p1;
}
rad = fa * boxhalfsize.x() + fb * boxhalfsize.y();
if (min > rad || max < -rad)
return false;
return true;
}
inline bool axisTestZ0(float a, float b, float fa, float fb, const Eigen::Vector3d &v0,
const Eigen::Vector3d &v1, const Eigen::Vector3d &boxhalfsize, float &rad, float &min,
float &max, float &p0, float &p1) {
p0 = a * v0.x() - b * v0.y();
p1 = a * v1.x() - b * v1.y();
if (p0 < p1) {
min = p0;
max = p1;
} else {
min = p1;
max = p0;
}
rad = fa * boxhalfsize.x() + fb * boxhalfsize.y();
if (min > rad || max < -rad)
return false;
return true;
}
bool triBoxOverlap(Eigen::Vector3d boxcenter, Eigen::Vector3d boxhalfsize, Eigen::Vector3d tv0, Eigen::Vector3d tv1,
Eigen::Vector3d tv2) {
/* use separating axis theorem to test overlap between triangle and box */
/* need to test for overlap in these directions: */
/* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
/* we do not even need to test these) */
/* 2) normal of the triangle */
/* 3) crossproduct(edge from tri, {x,y,z}-directin) */
/* this gives 3x3=9 more tests */
Eigen::Vector3d v0, v1, v2;
float min, max, p0, p1, p2, rad, fex, fey, fez;
Eigen::Vector3d normal, e0, e1, e2;
/* This is the fastest branch on Sun */
/* move everything so that the boxcenter is in (0,0,0) */
v0 = tv0 - boxcenter;
v1 = tv1 - boxcenter;
v2 = tv2 - boxcenter;
/* compute triangle edges */
e0 = v1 - v0;
e1 = v2 - v1;
e2 = v0 - v2;
/* Bullet 3: */
/* test the 9 tests first (this was faster) */
fex = fabsf(e0.x());
fey = fabsf(e0.y());
fez = fabsf(e0.z());
if (!axisTestX01(e0.z(), e0.y(), fez, fey, v0, v2, boxhalfsize, rad, min, max, p0, p2))
return false;
if (!axisTestY02(e0.z(), e0.x(), fez, fex, v0, v2, boxhalfsize, rad, min, max, p0, p2))
return false;
if (!axisTestZ12(e0.y(), e0.x(), fey, fex, v1, v2, boxhalfsize, rad, min, max, p1, p2))
return false;
fex = fabsf(e1.x());
fey = fabsf(e1.y());
fez = fabsf(e1.z());
if (!axisTestX01(e1.z(), e1.y(), fez, fey, v0, v2, boxhalfsize, rad, min, max, p0, p2))
return false;
if (!axisTestY02(e1.z(), e1.x(), fez, fex, v0, v2, boxhalfsize, rad, min, max, p0, p2))
return false;
if (!axisTestZ0(e1.y(), e1.x(), fey, fex, v0, v1, boxhalfsize, rad, min, max, p0, p1))
return false;
fex = fabsf(e2.x());
fey = fabsf(e2.y());
fez = fabsf(e2.z());
if (!axisTestX2(e2.z(), e2.y(), fez, fey, v0, v1, boxhalfsize, rad, min, max, p0, p1))
return false;
if (!axisTestY1(e2.z(), e2.x(), fez, fex, v0, v1, boxhalfsize, rad, min, max, p0, p1))
return false;
if (!axisTestZ12(e2.y(), e2.x(), fey, fex, v1, v2, boxhalfsize, rad, min, max, p1, p2))
return false;
/* Bullet 1: */
/* first test overlap in the {x,y,z}-directions */
/* find min, max of the triangle each direction, and test for overlap in */
/* that direction -- this is equivalent to testing a minimal AABB around */
/* the triangle against the AABB */
/* test in X-direction */
findMinMax(v0.x(), v1.x(), v2.x(), min, max);
if (min > boxhalfsize.x() || max < -boxhalfsize.x())
return false;
/* test in Y-direction */
findMinMax(v0.y(), v1.y(), v2.y(), min, max);
if (min > boxhalfsize.y() || max < -boxhalfsize.y())
return false;
/* test in Z-direction */
findMinMax(v0.z(), v1.z(), v2.z(), min, max);
if (min > boxhalfsize.z() || max < -boxhalfsize.z())
return false;
/* Bullet 2: */
/* test if the box intersects the plane of the triangle */
/* compute plane equation of triangle: normal*x+d=0 */
normal = e0.cross(e1);
if (!planeBoxOverlap(normal, v0, boxhalfsize))
return false;
return true; /* box and triangle overlaps */
} | 7,029 | C | 27.811475 | 116 | 0.577038 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_player/package.xml | <package>
<name>gaden_player</name>
<version>1.0.0</version>
<description> This package loads the log files (results) from the gaden_simulator pkg, and provides services to evaluate the gas concentration and wind vector at a given location. The goal is to provide a fast (real time) service for the simulated MOX and Anemometer sensors.</description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<author>Javier Monroy</author>
<!-- Dependencies which this package needs to build itself. -->
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>roscpp</build_depend>
<build_depend>visualization_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<build_depend>tf</build_depend>
<build_depend>message_generation</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>roscpp</run_depend>
<run_depend>visualization_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>tf</run_depend>
<run_depend>nav_msgs</run_depend>
<run_depend>message_runtime</run_depend>
</package>
| 1,206 | XML | 39.233332 | 291 | 0.737148 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_player/src/simulation_player.h | #include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_listener.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Float32MultiArray.h>
#include <visualization_msgs/Marker.h>
#include <gaden_player/GasPosition.h>
#include <gaden_player/WindPosition.h>
#include <cstdlib>
#include <math.h>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <map>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/iostreams/copy.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
struct Filament{
public:
double x, y, z, sigma;
Filament(double a, double b, double c, double d){
x=a;
y=b;
z=c;
sigma=d;
}
};
// CLASS for every simulation to run. If two gas sources are needed, just create 2 instances!
class sim_obj
{
public:
sim_obj(std::string filepath, bool load_wind_info);
~sim_obj();
std::string gas_type;
std::string simulation_filename;
int environment_cells_x, environment_cells_y, environment_cells_z;
double environment_cell_size;
double source_pos_x, source_pos_y, source_pos_z;
double env_min_x; //[m]
double env_max_x; //[m]
double env_min_y; //[m]
double env_max_y; //[m]
double env_min_z; //[m]
double env_max_z; //[m]
bool load_wind_data;
std::vector<double> C; //3D Gas concentration
std::vector<double> U; //3D Wind U
std::vector<double> V; //3D Wind V
std::vector<double> W; //3D Wind W
bool first_reading;
bool filament_log;
double total_moles_in_filament;
double num_moles_all_gases_in_cm3;
std::map<int, Filament> activeFilaments;
std::vector<uint8_t> Env;
//methods
void configure_environment();
void readEnvFile();
void load_data_from_logfile(int sim_iteration);
void load_ascii_file(std::stringstream &decompressed);
void load_binary_file(std::stringstream &decompressed);
double get_gas_concentration(float x, float y, float z);
double concentration_from_filament(float x, float y, float z, Filament fil);
bool check_environment_for_obstacle(double start_x, double start_y, double start_z,
double end_x, double end_y, double end_z);
int check_pose_with_environment(double pose_x, double pose_y, double pose_z);
void get_wind_value(float x, float y, float z, double &u, double &v, double &w);
void get_concentration_as_markers(visualization_msgs::Marker &mkr_points);
void read_headers(std::stringstream &inbuf, std::string &line);
void load_wind_file(int wind_index);
int last_wind_idx=-1;
void read_concentration_line(std::string line);
std::vector<std::vector<double> > heatmap;
void updateHeatmap();
void writeHeatmapImage();
int indexFrom3D(int x, int y, int z);
std::string gasTypesByCode[14] = {
"ethanol",
"methane",
"hydrogen",
"propanol",
"chlorine",
"flurorine",
"acetone",
"neon",
"helium",
"biogas",
"butane",
"carbon dioxide",
"carbon monoxide",
"smoke"
};
};
// ---------------------- MAIN--------------------//
// Parameters
double player_freq;
int num_simulators;
bool verbose;
std::vector<std::string> simulation_data;
std::vector<sim_obj> player_instances; //To handle N simulations at a time.
int initial_iteration, loop_from_iteration, loop_to_iteration;
bool allow_looping;
std::string occupancyFile;
bool createHeatmapImage;
std::string heatmapPath;
float heatmapHeight;
double heatmapThreshold;
int heatMapIterations;
//Visualization
ros::Publisher marker_pub;
visualization_msgs::Marker mkr_gas_points; //We will create an array of particles according to cell concentration
//functions:
void loadNodeParameters(ros::NodeHandle private_nh);
void init_all_simulation_instances();
void load_all_data_from_logfiles(int sim_iteration);
void display_current_gas_distribution();
| 4,550 | C | 29.543624 | 135 | 0.617582 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_player/src/simulation_player.cpp | /*--------------------------------------------------------------------------------
* Pkg for playing the simulation results of the "filament_simulator" pkg.
* It allows to run on real time, and provide services to simulated sensors (gas, wind)
* It supports loading several simulations at a time, which allows multiple gas sources and gas types
* It also generates a point cloud representing the gas concentration [ppm] on the 3D environment
--------------------------------------------------------------------------------*/
#include <boost/format.hpp>
#include "simulation_player.h"
//--------------- SERVICES CALLBACKS----------------------//
gaden_player::GasInCell get_all_gases_single_cell(float x, float y, float z, const std::vector<std::string>& gas_types)
{
std::vector<double> srv_response_gas_concs(num_simulators);
std::map<std::string,double> concentrationByGasType;
for(int i=0;i<gas_types.size();i++)
concentrationByGasType[gas_types[i]] = 0;
//Get all gas concentrations and gas types (from all instances)
for (int i=0;i<num_simulators; i++)
concentrationByGasType[player_instances[i].gas_type] += player_instances[i].get_gas_concentration(x, y, z);
//Configure Response
gaden_player::GasInCell response;
for (int i = 0; i< gas_types.size();i++)
{
response.concentration.push_back( concentrationByGasType[gas_types[i]] );
}
return response;
}
bool get_gas_value_srv(gaden_player::GasPosition::Request &req, gaden_player::GasPosition::Response &res)
{
std::set<std::string> gas_types;
for (int i=0;i<num_simulators; i++)
gas_types.insert(player_instances[i].gas_type);
std::vector<std::string> gast_types_v(gas_types.begin(), gas_types.end());
res.gas_type = gast_types_v;
for(int i=0;i<req.x.size(); i++)
{
res.positions.push_back( get_all_gases_single_cell(req.x[i], req.y[i], req.z[i], gast_types_v) );
}
return true;
}
bool get_wind_value_srv(gaden_player::WindPosition::Request &req, gaden_player::WindPosition::Response &res)
{
//Since the wind fields are identical among different instances, return just the information from instance[0]
for(int i = 0; i<req.x.size(); i++){
double u, v, w;
player_instances[0].get_wind_value(req.x[i], req.y[i], req.z[i], u, v, w);
res.u.push_back(u);
res.v.push_back(v);
res.w.push_back(w);
}
return true;
}
//------------------------ MAIN --------------------------//
int main( int argc, char** argv )
{
ros::init(argc, argv, "simulation_player");
ros::NodeHandle n;
ros::NodeHandle pn("~");
//Read Node Parameters
loadNodeParameters(pn);
//Publishers
marker_pub = n.advertise<visualization_msgs::Marker>("Gas_Distribution", 1);
//Services offered
ros::ServiceServer serviceGas = n.advertiseService("odor_value", get_gas_value_srv);
ros::ServiceServer serviceWind = n.advertiseService("wind_value", get_wind_value_srv);
//Init variables
init_all_simulation_instances();
ros::Time time_last_loaded_file = ros::Time::now();
srand(time(NULL));// initialize random seed
//Init Markers for RVIZ visualization
mkr_gas_points.header.frame_id = "map";
mkr_gas_points.header.stamp = ros::Time::now();
mkr_gas_points.ns = "Gas_Dispersion";
mkr_gas_points.action = visualization_msgs::Marker::ADD;
mkr_gas_points.type = visualization_msgs::Marker::POINTS; //Marker type
mkr_gas_points.id = 0; //One marker with multiple points.
mkr_gas_points.scale.x = 0.025;
mkr_gas_points.scale.y = 0.025;
mkr_gas_points.scale.z = 0.025;
mkr_gas_points.pose.orientation.w = 1.0;
// Loop
ros::Rate r(100); //Set max rate at 100Hz (for handling services - Top Speed!!)
int iteration_counter = initial_iteration;
while (ros::ok())
{
if( (ros::Time::now() - time_last_loaded_file).toSec() >= 1/player_freq )
{
if (verbose)
ROS_INFO("[Player] Playing simulation iteration %i", iteration_counter);
//Read Gas and Wind data from log_files
load_all_data_from_logfiles(iteration_counter); //On the first time, we configure gas type, source pos, etc.
display_current_gas_distribution(); //Rviz visualization
iteration_counter++;
//Looping?
if (allow_looping)
{
if (iteration_counter >= loop_to_iteration)
{
iteration_counter = loop_from_iteration;
if (verbose)
ROS_INFO("[Player] Looping");
}
}
time_last_loaded_file = ros::Time::now();
}
//Attend service request at max rate!
//This allows sensors to have higher sampling rates than the simulation update
ros::spinOnce();
r.sleep();
}
}
//Load Node parameters
void loadNodeParameters(ros::NodeHandle private_nh)
{
//player_freq
private_nh.param<bool>("verbose", verbose, false);
//player_freq
private_nh.param<double>("player_freq", player_freq, 1); //Hz
//Number of simulators to load (For simulating multiple gases and multiple sources)
private_nh.param<int>("num_simulators", num_simulators, 1);
if (verbose)
{
ROS_INFO("[Player] player_freq %.2f", player_freq);
ROS_INFO("[Player] num_simulators: %i", num_simulators);
}
//FilePath for simulated data
simulation_data.resize(num_simulators);
for (int i=0;i<num_simulators; i++)
{
//Get location of simulation data for instance (i)
std::string paramName = boost::str( boost::format("simulation_data_%i") % i);
private_nh.param<std::string>(paramName.c_str(),simulation_data[i], "");
if (verbose)
ROS_INFO("[Player] simulation_data_%i: %s", i, simulation_data[i].c_str());
}
// Initial iteration
private_nh.param<int>("initial_iteration", initial_iteration, 1);
private_nh.param<std::string>("occupancyFile", occupancyFile, "");
private_nh.param<bool>("createHeatmapImage", createHeatmapImage, false);
private_nh.param<std::string>("heatmapPath",heatmapPath, "");
private_nh.param<float>("heatmapHeight", heatmapHeight, 0.5);
private_nh.param<int>("heatMapIterations", heatMapIterations, 100);
private_nh.param<double>("heatmapThreshold", heatmapThreshold, 0.5);
// Loop
private_nh.param<bool>("allow_looping", allow_looping, false);
private_nh.param<int>("loop_from_iteration", loop_from_iteration, 1);
private_nh.param<int>("loop_to_iteration", loop_to_iteration, 1);
}
//Init
void init_all_simulation_instances()
{
ROS_INFO("[Player] Initializing %i instances",num_simulators);
// At least one instance is needed which loads the wind field data!
sim_obj so(simulation_data[0], true);
player_instances.push_back(so);
//Create other instances, but do not save wind information! It is the same for all instances
for (int i=1;i<num_simulators;i++)
{
sim_obj so(simulation_data[i], false);
player_instances.push_back(so);
}
//Set size for service responses
}
//Load new Iteration of the Gas&Wind State on the 3d environment
void load_all_data_from_logfiles(int sim_iteration)
{
//Load corresponding data for each instance (i.e for every gas source)
for (int i=0;i<num_simulators;i++)
{
if (verbose)
ROS_INFO("[Player] Loading new data to instance %i (iteration %i)",i,sim_iteration);
player_instances[i].load_data_from_logfile(sim_iteration);
}
}
//Display in RVIZ the gas distribution
void display_current_gas_distribution()
{
//Remove previous data points
mkr_gas_points.points.clear();
mkr_gas_points.colors.clear();
for (int i=0;i<num_simulators;i++)
{
player_instances[i].get_concentration_as_markers(mkr_gas_points);
}
//Display particles
marker_pub.publish(mkr_gas_points);
}
//==================================== SIM_OBJ ==============================//
// Constructor
sim_obj::sim_obj(std::string filepath, bool load_wind_info)
{
gas_type = "unknown";
simulation_filename = filepath;
environment_cells_x = environment_cells_y = environment_cells_z = 0;
environment_cell_size = 0.0; //m
source_pos_x = source_pos_y = source_pos_z = 0.0; //m
load_wind_data = load_wind_info;
first_reading = true;
filament_log=false;
}
sim_obj::~sim_obj(){}
void sim_obj::read_concentration_line(std::string line){
size_t pos;
double conc, u, v, w;
int x, y, z;
//A line has the format x y z conc u v w
pos = line.find(" ");
x = atoi(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
y = atoi(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
z = atoi(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
conc = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
u = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
v = atof(line.substr(0, pos).c_str());
w = atof(line.substr(pos + 1).c_str());
//Save data to internal storage
C[indexFrom3D(x,y,z)] = conc / 1000;
if (load_wind_data)
{
U[indexFrom3D(x,y,z)] = u / 1000;
V[indexFrom3D(x,y,z)] = v / 1000;
W[indexFrom3D(x,y,z)] = w / 1000;
}
}
void sim_obj::read_headers(std::stringstream &inbuf, std::string &line){
std::getline(inbuf, line);
//Line 1 (min values of environment)
size_t pos = line.find(" ");
line.erase(0, pos + 1);
pos = line.find(" ");
env_min_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
env_min_y = atof(line.substr(0, pos).c_str());
env_min_z = atof(line.substr(pos + 1).c_str());
std::getline(inbuf, line);
//Line 2 (max values of environment)
pos = line.find(" ");
line.erase(0, pos + 1);
pos = line.find(" ");
env_max_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
env_max_y = atof(line.substr(0, pos).c_str());
env_max_z = atof(line.substr(pos + 1).c_str());
std::getline(inbuf, line);
//Get Number of cells (X,Y,Z)
pos = line.find(" ");
line.erase(0, pos + 1);
pos = line.find(" ");
environment_cells_x = atoi(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
environment_cells_y = atoi(line.substr(0, pos).c_str());
environment_cells_z = atoi(line.substr(pos + 1).c_str());
std::getline(inbuf, line);
//Get Cell_size
pos = line.find(" ");
line.erase(0, pos + 1);
pos = line.find(" ");
environment_cell_size = atof(line.substr(0, pos).c_str());
std::getline(inbuf, line);
//Get GasSourceLocation
pos = line.find(" ");
line.erase(0, pos + 1);
pos = line.find(" ");
source_pos_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos + 1);
pos = line.find(" ");
source_pos_y = atof(line.substr(0, pos).c_str());
source_pos_z = atof(line.substr(pos + 1).c_str());
std::getline(inbuf, line);
//Get Gas_Type
pos = line.find(" ");
gas_type = line.substr(pos + 1);
//Configure instances
configure_environment();
std::getline(inbuf, line);
std::getline(inbuf, line);
std::getline(inbuf, line);
}
//Load a new file with Gas+Wind data
void sim_obj::load_data_from_logfile(int sim_iteration)
{
std::string filename = boost::str( boost::format("%s/iteration_%i") % simulation_filename.c_str() % sim_iteration);
FILE* fileCheck;
if ((fileCheck =fopen(filename.c_str(),"rb"))==NULL){
ROS_ERROR("File %s does not exist\n", filename.c_str());
return;
}
fclose(fileCheck);
std::ifstream infile(filename, std::ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::zlib_decompressor());
inbuf.push(infile);
std::stringstream decompressed;
boost::iostreams::copy(inbuf,decompressed);
//if the file starts with a 1, the contents are in binary
int check=0;
decompressed.read((char*) &check, sizeof(int));
if (check==1){
filament_log=true;
load_binary_file(decompressed);
}
else
load_ascii_file(decompressed);
infile.close();
static int iterationCounter=0;
if(createHeatmapImage){
if(iterationCounter<heatMapIterations)
updateHeatmap();
else if(iterationCounter==heatMapIterations)
writeHeatmapImage();
iterationCounter++;
}
}
void sim_obj::load_ascii_file(std::stringstream& decompressed){
std::string line;
size_t pos;
double conc, u, v, w;
int x, y, z;
if (first_reading)
{
read_headers(decompressed, line);
first_reading=false;
}
else{
//if already initialized, skip the header
for(int i=0; i<8; i++){
std::getline(decompressed, line);
}
}
do
{
read_concentration_line(line);
}while (std::getline(decompressed, line));
}
void sim_obj::load_binary_file(std::stringstream& decompressed){
if(first_reading){
double bufferD [5];
decompressed.read((char*) &env_min_x, sizeof(double));
decompressed.read((char*) &env_min_y, sizeof(double));
decompressed.read((char*) &env_min_z, sizeof(double));
decompressed.read((char*) &env_max_x, sizeof(double));
decompressed.read((char*) &env_max_y, sizeof(double));
decompressed.read((char*) &env_max_z, sizeof(double));
decompressed.read((char*) &environment_cells_x, sizeof(int));
decompressed.read((char*) &environment_cells_y, sizeof(int));
decompressed.read((char*) &environment_cells_z, sizeof(int));
decompressed.read((char*) &environment_cell_size, sizeof(double));
decompressed.read((char*) &bufferD, 5*sizeof(double));
int gt;
decompressed.read((char*) >, sizeof(int));
gas_type=gasTypesByCode[gt];
decompressed.read((char*) &total_moles_in_filament, sizeof(double));
decompressed.read((char*) &num_moles_all_gases_in_cm3, sizeof(double));
configure_environment();
first_reading=false;
}else{
//skip headers
decompressed.seekg(14*sizeof(double) + 5*sizeof(int));
}
int wind_index;
decompressed.read((char*) &wind_index, sizeof(int));
activeFilaments.clear();
int filament_index;
double x, y, z, stdDev;
while(decompressed.peek()!=EOF){
decompressed.read((char*) &filament_index, sizeof(int));
decompressed.read((char*) &x, sizeof(double));
decompressed.read((char*) &y, sizeof(double));
decompressed.read((char*) &z, sizeof(double));
decompressed.read((char*) &stdDev, sizeof(double));
std::pair<int, Filament> pair(filament_index, Filament(x, y, z, stdDev));
activeFilaments.insert(pair);
}
load_wind_file(wind_index);
}
void sim_obj::load_wind_file(int wind_index){
if(wind_index==last_wind_idx)
return;
last_wind_idx=wind_index;
std::ifstream infile(boost::str( boost::format("%s/wind/wind_iteration_%i") % simulation_filename.c_str() % wind_index), std::ios_base::binary);
infile.read((char*) U.data(), sizeof(double)* U.size());
infile.read((char*) V.data(), sizeof(double)* U.size());
infile.read((char*) W.data(), sizeof(double)* U.size());
infile.close();
}
//Get Gas concentration at lcoation (x,y,z)
double sim_obj::get_gas_concentration(float x, float y, float z)
{
int xx,yy,zz;
xx = (int)ceil((x - env_min_x)/environment_cell_size);
yy = (int)ceil((y - env_min_y)/environment_cell_size);
zz = (int)ceil((z - env_min_z)/environment_cell_size);
if(xx<0|| xx>environment_cells_x
|| yy<0|| yy>environment_cells_y
|| zz<0|| zz>environment_cells_z)
{
ROS_ERROR("Requested gas concentration at a point outside the environment (%f, %f, %f). Are you using the correct coordinates?\n", x, y ,z);
return 0;
}
double gas_conc=0;
if(filament_log){
for(auto it = activeFilaments.begin(); it!=activeFilaments.end(); it++){
Filament fil = it->second;
double distSQR = (x-fil.x)*(x-fil.x) + (y-fil.y)*(y-fil.y) + (z-fil.z)*(z-fil.z);
double limitDistance = fil.sigma*5/100;
if(distSQR < limitDistance * limitDistance && check_environment_for_obstacle(x, y, z, fil.x, fil.y, fil.z)){
gas_conc += concentration_from_filament(x, y, z, fil);
}
}
}else{
//Get cell idx from point location
//Get gas concentration from that cell
gas_conc = C[indexFrom3D(xx,yy,zz)];
}
return gas_conc;
}
double sim_obj::concentration_from_filament(float x, float y, float z, Filament filament){
//calculate how much gas concentration does one filament contribute to the queried location
double sigma = filament.sigma;
double distance_cm = 100 * sqrt( pow(x-filament.x,2) + pow(y-filament.y,2) + pow(z-filament.z,2) );
double num_moles_target_cm3 = (total_moles_in_filament /
(sqrt(8*pow(M_PI,3)) * pow(sigma,3) )) * exp( -pow(distance_cm,2)/(2*pow(sigma,2)) );
double ppm = num_moles_target_cm3/num_moles_all_gases_in_cm3 * 1000000; //parts of target gas per million
return ppm;
}
bool sim_obj::check_environment_for_obstacle(double start_x, double start_y, double start_z,
double end_x, double end_y, double end_z)
{
// Check whether one of the points is outside the valid environment or is not free
if(check_pose_with_environment(start_x, start_y, start_z) != 0) { return false; }
if(check_pose_with_environment( end_x, end_y , end_z) != 0) { return false; }
// Calculate normal displacement vector
double vector_x = end_x - start_x;
double vector_y = end_y - start_y;
double vector_z = end_z - start_z;
double distance = sqrt(vector_x*vector_x + vector_y*vector_y + vector_z*vector_z);
vector_x = vector_x/distance;
vector_y = vector_y/distance;
vector_z = vector_z/distance;
// Traverse path
int steps = ceil( distance / environment_cell_size ); // Make sure no two iteration steps are separated more than 1 cell
double increment = distance/steps;
for(int i=1; i<steps-1; i++)
{
// Determine point in space to evaluate
double pose_x = start_x + vector_x*increment*i;
double pose_y = start_y + vector_y*increment*i;
double pose_z = start_z + vector_z*increment*i;
// Determine cell to evaluate (some cells might get evaluated twice due to the current code
int x_idx = floor( (pose_x-env_min_x)/environment_cell_size );
int y_idx = floor( (pose_y-env_min_y)/environment_cell_size );
int z_idx = floor( (pose_z-env_min_z)/environment_cell_size );
// Check if the cell is occupied
if(Env[indexFrom3D(x_idx,y_idx,z_idx)] != 0) { return false; }
}
// Direct line of sight confirmed!
return true;
}
int sim_obj::check_pose_with_environment(double pose_x, double pose_y, double pose_z)
{
//1.1 Check that pose is within the boundingbox environment
if (pose_x<env_min_x || pose_x>env_max_x || pose_y<env_min_y || pose_y>env_max_y || pose_z<env_min_z || pose_z>env_max_z)
return 1;
//Get 3D cell of the point
int x_idx = (pose_x-env_min_x)/environment_cell_size;
int y_idx = (pose_y-env_min_y)/environment_cell_size;
int z_idx = (pose_z-env_min_z)/environment_cell_size;
if (x_idx >= environment_cells_x || y_idx >= environment_cells_y || z_idx >= environment_cells_z)
return 1;
//1.2. Return cell occupancy (0=free, 1=obstacle, 2=outlet)
return Env[indexFrom3D(x_idx,y_idx,z_idx)];
}
//Get Wind concentration at lcoation (x,y,z)
void sim_obj::get_wind_value(float x, float y, float z, double &u, double &v, double &w)
{
if (load_wind_data)
{
int xx,yy,zz;
xx = (int)ceil((x - env_min_x)/environment_cell_size);
yy = (int)ceil((y - env_min_y)/environment_cell_size);
zz = (int)ceil((z - env_min_z)/environment_cell_size);
if(xx<0|| xx>environment_cells_x
|| yy<0|| yy>environment_cells_y
|| zz<0|| zz>environment_cells_z)
{
ROS_ERROR("Requested gas concentration at a point outside the environment. Are you using the correct coordinates?\n");
return;
}
//Set wind vectors from that cell
u = U[indexFrom3D(xx,yy,zz)];
v = V[indexFrom3D(xx,yy,zz)];
w = W[indexFrom3D(xx,yy,zz)];
}
else
{
if (verbose)
ROS_WARN("[Player] Request to provide Wind information when No Wind data is available!!");
}
}
void sim_obj::readEnvFile()
{
if(occupancyFile==""){
ROS_ERROR(" [GADEN_PLAYER] No occupancy file specified. Use the parameter \"occupancyFile\" to input the path to the OccupancyGrid3D.csv file.\n");
return;
}
Env.resize(environment_cells_x * environment_cells_y * environment_cells_z);
//open file
std::ifstream infile(occupancyFile.c_str());
std::string line;
//discard the header
std::getline(infile, line);
std::getline(infile, line);
std::getline(infile, line);
std::getline(infile, line);
int x_idx = 0;
int y_idx = 0;
int z_idx = 0;
while ( std::getline(infile, line) )
{
std::stringstream ss(line);
if (z_idx >=environment_cells_z)
{
ROS_ERROR("Trying to read:[%s]",line.c_str());
}
if (line == ";")
{
//New Z-layer
z_idx++;
x_idx = 0;
y_idx = 0;
}
else
{ //New line with constant x_idx and all the y_idx values
while (ss)
{
double f;
ss >> std::skipws >> f; //get one double value
Env[indexFrom3D(x_idx,y_idx,z_idx)] = f;
y_idx++;
}
//Line has ended
x_idx++;
y_idx = 0;
}
}
infile.close();
}
//Init instances (for running multiple simulations)
void sim_obj::configure_environment()
{
//ROS_INFO("Configuring Enviroment");
//ROS_INFO("\t\t Dimension: [%i,%i,%i] cells", environment_cells_x, environment_cells_y, environment_cells_z);
//ROS_INFO("\t\t Gas_Type: %s", gas_type.c_str());
//ROS_INFO("\t\t FilePath: %s", simulation_filename.c_str());
//ROS_INFO("\t\t Source at location: [%.4f,%.4f,%.4f][m] ", source_pos_x, source_pos_y, source_pos_z);
//ROS_INFO("\t\t Loading Wind Data: %i", load_wind_data);
//Resize Gas Concentration container
C.resize(environment_cells_x * environment_cells_y * environment_cells_z);
//Resize Wind info container (if necessary)
if (load_wind_data)
{
U.resize(environment_cells_x * environment_cells_y * environment_cells_z);
V.resize(environment_cells_x * environment_cells_y * environment_cells_z);
W.resize(environment_cells_x * environment_cells_y * environment_cells_z);
}
readEnvFile();
if(createHeatmapImage)
heatmap = std::vector<std::vector<double> >(environment_cells_x, std::vector<double>(environment_cells_y));
}
void sim_obj::get_concentration_as_markers(visualization_msgs::Marker &mkr_points)
{
if(!filament_log){
//For every cell, generate as much "marker points" as [ppm]
for (int i=0;i<environment_cells_x;i++)
{
for (int j=0;j<environment_cells_y;j++)
{
for (int k=0;k<environment_cells_z;k++)
{
geometry_msgs::Point p; //Location of point
std_msgs::ColorRGBA color; //Color of point
double gas_value = C[indexFrom3D(i,j,k)];
for (int N=0;N<(int)round(gas_value/2);N++)
{
//Set point position (corner of the cell + random)
p.x = env_min_x + (i+0.5)*environment_cell_size + ((rand()%100)/100.0f)*environment_cell_size;
p.y = env_min_y + (j+0.5)*environment_cell_size + ((rand()%100)/100.0f)*environment_cell_size;
p.z = env_min_z + (k+0.5)*environment_cell_size + ((rand()%100)/100.0f)*environment_cell_size;
//Set color of particle according to gas type
color.a = 1.0;
if (!strcmp(gas_type.c_str(),"ethanol"))
{
color.r=0.2; color.g=0.9; color.b=0;
}
else if (!strcmp(gas_type.c_str(),"methane"))
{
color.r=0.9; color.g=0.1; color.b=0.1;
}
else if (!strcmp(gas_type.c_str(),"hydrogen"))
{
color.r=0.2; color.g=0.1; color.b=0.9;
}
else if (!strcmp(gas_type.c_str(),"propanol"))
{
color.r=0.8; color.g=0.8; color.b=0;
}
else if (!strcmp(gas_type.c_str(),"chlorine"))
{
color.r=0.8; color.g=0; color.b=0.8;
}
else if (!strcmp(gas_type.c_str(),"flurorine"))
{
color.r=0.0; color.g=0.8; color.b=0.8;
}
else if (!strcmp(gas_type.c_str(),"acetone"))
{
color.r=0.9; color.g=0.2; color.b=0.2;
}
else if (!strcmp(gas_type.c_str(),"neon"))
{
color.r=0.9; color.g=0; color.b=0;
}
else if (!strcmp(gas_type.c_str(),"helium"))
{
color.r=0.9; color.g=0; color.b=0;
}
else if (!strcmp(gas_type.c_str(),"hot_air"))
{
color.r=0.9; color.g=0; color.b=0;
}
else
{
ROS_INFO("[player] Setting Defatul Color");
color.r = 0.9; color.g = 0;color.b = 0;
}
//Add particle marker
mkr_points.points.push_back(p);
mkr_points.colors.push_back(color);
}
}
}
}
}
else{
for(auto it = activeFilaments.begin(); it!=activeFilaments.end(); it++){
geometry_msgs::Point p; //Location of point
std_msgs::ColorRGBA color; //Color of point
Filament filament = it->second;
for (int i=0; i<5; i++){
p.x=(filament.x)+((std::rand()%1000)/1000.0 -0.5) * filament.sigma/200;
p.y=(filament.y)+((std::rand()%1000)/1000.0 -0.5) * filament.sigma/200;
p.z=(filament.z)+((std::rand()%1000)/1000.0 -0.5) * filament.sigma/200;
color.a=1;
color.r=0;
color.g=1;
color.b=0;
//Add particle marker
mkr_points.points.push_back(p);
mkr_points.colors.push_back(color);
}
}
}
}
int sim_obj::indexFrom3D(int x, int y, int z){
return x + y*environment_cells_x + z*environment_cells_x*environment_cells_y;
}
void sim_obj::updateHeatmap(){
#pragma omp parallel for collapse(2)
for(int i = 0; i<heatmap.size(); i++){
for(int j=0; j<heatmap[0].size(); j++){
double p_x = env_min_x + (i+0.5)*environment_cell_size;
double p_y = env_min_y + (j+0.5)*environment_cell_size;
double g_c = get_gas_concentration(p_x, p_y, heatmapHeight);
if(g_c>heatmapThreshold)
heatmap[i][j]++;
}
}
}
void sim_obj::writeHeatmapImage(){
//std::ofstream pgmFile ("/home/pepe/catkin_ws/asd");
//pgmFile<<"P2\n";
//pgmFile<<heatmap[0].size()<<" "<<heatmap.size()<<"\n";
//pgmFile<<"255\n";
//for(int i = 0; i<heatmap.size(); i++){
// for(int j=0; j<heatmap[0].size(); j++){
// pgmFile<< (int)((heatmap[i][j]/heatMapIterations) * 255) <<" ";
// }
// pgmFile<<"\n";
//}
cv::Mat image(cv::Size(heatmap.size(), heatmap[0].size()), CV_32F, cv::Scalar(0) );
#pragma omp parallel for collapse(2)
for(int i = 0; i<heatmap.size(); i++){
for(int j=0; j<heatmap[0].size(); j++){
image.at<float>(heatmap[0].size()-1-j, i) = (heatmap[i][j]/heatMapIterations) * 255;
}
}
cv::imwrite(heatmapPath, image);
std::cout<<"Heatmap image saved\n";
} | 29,208 | C++ | 32.728637 | 155 | 0.570837 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_filament_simulator/package.xml | <package>
<name>gaden_filament_simulator</name>
<version>1.0.0</version>
<description>Implements the filament-based gas dispersal simulation. Gases with different densities are simulated such as: ethanol, methane and hydrogen etc.</description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<author>Javier Monroy</author>
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>roscpp</build_depend>
<build_depend>visualization_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>roscpp</run_depend>
<run_depend>visualization_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>nav_msgs</run_depend>
</package>
| 884 | XML | 30.607142 | 173 | 0.735294 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_filament_simulator/src/filament_simulator.cpp | /*---------------------------------------------------------------------------------------
* MAIN Node for the simulation of gas dispersal using a Filament-based approach.
* This node loads the wind field (usually from CFD simulation), and simulates over it
* different filaments to spread gas particles.
*
* Each filament is composed of a fixed number of gas molecules (Q)
* Each filament is determined by its center position and width.
* The width of a filament increases over time (Turbulent and molecular difussion)
* The position of a filament is updated with the wind.
*
* The gas concentration at a given point is the sum of the concentration of all filaments.
*
* Thus, the gas concentration at the source location is determined by the number of molecules/filament and the number of filaments.
*
* A log file is recorded for every snapshot (time-step) with information about the gas
* concentration and wind vector for every cell (3D) of the environment.
*
* The node implements the filament-base gas dispersal simulation. At each time step, the puffs
* of filaments are sequentially released at a source location. Each puff is composed of n filaments.
* Filaments are affected by turbulence and molecular diffusion along its path while being transported
* by advection with the wind. The 3-dimensional positions of these filaments are represented by the points
* of the “visualization msgs/markers”. At each time step, “Dispersal_Simulation” node calculates or
* determines the positions of n filaments. Gas plumes are simulated with or without acceleration.
*
* It is very time consuming, and currently it runs in just one thread (designed to run offline).
*
* TODO: Cambiar std::vector por std::list para los FILAMENTOS
---------------------------------------------------------------------------------------*/
#include "filament_simulator/filament_simulator.h"
//==========================//
// Constructor //
//==========================//
CFilamentSimulator::CFilamentSimulator()
{
//Read parameters
loadNodeParameters();
//Create directory to save results (if needed)
if (save_results && !boost::filesystem::exists(results_location)){
if (!boost::filesystem::create_directories(results_location))
ROS_ERROR("[filament] Could not create result directory: %s", results_location.c_str());
if (!boost::filesystem::create_directories(boost::str(boost::format("%s/wind") % results_location) ) )
ROS_ERROR("[filament] Could not create result directory: %s", results_location.c_str());
}
//Set Publishers and Subscribers
//-------------------------------
marker_pub = n.advertise<visualization_msgs::Marker>("filament_visualization", 1);
// Wait preprocessing Node to finish?
preprocessing_done = false;
if(wait_preprocessing)
{
prepro_sub = n.subscribe("preprocessing_done", 1, &CFilamentSimulator::preprocessingCB, this);
while(ros::ok() && !preprocessing_done)
{
ros::Duration(0.5).sleep();
ros::spinOnce();
if (verbose) ROS_INFO("[filament] Waiting for node GADEN_preprocessing to end.");
}
}
//Init variables
//-----------------
sim_time = 0.0; //Start at time = 0(sec)
sim_time_last_wind = -2*windTime_step; //Force to load wind-data on startup
current_wind_snapshot = 0; //Start with wind_iter= 0;
current_simulation_step = 0; //Start with iter= 0;
last_saved_step = -1;
wind_notified = false; //To warn the user (only once) that no more wind data is found!
wind_finished = false;
//Init the Simulator
initSimulator();
//Fluid Dynamics Eq
/*/-----------------
* Ideal gas equation:
* PV = nRT
* P is the pressure of the gas (atm)
* V is the volume of the gas (cm^3)
* n is the amount of substance of gas (mol) = m/M where m=mass of the gas [g] and M is the molar mass
* R is the ideal, or universal, gas constant, equal to the product of the Boltzmann constant and the Avogadro constant. (82.057338 cm^3·atm/mol·k)
* T is the temperature of the gas (kelvin)
*/
double R = 82.057338; //[cm³·atm/mol·K] Gas Constant
filament_initial_vol = pow(6*filament_initial_std,3); //[cm³] -> We approximate the infinite volumen of the 3DGaussian as 6 sigmas.
env_cell_vol = pow(cell_size*100,3); //[cm³] Volumen of a cell
filament_numMoles = (envPressure*filament_initial_vol)/(R*envTemperature);//[mol] Num of moles of Air in that volume
env_cell_numMoles = (envPressure*env_cell_vol)/(R*envTemperature); //[mol] Num of moles of Air in that volume
//The moles of target_gas in a Filament are distributted following a 3D Gaussian
//Given the ppm value at the center of the filament, we approximate the total number of gas moles in that filament.
double numMoles_in_cm3 = envPressure/(R*envTemperature); //[mol of all gases/cm³]
double filament_moles_cm3_center = filament_ppm_center/pow(10,6)* numMoles_in_cm3; //[moles of target gas / cm³]
filament_numMoles_of_gas = filament_moles_cm3_center * ( sqrt(8*pow(3.14159,3))*pow(filament_initial_std,3) ); //total number of moles in a filament
if (verbose) ROS_INFO("[filament] filament_initial_vol [cm3]: %f",filament_initial_vol);
if (verbose) ROS_INFO("[filament] env_cell_vol [cm3]: %f",env_cell_vol);
if (verbose) ROS_INFO("[filament] filament_numMoles [mol]: %E",filament_numMoles);
if (verbose) ROS_INFO("[filament] env_cell_numMoles [mol]: %E",env_cell_numMoles);
if (verbose) ROS_INFO("[filament] filament_numMoles_of_gas [mol]: %E",filament_numMoles_of_gas);
//Init visualization
//-------------------
filament_marker.header.frame_id = fixed_frame;
filament_marker.ns = "filaments";
filament_marker.action = visualization_msgs::Marker::ADD;
filament_marker.id = 0;
filament_marker.type = visualization_msgs::Marker::POINTS;
filament_marker.color.a = 1;
}
CFilamentSimulator::~CFilamentSimulator()
{
}
//==============================//
// GADEN_preprocessing CB //
//==============================//
void CFilamentSimulator::preprocessingCB(const std_msgs::Bool& b)
{
preprocessing_done = true;
}
//==========================//
// Load Params //
//==========================//
void CFilamentSimulator::loadNodeParameters()
{
ros::NodeHandle private_nh("~");
// Verbose
private_nh.param<bool>("verbose", verbose, false);
// Wait PreProcessing
private_nh.param<bool>("wait_preprocessing", wait_preprocessing, false);
// Simulation Time (sec)
private_nh.param<double>("sim_time", max_sim_time, 20.0);
// Time increment between Gas snapshots (sec)
private_nh.param<double>("time_step", time_step, 1.0);
// Number of iterations to carry on = max_sim_time/time_step
numSteps = floor(max_sim_time/time_step);
// Num of filaments/sec
private_nh.param<int>("num_filaments_sec", numFilaments_sec, 100);
private_nh.param<bool>("variable_rate", variable_rate, false);
numFilaments_step = numFilaments_sec * time_step;
numFilament_aux=0;
total_number_filaments = numFilaments_step * numSteps;
current_number_filaments = 0;
private_nh.param<int>("filament_stop_steps", filament_stop_steps, 0);
filament_stop_counter= 0;
// Gas concentration at the filament center - 3D gaussian [ppm]
private_nh.param<double>("ppm_filament_center", filament_ppm_center, 20);
// [cm] Sigma of the filament at t=0-> 3DGaussian shape
private_nh.param<double>("filament_initial_std", filament_initial_std, 1.5);
// [cm²/s] Growth ratio of the filament_std
private_nh.param<double>("filament_growth_gamma", filament_growth_gamma, 10.0);
// [cm] Sigma of the white noise added on each iteration
private_nh.param<double>("filament_noise_std", filament_noise_std, 0.1);
// Gas Type ID
private_nh.param<int>("gas_type", gasType, 1);
// Environment temperature (necessary for molecules/cm3 -> ppm)
private_nh.param<double>("temperature", envTemperature, 298.0);
// Enviorment pressure (necessary for molecules/cm3 -> ppm)
private_nh.param<double>("pressure", envPressure, 1.0);
// Gas concentration units (0= molecules/cm3, 1=ppm)
private_nh.param<int>("concentration_unit_choice", gasConc_unit, 1);
//WIND DATA
//----------
//CFD wind files location
private_nh.param<std::string>("wind_data", wind_files_location, "");
//(sec) Time increment between Wind snapshots --> Determines when to load a new wind field
private_nh.param<double>("wind_time_step", windTime_step, 1.0);
// Loop
private_nh.param<bool>("allow_looping", allow_looping, false);
private_nh.param<int>("loop_from_step", loop_from_step, 1);
private_nh.param<int>("loop_to_step", loop_to_step, 100);
//ENVIRONMENT
//-----------
// Occupancy gridmap 3D location
private_nh.param<std::string>("occupancy3D_data", occupancy3D_data, "");
//fixed frame (to disaply the gas particles on RVIZ)
private_nh.param<std::string>("fixed_frame", fixed_frame, "/map");
//Source postion (x,y,z)
private_nh.param<double>("source_position_x", gas_source_pos_x, 1.0);
private_nh.param<double>("source_position_y", gas_source_pos_y, 1.0);
private_nh.param<double>("source_position_z", gas_source_pos_z, 1.0);
// Simulation results.
private_nh.param<int>("save_results", save_results, 1);
private_nh.param<std::string>("results_location", results_location, "");
if (save_results && !boost::filesystem::exists(results_location)){
if (!boost::filesystem::create_directories(results_location))
ROS_ERROR("[filament] Could not create result directory: %s", results_location.c_str());
}
//create a sub-folder for this specific simulation
results_location=boost::str(boost::format("%s/FilamentSimulation_gasType_%i_sourcePosition_%.2f_%.2f_%.2f") % results_location % gasType % gas_source_pos_x % gas_source_pos_y % gas_source_pos_z );
private_nh.param<double>("results_min_time", results_min_time, 0.0);
private_nh.param<double>("results_time_step", results_time_step, 1.0);
if (verbose)
{
ROS_INFO("[filament] The data provided in the roslaunch file is:");
ROS_INFO("[filament] Simulation Time %f(s)",sim_time);
ROS_INFO("[filament] Gas Time Step: %f(s)",time_step);
ROS_INFO("[filament] Num_steps: %d",numSteps);
ROS_INFO("[filament] Number of filaments: %d",numFilaments_sec);
ROS_INFO("[filament] PPM filament center %f",filament_ppm_center);
ROS_INFO("[filament] Gas type: %d",gasType);
ROS_INFO("[filament] Concentration unit: %d",gasConc_unit);
ROS_INFO("[filament] Wind_time_step: %f(s)", windTime_step);
ROS_INFO("[filament] Fixed frame: %s",fixed_frame.c_str());
ROS_INFO("[filament] Source position: (%f,%f,%f)",gas_source_pos_x, gas_source_pos_y, gas_source_pos_z);
if (save_results)
ROS_INFO("[filament] Saving results to %s",results_location.c_str());
}
}
//==========================//
// //
//==========================//
void CFilamentSimulator::initSimulator()
{
if (verbose) ROS_INFO("[filament] Initializing Simulator... Please Wait!");
//1. Load Environment and Configure Matrices
if (FILE *file = fopen(occupancy3D_data.c_str(), "r"))
{
//Files exist!, keep going!
fclose(file);
if (verbose) ROS_INFO("[filament] Loading 3D Occupancy GridMap");
read_3D_file(occupancy3D_data, Env, true, false);
}
else
{
ROS_ERROR("[filament] File %s Does Not Exists!",occupancy3D_data.c_str());
}
//2. Load the first Wind snapshot from file (all 3 components U,V,W)
read_wind_snapshot(current_simulation_step);
//3. Initialize the filaments vector to its max value (to avoid increasing the size at runtime)
if (verbose) ROS_INFO("[filament] Initializing Filaments");
filaments.resize(total_number_filaments, CFilament(0.0, 0.0, 0.0, filament_initial_std));
}
//Resize a 3D Matrix compose of Vectors, This operation is only performed once!
void CFilamentSimulator::configure3DMatrix(std::vector< double > &A)
{
A.resize(env_cells_x* env_cells_y * env_cells_z);
}
//==========================//
// //
//==========================//
void CFilamentSimulator::read_wind_snapshot(int idx)
{
if (last_wind_idx==idx)
return;
//configure filenames to read
std::string U_filename = boost::str( boost::format("%s%i.csv_U") % wind_files_location % idx );
std::string V_filename = boost::str( boost::format("%s%i.csv_V") % wind_files_location % idx );
std::string W_filename = boost::str( boost::format("%s%i.csv_W") % wind_files_location % idx );
if (verbose) ROS_INFO("Reading Wind Snapshot %s",U_filename.c_str());
//read data to 3D matrices
if (FILE *file = fopen(U_filename.c_str(), "r"))
{
//Files exist!, keep going!
fclose(file);
last_wind_idx=idx;
if (verbose) ROS_INFO("[filament] Loading Wind Snapshot %i", idx);
//binary format files start with the code "999"
std::ifstream ist(U_filename, std::ios_base::binary);
int check=0;
ist.read((char*) &check, sizeof(int));
ist.close();
read_3D_file(U_filename, U, false, (check==999));
read_3D_file(V_filename, V, false, (check==999));
read_3D_file(W_filename, W, false, (check==999));
if(!wind_finished){
//dump the binary wind data to file
std::string out_filename = boost::str( boost::format("%s/wind/wind_iteration_%i") % results_location % idx);
FILE * file = fopen(out_filename.c_str(), "wb");
if (file==NULL){
ROS_ERROR("CANNOT OPEN WIND LOG FILE\n");
exit(1);
}
fclose(file);
std::ofstream wind_File(out_filename.c_str());
wind_File.write((char*) U.data(), sizeof(double) * U.size());
wind_File.write((char*) V.data(), sizeof(double) * V.size());
wind_File.write((char*) W.data(), sizeof(double) * W.size());
wind_File.close();
}
}
else
{
//No more wind data. Keep current info.
if (!wind_notified)
{
ROS_WARN("[filament] File %s Does Not Exists!",U_filename.c_str());
ROS_WARN("[filament] No more wind data available. Using last Wind snapshopt as SteadyState.");
wind_notified = true;
wind_finished = true;
}
}
}
//==========================//
// //
//==========================//
void CFilamentSimulator::read_3D_file(std::string filename, std::vector< double > &A, bool hasHeader, bool binary)
{
if(binary){
std::ifstream infile(filename, std::ios_base::binary);
infile.seekg(sizeof(int));
infile.read((char*) A.data(), sizeof(double)* A.size());
infile.close();
return;
}
//open file
std::ifstream infile(filename.c_str());
std::string line;
int line_counter = 0;
//If header -> read 4 Header lines & configure all matrices to given dimensions!
if (hasHeader)
{
//Line 1 (min values of environment)
std::getline(infile, line);
line_counter++;
size_t pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_min_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_min_y = atof(line.substr(0, pos).c_str());
env_min_z = atof(line.substr(pos+1).c_str());
//Line 2 (max values of environment)
std::getline(infile, line);
line_counter++;
pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_max_x = atof(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_max_y = atof(line.substr(0, pos).c_str());
env_max_z = atof(line.substr(pos+1).c_str());
//Line 3 (Num cells on eahc dimension)
std::getline(infile, line);
line_counter++;
pos = line.find(" ");
line.erase(0, pos+1);
pos = line.find(" ");
env_cells_x = atoi(line.substr(0, pos).c_str());
line.erase(0, pos+1);
pos = line.find(" ");
env_cells_y = atof(line.substr(0, pos).c_str());
env_cells_z = atof(line.substr(pos+1).c_str());
//Line 4 cell_size (m)
std::getline(infile, line);
line_counter++;
pos = line.find(" ");
cell_size = atof(line.substr(pos+1).c_str());
if (verbose) ROS_INFO("[filament] Env dimensions (%.2f,%.2f,%.2f) to (%.2f,%.2f,%.2f)",env_min_x, env_min_y, env_min_z, env_max_x, env_max_y, env_max_z );
if (verbose) ROS_INFO("[filament] Env size in cells (%d,%d,%d) - with cell size %f [m]",env_cells_x,env_cells_y,env_cells_z, cell_size);
//Reserve memory for the 3D matrices: U,V,W,C and Env, according to provided num_cells of the environment.
//It also init them to 0.0 values
configure3DMatrix(U);
configure3DMatrix(V);
configure3DMatrix(W);
configure3DMatrix(C);
configure3DMatrix(Env);
}
//Read file line by line
int x_idx = 0;
int y_idx = 0;
int z_idx = 0;
while ( std::getline(infile, line) )
{
line_counter++;
std::stringstream ss(line);
if (z_idx >=env_cells_z)
{
ROS_ERROR("Trying to read:[%s]",line.c_str());
}
if (line == ";")
{
//New Z-layer
z_idx++;
x_idx = 0;
y_idx = 0;
}
else
{ //New line with constant x_idx and all the y_idx values
while (!ss.fail())
{
double f;
ss >> f; //get one double value
if (!ss.fail())
{
A[indexFrom3D(x_idx,y_idx,z_idx)] = f;
y_idx++;
}
}
//Line has ended
x_idx++;
y_idx = 0;
}
}
//End of file.
if (verbose)
ROS_INFO("End of File");
infile.close();
}
// Add new filaments. On each step add a total of "numFilaments_step"
void CFilamentSimulator::add_new_filaments(double radius_arround_source)
{
numFilament_aux+=numFilaments_step;
// Release rate
int filaments_to_release=floor(numFilament_aux);
if (variable_rate)
{
filaments_to_release = (int) round( random_number(0.0, filaments_to_release) );
}
else
{
if(filament_stop_counter==filament_stop_steps){
filament_stop_counter=0;
}else{
filament_stop_counter++;
filaments_to_release=0;
}
}
for (int i=0; i<filaments_to_release; i++)
{
double x, y, z;
do{
//Set position of new filament within the especified radius arround the gas source location
x = gas_source_pos_x + random_number(-1,1)*radius_arround_source;
y = gas_source_pos_y + random_number(-1,1)*radius_arround_source;
z = gas_source_pos_z + random_number(-1,1)*radius_arround_source;
}while(check_pose_with_environment(x,y,z)!=0);
/*Instead of adding new filaments to the filaments vector on each iteration (push_back)
we had initially resized the filaments vector to the max number of filaments (numSteps*numFilaments_step)
Here we will "activate" just the corresponding filaments for this step.*/
filaments[current_number_filaments+i].activate_filament(x, y, z, sim_time);
}
}
// Here we estimate the gas concentration on each cell of the 3D env
// based on the active filaments and their 3DGaussian shapes
// For that we employ Farrell's Concentration Eq
void CFilamentSimulator::update_gas_concentration_from_filament(int fil_i)
{
// We run over all the active filaments, and update the gas concentration of the cells that are close to them.
// Ideally a filament spreads over the entire environment, but in practice since filaments are modeled as 3Dgaussians
// We can stablish a cutt_off raduis of 3*sigma.
// To avoid resolution problems, we evaluate each filament according to the minimum between:
// the env_cell_size and filament_sigma. This way we ensure a filament is always well evaluated (not only one point).
double grid_size_m = std::min(cell_size, (filaments[fil_i].sigma/100)); //[m] grid size to evaluate the filament
// Compute at which increments the Filament has to be evaluated.
// If the sigma of the Filament is very big (i.e. the Filament is very flat), the use the world's cell_size.
// If the Filament is very small (i.e in only spans one or few world cells), then use increments equal to sigma
// in order to have several evaluations fall in the same cell.
int num_evaluations = ceil(6*(filaments[fil_i].sigma/100) / grid_size_m);
// How many times the Filament has to be evaluated depends on the final grid_size_m.
// The filament's grid size is multiplied by 6 because we evaluate it over +-3 sigma
// If the filament is very small (i.e. grid_size_m = sigma), then the filament is evaluated only 6 times
// If the filament is very big and spans several cells, then it has to be evaluated for each cell (which will be more than 6)
// EVALUATE IN ALL THREE AXIS
for (int i=0; i<=num_evaluations; i++)
{
for (int j=0; j<=num_evaluations; j++)
{
for (int k=0; k<=num_evaluations; k++)
{
//get point to evaluate [m]
double x = (filaments[fil_i].pose_x - 3*(filaments[fil_i].sigma/100)) + i*grid_size_m;
double y = (filaments[fil_i].pose_y - 3*(filaments[fil_i].sigma/100)) + j*grid_size_m;
double z = (filaments[fil_i].pose_z - 3*(filaments[fil_i].sigma/100)) + k*grid_size_m;
// Disntance from evaluated_point to filament_center (in [cm])
double distance_cm = 100 * sqrt( pow(x-filaments[fil_i].pose_x,2) + pow(y-filaments[fil_i].pose_y,2) + pow(z-filaments[fil_i].pose_z,2) );
// FARRELLS Eq.
//Evaluate the concentration of filament fil_i at given point (moles/cm³)
double num_moles_cm3 = (filament_numMoles_of_gas / (sqrt(8*pow(3.14159,3)) * pow(filaments[fil_i].sigma,3) )) * exp( -pow(distance_cm,2)/(2*pow(filaments[fil_i].sigma,2)) );
//Multiply for the volumen of the grid cell
double num_moles = num_moles_cm3 * pow(grid_size_m*100,3); //[moles]
//Valid point? If either OUT of the environment, or through a wall, treat it as invalid
bool path_is_obstructed = check_environment_for_obstacle(filaments[fil_i].pose_x, filaments[fil_i].pose_y, filaments[fil_i].pose_z, x,y,z );
if (!path_is_obstructed)
{
//Get 3D cell of the evaluated point
int x_idx = floor( (x-env_min_x)/cell_size );
int y_idx = floor( (y-env_min_y)/cell_size );
int z_idx = floor( (z-env_min_z)/cell_size );
//Accumulate concentration in corresponding env_cell
if (gasConc_unit==0)
{
mtx.lock();
C[indexFrom3D(x_idx,y_idx,z_idx)] += num_moles; //moles
mtx.unlock();
}
else
{
mtx.lock();
double num_ppm = (num_moles/env_cell_numMoles)*pow(10,6); //[ppm]
C[indexFrom3D(x_idx,y_idx,z_idx)] += num_ppm; //ppm
mtx.unlock();
}
}
}
}
}
//Update Gasconcentration markers
}
//==========================//
// //
//==========================//
void CFilamentSimulator::update_gas_concentration_from_filaments(){
//First, set all cells to 0.0 gas concentration (clear previous state)
#pragma omp parallel for collapse(3)
for (size_t i=0; i<env_cells_x; i++)
{
for (size_t j=0; j<env_cells_y; j++)
{
for (size_t k=0; k<env_cells_z; k++)
{
C[indexFrom3D(i,j,k)] = 0.0;
}
}
}
#pragma omp parallel for
for (int i = 0; i < current_number_filaments; i++)
{
if (filaments[i].valid)
{
update_gas_concentration_from_filament(i);
}
}
}
//Check if a given 3D pose falls in:
// 0 = free space
// 1 = obstacle, wall, or outside the environment
// 2 = outlet (usefull to disable filaments)
int CFilamentSimulator::check_pose_with_environment(double pose_x, double pose_y, double pose_z)
{
//1.1 Check that pose is within the boundingbox environment
if (pose_x<env_min_x || pose_x>env_max_x || pose_y<env_min_y || pose_y>env_max_y || pose_z<env_min_z || pose_z>env_max_z)
return 1;
//Get 3D cell of the point
int x_idx = (pose_x-env_min_x)/cell_size;
int y_idx = (pose_y-env_min_y)/cell_size;
int z_idx = (pose_z-env_min_z)/cell_size;
if (x_idx >= env_cells_x || y_idx >= env_cells_y || z_idx >= env_cells_z)
return 1;
//1.2. Return cell occupancy (0=free, 1=obstacle, 2=outlet)
return Env[indexFrom3D(x_idx,y_idx,z_idx)];
}
//==========================//
// //
//==========================//
bool CFilamentSimulator::check_environment_for_obstacle(double start_x, double start_y, double start_z,
double end_x, double end_y, double end_z)
{
const bool PATH_OBSTRUCTED = true;
const bool PATH_UNOBSTRUCTED = false;
// Check whether one of the points is outside the valid environment or is not free
if(check_pose_with_environment(start_x, start_y, start_z) != 0) { return PATH_OBSTRUCTED; }
if(check_pose_with_environment( end_x, end_y , end_z) != 0) { return PATH_OBSTRUCTED; }
// Calculate normal displacement vector
double vector_x = end_x - start_x;
double vector_y = end_y - start_y;
double vector_z = end_z - start_z;
double distance = sqrt(vector_x*vector_x + vector_y*vector_y + vector_z*vector_z);
vector_x = vector_x/distance;
vector_y = vector_y/distance;
vector_z = vector_z/distance;
// Traverse path
int steps = ceil( distance / cell_size ); // Make sure no two iteration steps are separated more than 1 cell
double increment = distance/steps;
for(int i=1; i<steps-1; i++)
{
// Determine point in space to evaluate
double pose_x = start_x + vector_x*increment*i;
double pose_y = start_y + vector_y*increment*i;
double pose_z = start_z + vector_z*increment*i;
// Determine cell to evaluate (some cells might get evaluated twice due to the current code
int x_idx = floor( (pose_x-env_min_x)/cell_size );
int y_idx = floor( (pose_y-env_min_y)/cell_size );
int z_idx = floor( (pose_z-env_min_z)/cell_size );
// Check if the cell is occupied
if(Env[indexFrom3D(x_idx,y_idx,z_idx)] != 0) { return PATH_OBSTRUCTED; }
}
// Direct line of sight confirmed!
return PATH_UNOBSTRUCTED;
}
//Update the filaments location in the 3D environment
// According to Farrell Filament model, a filament is afected by three components of the wind flow.
// 1. Va (large scale wind) -> Advection (Va) -> Movement of a filament as a whole by wind) -> from CFD
// 2. Vm (middle scale wind)-> Movement of the filament with respect the center of the "plume" -> modeled as white noise
// 3. Vd (small scale wind) -> Difussion or change of the filament shape (growth with time)
// We also consider Gravity and Bouyant Forces given the gas molecular mass
void CFilamentSimulator::update_filament_location(int i)
{
//Estimte filament acceleration due to gravity & Bouyant force (for the given gas_type):
double g = 9.8;
double specific_gravity_air = 1; //[dimensionless]
double accel = g * ( specific_gravity_air - SpecificGravity[gasType] ) / SpecificGravity[gasType];
double newpos_x, newpos_y, newpos_z;
//Update the location of all active filaments
//ROS_INFO("[filament] Updating %i filaments of %lu",current_number_filaments, filaments.size());
try
{
//Get 3D cell of the filament center
int x_idx = floor( (filaments[i].pose_x-env_min_x)/cell_size );
int y_idx = floor( (filaments[i].pose_y-env_min_y)/cell_size );
int z_idx = floor( (filaments[i].pose_z-env_min_z)/cell_size );
//1. Simulate Advection (Va)
// Large scale wind-eddies -> Movement of a filament as a whole by wind
//------------------------------------------------------------------------
newpos_x = filaments[i].pose_x + U[indexFrom3D(x_idx,y_idx,z_idx)] * time_step;
newpos_y = filaments[i].pose_y + V[indexFrom3D(x_idx,y_idx,z_idx)] * time_step;
newpos_z = filaments[i].pose_z + W[indexFrom3D(x_idx,y_idx,z_idx)] * time_step;
//Check filament location
int valid_location = check_pose_with_environment(newpos_x, newpos_y, newpos_z);
switch (valid_location)
{
case 0:
//Free and valid location... update filament position
filaments[i].pose_x = newpos_x;
filaments[i].pose_y = newpos_y;
filaments[i].pose_z = newpos_z;
break;
case 2:
//The location corresponds to an outlet! Delete filament!
filaments[i].valid = false;
break;
default:
//The location falls in an obstacle -> Illegal movement (Do not apply advection)
break;
}
//2. Simulate Gravity & Bouyant Force
//------------------------------------
//OLD approach: using accelerations (pure gas)
//newpos_z = filaments[i].pose_z + 0.5*accel*pow(time_step,2);
//Approximation from "Terminal Velocity of a Bubble Rise in a Liquid Column", World Academy of Science, Engineering and Technology 28 2007
double ro_air = 1.205; //[kg/m³] density of air
double mu = 19*pow(10,-6); //[kg/s·m] dynamic viscosity of air
double terminal_buoyancy_velocity = (g * (1-SpecificGravity[gasType])*ro_air * filament_ppm_center*pow(10,-6) ) / (18* mu);
//newpos_z = filaments[i].pose_z + terminal_buoyancy_velocity*time_step;
//Check filament location
if (check_pose_with_environment(filaments[i].pose_x, filaments[i].pose_y, newpos_z ) == 0){
filaments[i].pose_z = newpos_z;
}else if(check_pose_with_environment(filaments[i].pose_x, filaments[i].pose_y, newpos_z ) == 2){
filaments[i].valid = false;
}
//3. Add some variability (stochastic process)
static thread_local std::mt19937 engine;
static thread_local std::normal_distribution<> dist{0, filament_noise_std};
newpos_x = filaments[i].pose_x + dist(engine);
newpos_y = filaments[i].pose_y + dist(engine);
newpos_z = filaments[i].pose_z + dist(engine);
//Check filament location
if (check_pose_with_environment(newpos_x, newpos_y, newpos_z ) == 0)
{
filaments[i].pose_x = newpos_x;
filaments[i].pose_y = newpos_y;
filaments[i].pose_z = newpos_z;
}
//4. Filament growth with time (this affects the posterior estimation of gas concentration at each cell)
// Vd (small scale wind eddies) -> Difussion or change of the filament shape (growth with time)
// R = sigma of a 3D gaussian -> Increasing sigma with time
//------------------------------------------------------------------------
filaments[i].sigma = sqrt(pow(filament_initial_std,2) + filament_growth_gamma*(sim_time-filaments[i].birth_time));
}catch(...)
{
ROS_ERROR("Exception Updating Filaments!");
return;
}
}
//==========================//
// //
//==========================//
void CFilamentSimulator::update_filaments_location()
{
#pragma omp parallel for
for (int i = 0; i < current_number_filaments; i++)
{
if (filaments[i].valid)
{
update_filament_location(i);
}
}
current_number_filaments+=floor(numFilament_aux);
numFilament_aux-=floor(numFilament_aux);
}
//==========================//
// //
//==========================//
void CFilamentSimulator::publish_markers()
{
//1. Clean old markers
filament_marker.points.clear();
filament_marker.colors.clear();
filament_marker.header.stamp = ros::Time::now();
filament_marker.pose.orientation.w = 1.0;
//width of points: scale.x is point width, scale.y is point height
filament_marker.scale.x = cell_size/4;
filament_marker.scale.y = cell_size/4;
filament_marker.scale.z = cell_size/4;
//2. Add a marker for each filament!
for (int i=0; i<current_number_filaments; i++)
{
geometry_msgs::Point point;
std_msgs::ColorRGBA color;
//Set filament pose
point.x = filaments[i].pose_x;
point.y = filaments[i].pose_y;
point.z = filaments[i].pose_z;
//Set filament color
color.a = 1;
if (filaments[i].valid)
{
color.r = 0;
color.g = 0;
color.b = 1;
}
else
{
color.r = 1;
color.g = 0;
color.b = 0;
}
//Add marker
filament_marker.points.push_back(point);
filament_marker.colors.push_back(color);
}
//Publish marker of the filaments
marker_pub.publish(filament_marker);
}
//==========================//
// //
//==========================//
double CFilamentSimulator::random_number(double min_val, double max_val)
{
double n = (double)(rand() % 100); //int random number [0, 100)
n = n/100.0f; //random number [0, 1)
n = n * (max_val - min_val); //random number [0, max-min)
n = n+ min_val; //random number [min, max)
return n;
}
bool eq (double a, double b){
return abs(a-b)<0.001;
}
//Saves current Wind + GasConcentration to file
// These files will be later used in the "player" node.
void CFilamentSimulator::save_state_to_file()
{
last_saved_step++;
//Configure file name for saving the current snapshot
std::string out_filename = boost::str( boost::format("%s/iteration_%i") % results_location % last_saved_step);
FILE * file = fopen(out_filename.c_str(), "wb");
if (file==NULL){
ROS_ERROR("CANNOT OPEN LOG FILE\n");
exit(1);
}
fclose(file);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
std::stringstream ist;
inbuf.push(boost::iostreams::zlib_compressor());
inbuf.push(ist);
int h = 1;
ist.write((char*) &h, sizeof(int));
ist.write((char*) &env_min_x, sizeof(double));
ist.write((char*) &env_min_y, sizeof(double));
ist.write((char*) &env_min_z, sizeof(double));
ist.write((char*) &env_max_x, sizeof(double));
ist.write((char*) &env_max_y, sizeof(double));
ist.write((char*) &env_max_z, sizeof(double));
ist.write((char*) &env_cells_x, sizeof(int));
ist.write((char*) &env_cells_y, sizeof(int));
ist.write((char*) &env_cells_z, sizeof(int));
ist.write((char*) &cell_size, sizeof(double));
ist.write((char*) &cell_size, sizeof(double));
ist.write((char*) &cell_size, sizeof(double));
ist.write((char*) &gas_source_pos_x, sizeof(double));
ist.write((char*) &gas_source_pos_y, sizeof(double));
ist.write((char*) &gas_source_pos_z, sizeof(double));
ist.write((char*)&gasType, sizeof(int));
//constants to work out the gas concentration form the filament location
ist.write((char*) &filament_numMoles_of_gas, sizeof(double));
double num_moles_all_gases_in_cm3=env_cell_numMoles/env_cell_vol;
ist.write((char*) &num_moles_all_gases_in_cm3, sizeof(double));
ist.write((char*) &last_wind_idx, sizeof(int)); //index of the wind file (they are stored separately under (results_location)/wind/... )
for(int i=0;i<filaments.size();i++){
if(filaments[i].valid){
ist.write((char*) &i, sizeof(int));
ist.write((char*) &filaments[i].pose_x, sizeof(double));
ist.write((char*) &filaments[i].pose_y, sizeof(double));
ist.write((char*) &filaments[i].pose_z, sizeof(double));
ist.write((char*) &filaments[i].sigma, sizeof(double));
}
}
std::ofstream fi(out_filename);
boost::iostreams::copy(inbuf,fi);
fi.close();
}
int CFilamentSimulator::indexFrom3D(int x, int y, int z){
return x + y*env_cells_x + z*env_cells_x*env_cells_y;
}
//==============================//
// MAIN //
//==============================//
int main(int argc, char **argv)
{
// Init ROS-NODE
ros::init(argc, argv, "new_filament_simulator");
//Create simulator obj and initialize it
CFilamentSimulator sim;
// Initiate Random Number generator with current time
srand(time(NULL));
//--------------
// LOOP
//--------------
while (ros::ok() && (sim.current_simulation_step<sim.numSteps) )
{
//ROS_INFO("[filament] Simulating step %i (sim_time = %.2f)", sim.current_simulation_step, sim.sim_time);
//0. Load wind snapshot (if necessary and availabe)
if ( sim.sim_time-sim.sim_time_last_wind >= sim.windTime_step)
{
// Time to update wind!
sim.sim_time_last_wind = sim.sim_time;
if (sim.allow_looping)
{
// Load wind-data
sim.read_wind_snapshot(sim.current_wind_snapshot);
// Update idx
if (sim.current_wind_snapshot >= sim.loop_to_step){
sim.current_wind_snapshot = sim.loop_from_step;
sim.wind_finished = true;
}
else
sim.current_wind_snapshot++;
}
else
sim.read_wind_snapshot(floor(sim.sim_time/sim.windTime_step)); //Alllways increasing
}
//1. Create new filaments close to the source location
// On each iteration num_filaments (See params) are created
sim.add_new_filaments(sim.cell_size);
//2. Publish markers for RVIZ
sim.publish_markers();
//3. Update filament locations
sim.update_filaments_location();
//4. Save data (if necessary)
if ( (sim.save_results==1) && (sim.sim_time>=sim.results_min_time) )
{
if ( floor(sim.sim_time/sim.results_time_step) != sim.last_saved_step ){
sim.save_state_to_file();
}
}
//5. Update Simulation state
sim.sim_time = sim.sim_time + sim.time_step; //sec
sim.current_simulation_step++;
ros::spinOnce();
}
}
| 37,202 | C++ | 34.910232 | 197 | 0.625988 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_filament_simulator/src/filament.cpp | /*---------------------------------------------------------------------------------------
* Very simple implementation of the class Filament
* A gas source releases patches/puffs of gas. Each pach or puff is composed of N filaments.
* A filament is a 3D shape which contains Q molecules of gas.
* The filament is affected by advection (i.e its center moves with the wind field)
* But also for difussion (its width increases with time), and some estochastic process (random behaviour)
* This three effects can be related to the size of the wind turbulent eddies
* See: Filament-Based Atmospheric DispersionModel to Achieve Short Time-Scale Structure of Odor Plumes, Farrell et al, 2002
---------------------------------------------------------------------------------------*/
#include "filament_simulator/filament.h"
//Default Constructor
CFilament::CFilament()
{
//Create a new filament!
pose_x = 0.0; //[m] Filament center pose
pose_y = 0.0; //[m] Filament center pose
pose_z = 0.0; //[m] Filament center pose
sigma = 0.01; //[cm] The sigma of a 3D gaussian (controlls the shape of the filament)
birth_time = 0.0;
valid = false;
}
//Overload Constructor
CFilament::CFilament(double x, double y, double z, double sigma_filament)
{
//Create a new filament!
pose_x = x; //[m] Filament center pose
pose_y = y; //[m] Filament center pose
pose_z = z; //[m] Filament center pose
sigma = sigma_filament; //[cm] The sigma of a 3D gaussian (controlls the shape of the filament)
birth_time = 0.0;
valid = false;
}
CFilament::~CFilament()
{
}
void CFilament::activate_filament(double x, double y, double z, double birth)
{
//Active the filament at given location
pose_x = x;
pose_y = y;
pose_z = z;
birth_time = birth;
valid = true;
}
void CFilament::deactivate_filament()
{
//de-Active the filament
valid = false;
}
| 2,018 | C++ | 33.810344 | 124 | 0.590188 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_filament_simulator/include/filament_simulator/filament_simulator.h | #ifndef CFilamentSimulator_H
#define CFilamentSimulator_H
#include <omp.h>
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <visualization_msgs/Marker.h>
#include "filament_simulator/filament.h"
#include <stdlib.h> /* srand, rand */
#include <iostream>
#include <fstream>
#include <random>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
class CFilamentSimulator
{
public:
CFilamentSimulator();
~CFilamentSimulator();
void add_new_filaments(double radius_arround_source);
void read_wind_snapshot(int idx);
void update_gas_concentration_from_filaments();
void update_gas_concentration_from_filament(int fil_i);
void update_filaments_location();
void update_filament_location(int i);
void publish_markers();
void save_state_to_file();
//Variables
int current_wind_snapshot;
int current_simulation_step;
double sim_time;
int last_saved_step;
//Parameters
bool verbose;
bool wait_preprocessing;
bool preprocessing_done;
double max_sim_time; //(sec) Time tu run this simulation
int numSteps; //Number of gas iterations to simulate
double time_step; //(sec) Time increment between gas snapshots --> Simul_time = snapshots*time_step
int numFilaments_sec; //Num of filaments released per second
bool variable_rate; //If true the number of released filaments would be random(0,numFilaments_sec)
int filament_stop_steps; //Number of steps to wait between the release of filaments (to force a patchy plume)
int filament_stop_counter;
double numFilaments_step; //Num of filaments released per time_step
double numFilament_aux;
int current_number_filaments;
int total_number_filaments; //total number of filaments to use along the simulation (for efficiency -> avoids push_back)
double filament_ppm_center; //[ppm] Gas concentration at the center of the 3D gaussian (filament)
double filament_initial_std; //[cm] Sigma of the filament at t=0-> 3DGaussian shape
double filament_growth_gamma; //[cm²/s] Growth ratio of the filament_std
double filament_noise_std; //STD to add some "variablity" to the filament location
int gasType; //Gas type to simulate
double envTemperature; //Temp in Kelvins
double envPressure; //Pressure in Atm
int gasConc_unit; //Get gas concentration in [molecules/cm3] or [ppm]
//Wind
std::string wind_files_location; //Location of the wind information
double windTime_step; //(sec) Time increment between wind snapshots
double sim_time_last_wind; //(sec) Simulation Time of the last updated of wind data
bool allow_looping;
int loop_from_step;
int loop_to_step;
//Enviroment
std::string occupancy3D_data; //Location of the 3D Occupancy GridMap of the environment
std::string fixed_frame; //Frame where to publish the markers
int env_cells_x; //cells
int env_cells_y; //cells
int env_cells_z; //cells
double env_min_x; //[m]
double env_max_x; //[m]
double env_min_y; //[m]
double env_max_y; //[m]
double env_min_z; //[m]
double env_max_z; //[m]
double cell_size; //[m]
//Gas Source Location (for releasing the filaments)
double gas_source_pos_x; //[m]
double gas_source_pos_y; //[m]
double gas_source_pos_z; //[m]
//Results
int save_results; //True or false
std::string results_location; //Location for results logfiles
double results_time_step; //(sec) Time increment between saving results
double results_min_time; //(sec) time after which start saving results
bool wind_finished;
boost::mutex mtx;
protected:
void loadNodeParameters();
void initSimulator();
void configure3DMatrix(std::vector< double > &A);
void read_3D_file(std::string filename, std::vector< double > &A, bool hasHeader, bool binary);
int check_pose_with_environment(double pose_x, double pose_y, double pose_z);
bool check_environment_for_obstacle(double start_x, double start_y, double start_z, double end_x, double end_y, double end_z);
double random_number(double min_val, double max_val);
void preprocessingCB(const std_msgs::Bool& b);
//Subscriptions & Publishers
ros::Publisher marker_pub; //For visualization of the filaments!
ros::Subscriber prepro_sub; // In case we require the preprocessing node to finish.
//Vars
ros::NodeHandle n;
std::vector< double > U, V, W, C, Env;
std::vector<CFilament> filaments;
visualization_msgs::Marker filament_marker;
bool wind_notified;
int last_wind_idx=-1;
// SpecificGravity [dimensionless] with respect AIR
double SpecificGravity[14] = {
// Molecular gas mass [g/mol]
// SpecificGravity(Air) = 1 (as reference)
// Specific gravity is the ratio of the density of a substance to the density of a reference substance; equivalently,
// it is the ratio of the mass of a substance to the mass of a reference substance for the same given volume.
1.0378, //ethanol (heavier than air)
0.5537, //methane (lighter than air)
0.0696, //hydrogen (lighter than air)
1.4529, //acetone (heavier than air)
//To be updated
1.23, //propanol //gases heavier then air
2.48, //chlorine
1.31, //fluorine
0.7, //neon //gases lighter than air
0.138, //helium
0.8, //sewage, biogas
2.0061, //butane
0.967, //carbon monoxide
1.52, //carbon dioxide
0.89 //smoke
};
//Fluid Dynamics
double filament_initial_vol;
double env_cell_vol;
double filament_numMoles; //Number of moles in a filament (of any gas or air)
double filament_numMoles_of_gas; //Number of moles of target gas in a filament
double env_cell_numMoles; //Number of moles in a cell (3D volume)
int indexFrom3D(int x, int y, int z);
};
#endif
| 6,800 | C | 40.218182 | 132 | 0.625735 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_filament_simulator/include/filament_simulator/filament.h | #ifndef FILAMENT_H
#define FILAMENT_H
class CFilament
{
public:
CFilament();
CFilament(double x, double y, double z, double sigma_filament);
~CFilament();
void activate_filament(double x, double y, double z, double birth);
void deactivate_filament();
//Parameters of the filament
//--------------------------
double pose_x; // Center of the filament (m)
double pose_y; // Center of the filament (m)
double pose_z; // Center of the filament (m)
double sigma; // [cm] The sigma of a 3D gaussian (controlls the shape of the filament)
bool valid; // Is filament valid?
double birth_time; // Time at which the filament is released (set as active)
};
#endif
| 769 | C | 31.083332 | 100 | 0.595579 |
tudelft/autoGDMplus/gaden_ws/src/gaden/utils/paraview.py | from paraview.simple import *
import sys
import os
path = sys.argv[1]
# create a new 'OpenFOAMReader'
foamReader = OpenFOAMReader(FileName=path)
# Properties modified on foamReader
if sys.argc==4 and sys.argv[3]=="-d":
foamReader.CaseType = 'Decomposed Case'
foamReader.UpdatePipeline()
foamReader.UpdatePipelineInformation()
# Properties modified on foamReader
foamReader.MeshRegions = ['internalMesh']
foamReader.CellArrays = ['U']
foamReader.UpdatePipeline()
# create a new 'Cell Centers'
cellCenters1 = CellCenters(Input=foamReader)
# Properties modified on cellCenters1
cellCenters1.VertexCells = 1
cellCenters1.UpdatePipeline()
# save data
directory=sys.argv[2]
if not os.path.exists(directory):
os.makedirs(directory)
SaveData(directory+"/"+sys.argv[2]+".csv", proxy=cellCenters1, WriteAllTimeSteps=1)
| 827 | Python | 21.999999 | 83 | 0.771463 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor/package.xml | <package>
<name>simulated_gas_sensor</name>
<version>1.0.0</version>
<description>Pkg for the simulation of the response of a gas sensor (MOX, EQ, PID, etc) to different gases.</description>
<maintainer email="[email protected]">Javier Monroy</maintainer>
<license>GPLv3</license>
<!-- Dependencies which this package needs to build itself. -->
<buildtool_depend>catkin</buildtool_depend>
<!-- Dependencies needed to compile this package. -->
<build_depend>roscpp</build_depend>
<build_depend>visualization_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<build_depend>olfaction_msgs</build_depend>
<build_depend>tf</build_depend>
<build_depend>gaden_player</build_depend>
<!-- Dependencies needed after this package is compiled. -->
<run_depend>roscpp</run_depend>
<run_depend>visualization_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>tf</run_depend>
<run_depend>nav_msgs</run_depend>
<run_depend>olfaction_msgs</run_depend>
<run_depend>gaden_player</run_depend>
</package>
| 1,091 | XML | 35.399999 | 123 | 0.72319 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor/src/fake_gas_sensor.h | #include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <visualization_msgs/Marker.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_listener.h>
#include <olfaction_msgs/gas_sensor.h>
#include <gaden_player/GasPosition.h>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <fstream>
#include <iostream>
//Gas Types
#define ETHANOL_ID 0
#define METHANE_ID 1
#define HYDROGEN_ID 2
#define PROPANOL_ID 3
#define CHLORIDE_ID 4
#define FLURORINE_ID 5
#define ACETONE_ID 6
#define NEON_ID 7
#define HELIUM_ID 8
#define HOTAIR_ID 9
//Sensor Types
#define TGS2620_ID 0
#define TGS2600_ID 1
#define TGS2611_ID 2
#define TGS2610_ID 3
#define TGS2612_ID 4
//Default Values
#define NODE_NAME "fake_mox"
#define DEFAULT_GAS_TYPE METHANE_ID
#define DEFAULT_SENSOR_NAME "mox_sensor"
#define DEFAULT_SENSOR_MODEL TGS2620_ID
#define DEFAULT_SENSOR_FRAME "mox_frame"
#define DEFAULT_FIXED_FRAME "map"
// Sensor Parameters
int input_sensor_model;
std::string input_sensor_frame;
std::string input_fixed_frame;
bool use_PID_correction_factors;
//MOX model params
bool first_reading; //First reading is set to baseline always
float RS_R0; //Ideal sensor response based on sensitivity
float sensor_output; //MOX model response
float previous_sensor_output; //The response in (t-1)
float node_rate; //(Hz) Execution freq. Useful for the MOX model
bool notified; //to notifiy about erros just once
// Vars
int ch_id; //Chemical ID
//functions:
void loadNodeParameters(ros::NodeHandle private_nh);
float simulate_mox_as_line_loglog(gaden_player::GasPositionResponse GT_gas_concentrations);
float simulate_pid(gaden_player::GasPositionResponse GT_gas_concentrations);
//------------------------ SENSOR CHARACTERIZATION PARAMS ----------------------------------//
std::string labels[5] = {"TGS2620", "TGS2600", "TGS2611", "TGS2610", "TGS2612"};
float R0[5] = {3000, 50000, 3740, 3740, 4500}; //[Ohms] Reference resistance (see datasheets)
//Time constants (Rise, Decay)
float tau_value[5][7][2] = //5 sensors, 7 gases , 2 Time Constants
{
{ //TGS2620
{2.96, 15.71}, //ethanol
{2.96, 15.71}, //methane
{2.96, 15.71}, //hydrogen
{2.96, 15.71}, //propanol
{2.96, 15.71}, //chlorine
{2.96, 15.71}, //fluorine
{2.96, 15.71} //Acetone
},
{ //TGS2600
{4.8, 18.75}, //ethanol
{4.8, 18.75}, //methane
{4.8, 18.75}, //hydrogen
{4.8, 18.75}, //propanol
{4.8, 18.75}, //chlorine
{4.8, 18.75}, //fluorine
{4.8, 18.75} //Acetone
},
{ //TGS2611
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
},
{ //TGS2610
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
},
{ //TGS2612
{3.44, 6.35}, //ethanol
{3.44, 6.35}, //methane
{3.44, 6.35}, //hydrogen
{3.44, 6.35}, //propanol
{3.44, 6.35}, //chlorine
{3.44, 6.35}, //fluorine
{3.44, 6.35} //Acetone
}
};
// MOX sensitivity. Extracted from datasheets and curve fitting
//--------------------------------------------------------------
float Sensitivity_Air[5] = {21, 1, 8.8, 10.3, 19.5}; //RS/R0 when exposed to clean air (datasheet)
// RS/R0 = A*conc^B (a line in the loglog scale)
float sensitivity_lineloglog[5][7][2]={ //5 Sensors, 7 Gases, 2 Constants: A, B
{ //TGS2620
{62.32, -0.7155}, //Ethanol
{120.6, -0.4877}, //Methane
{24.45, -0.5546}, //Hydrogen
{120.6, -0.4877}, //propanol (To review)
{120.6, -0.4877}, //chlorine (To review)
{120.6, -0.4877}, //fluorine (To review)
{120.6, -0.4877} //Acetone (To review)
},
{ //TGS2600
{0.6796, -0.3196}, //ethanol
{1.018, -0.07284}, //methane
{0.6821, -0.3532}, //hydrogen
{1.018, -0.07284}, //propanol (To review)
{1.018, -0.07284}, //chlorine (To review)
{1.018, -0.07284}, //fluorine (To review)
{1.018, -0.07284} //Acetone (To review)
},
{ //TGS2611
{51.11, -0.3658}, //ethanol
{38.46, -0.4289}, //methane
{41.3, -0.3614}, //hydrogen
{38.46, -0.4289}, //propanol (To review)
{38.46, -0.4289}, //chlorine (To review)
{38.46, -0.4289}, //fluorine (To review)
{38.46, -0.4289} //Acetone (To review)
},
{ //TGS2610
{106.1, -0.5008}, //ethanol
{63.91, -0.5372}, //methane
{66.78, -0.4888}, //hydrogen
{63.91, -0.5372}, //propanol (To review)
{63.91, -0.5372}, //chlorine (To review)
{63.91, -0.5372}, //fluorine (To review)
{63.91, -0.5372} //Acetone (To review)
},
{ //TGS2612
{31.35, -0.09115}, //ethanol
{146.2, -0.5916}, //methane
{19.5, 0.0}, //hydrogen
{146.2, -0.5916}, //propanol (To review)
{146.2, -0.5916}, //chlorine (To review)
{146.2, -0.5916}, //fluorine (To review)
{146.2, -0.5916} //Acetone (To review)
}
};
//PID correction factors for gas concentration
//--------------------------------------------
//Ethanol, Methane, Hydrogen, Propanol, Chlorine, Fluorine, Acetone
// http://www.intlsensor.com/pdf/pidcorrectionfactors.pdf
// Here we simulate a lamp of 11.7eV to increase the range of detectable gases
// A 0.0 means the PID is not responsive to that gas
float PID_correction_factors[7] = {10.47, 0.0, 0.0, 2.7, 1.0, 0.0, 1.4};
// OLD - DEPRECATED
// MOX sensitivity. Extracted from datasheets and curve fitting
// RS/R0 = A*e^(B*conc) + C*e^(D*conc)
float sensitivity_2exp[3][3][4]={ //3 Sensors, 3 Gases, 4 Constants: A, B, C, D
{ //TGS2620
{6.018,-0.01662, 0.9832,-0.0005651}, //ethanol
{18.79,-0.01062, 6.138, -0.0002136 }, //methane
{3.884 ,-0.0127,0.8745,-0.0003222 }, //hydrogen
},
{ //TGS2600
{0.4668,-0.3249, 0.3293, -0.01051 }, //ethanol
{0.2202, -0.1122, 0.8356, -0.001932}, //methane
{0.0,0.0,0.0,0.0}, //hydrogen
},
{ //TGS2611
{4.766,-0.001639, 3.497, -7.348e-05 }, //ethanol
{3.286 ,-0.002211, 1.806 -0.000103}, //methane
{4.535, -0.001723, 2.69, -5.191e-05}, //hydrogen
}
};
| 6,747 | C | 29.672727 | 103 | 0.551653 |
tudelft/autoGDMplus/gaden_ws/src/gaden/simulated_gas_sensor/src/fake_gas_sensor.cpp | /*-------------------------------------------------------------------------------
* This node simulates the response of a MOX gas sensor given the GT gas concentration
* of the gases it is exposed to (request to simulation_player or dispersion_simulation)
* - Gas concentration should be given in [ppm]
* - The Pkg response can be set to: Resistance of the sensor (Rs), Resistance-ratio (Rs/R0), or Voltage (0-5V)
* - Sensitivity to different gases is set based on manufacter datasheet
* - Time constants for the dynamic response are set based on real experiments
*
* - Response to mixture of gases is set based on datasheet.
* -----------------------------------------------------------------------------------------------*/
#include "fake_gas_sensor.h"
int main( int argc, char** argv )
{
ros::init(argc, argv, NODE_NAME);
ros::NodeHandle n;
ros::NodeHandle pn("~");
//Read parameters
loadNodeParameters(pn);
//Publishers
ros::Publisher sensor_read_pub = n.advertise<olfaction_msgs::gas_sensor>("Sensor_reading", 500);
ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("Sensor_display", 100);
//Service to request gas concentration
ros::ServiceClient client = n.serviceClient<gaden_player::GasPosition>("/odor_value");
//Init Visualization data (marker)
//---------------------------------
// sensor = sphere
// conector = stick from the floor to the sensor
visualization_msgs::Marker sensor,connector;
sensor.header.frame_id = input_fixed_frame.c_str();
sensor.ns = "sensor_visualization";
sensor.action = visualization_msgs::Marker::ADD;
sensor.type = visualization_msgs::Marker::SPHERE;
sensor.id = 0;
sensor.scale.x = 0.1;
sensor.scale.y = 0.1;
sensor.scale.z = 0.1;
sensor.color.r = 2.0f;
sensor.color.g = 1.0f;
sensor.color.a = 1.0;
connector.header.frame_id = input_fixed_frame.c_str();
connector.ns = "sensor_visualization";
connector.action = visualization_msgs::Marker::ADD;
connector.type = visualization_msgs::Marker::CYLINDER;
connector.id = 1;
connector.scale.x = 0.1;
connector.scale.y = 0.1;
connector.color.a = 1.0;
connector.color.r = 1.0f;
connector.color.b = 1.0f;
connector.color.g = 1.0f;
// Loop
tf::TransformListener listener;
node_rate = 5; //Hz
ros::Rate r(node_rate);
first_reading = true;
notified = false;
while (ros::ok())
{
//Vars
tf::StampedTransform transform;
bool know_sensor_pose = true;
//Get pose of the sensor in the /map reference
try
{
listener.lookupTransform(input_fixed_frame.c_str(), input_sensor_frame.c_str(),
ros::Time(0), transform);
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s",ex.what());
know_sensor_pose = false;
ros::Duration(1.0).sleep();
}
if (know_sensor_pose)
{
//Current sensor pose
float x_pos = transform.getOrigin().x();
float y_pos = transform.getOrigin().y();
float z_pos = transform.getOrigin().z();
// Get Gas concentration at current position (of each gas present)
// Service request to the simulator
gaden_player::GasPosition srv;
srv.request.x.push_back(x_pos);
srv.request.y.push_back(y_pos);
srv.request.z.push_back(z_pos);
if (client.call(srv))
{
/*
for (int i=0; i<srv.response.gas_type.size(); i++)
{
ROS_INFO("[FakeMOX] %s:%.4f at (%.2f,%.2f,%.2f)",srv.response.gas_type[i].c_str(), srv.response.gas_conc[i],srv.request.x, srv.request.y, srv.request.z );
}
*/
//Simulate Gas_Sensor response given this GT values of the concentration!
olfaction_msgs::gas_sensor sensor_msg;
sensor_msg.header.frame_id = input_sensor_frame;
sensor_msg.header.stamp = ros::Time::now();
switch (input_sensor_model)
{
case 0: //MOX TGS2620
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2620;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response);
sensor_msg.raw_air = Sensitivity_Air[input_sensor_model]*R0[input_sensor_model];
sensor_msg.calib_A = sensitivity_lineloglog[input_sensor_model][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[input_sensor_model][0][1]; //Calib for Ethanol
break;
case 1: //MOX TGS2600
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2600;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response);
sensor_msg.raw_air = Sensitivity_Air[input_sensor_model]*R0[input_sensor_model];
sensor_msg.calib_A = sensitivity_lineloglog[input_sensor_model][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[input_sensor_model][0][1]; //Calib for Ethanol
break;
case 2: //MOX TGS2611
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2611;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response);
sensor_msg.raw_air = Sensitivity_Air[input_sensor_model]*R0[input_sensor_model];
sensor_msg.calib_A = sensitivity_lineloglog[input_sensor_model][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[input_sensor_model][0][1]; //Calib for Ethanol
break;
case 3: //MOX TGS2610
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2610;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response);
sensor_msg.raw_air = Sensitivity_Air[input_sensor_model]*R0[input_sensor_model];
sensor_msg.calib_A = sensitivity_lineloglog[input_sensor_model][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[input_sensor_model][0][1]; //Calib for Ethanol
break;
case 4: //MOX TGS2612
sensor_msg.technology = sensor_msg.TECH_MOX;
sensor_msg.manufacturer = sensor_msg.MANU_FIGARO;
sensor_msg.mpn = sensor_msg.MPN_TGS2612;
sensor_msg.raw_units = sensor_msg.UNITS_OHM;
sensor_msg.raw = simulate_mox_as_line_loglog(srv.response);
sensor_msg.raw_air = Sensitivity_Air[input_sensor_model]*R0[input_sensor_model];
sensor_msg.calib_A = sensitivity_lineloglog[input_sensor_model][0][0]; //Calib for Ethanol
sensor_msg.calib_B = sensitivity_lineloglog[input_sensor_model][0][1]; //Calib for Ethanol
break;
case 30: //PID miniRaeLite
sensor_msg.technology = sensor_msg.TECH_PID;
sensor_msg.manufacturer = sensor_msg.MANU_RAE;
sensor_msg.mpn = sensor_msg.MPN_MINIRAELITE;
sensor_msg.raw_units = sensor_msg.UNITS_PPM;
sensor_msg.raw = simulate_pid(srv.response);
sensor_msg.raw_air = 0.0;
sensor_msg.calib_A = 0.0;
sensor_msg.calib_B = 0.0;
break;
default:
break;
}
//Publish simulated sensor reading
sensor_read_pub.publish(sensor_msg);
notified = false;
}
else
{
if (!notified)
{
ROS_WARN("[fake_gas_sensor] Cannot read Gas Concentrations from simulator.");
notified = true;
}
}
//Publish RVIZ sensor pose
sensor.header.stamp = ros::Time::now();
sensor.pose.position.x = x_pos;
sensor.pose.position.y = y_pos;
sensor.pose.position.z = z_pos;
marker_pub.publish(sensor);
connector.header.stamp = ros::Time::now();
connector.scale.z = z_pos;
connector.pose.position.x = x_pos;
connector.pose.position.y = y_pos;
connector.pose.position.z = float(z_pos)/2;
marker_pub.publish(connector);
}
ros::spinOnce();
r.sleep();
}
}
// Simulate MOX response: Sensitivity + Dynamic response
// RS = R0*( A * conc^B )
// This method employes a curve fitting based on a line in the loglog scale to set the sensitivity
float simulate_mox_as_line_loglog(gaden_player::GasPositionResponse GT_gas_concentrations)
{
if (first_reading)
{
//Init sensor to its Baseline lvl
sensor_output = Sensitivity_Air[input_sensor_model]; //RS_R0 value at air
previous_sensor_output = sensor_output;
first_reading = false;
}
else
{
//1. Set Sensor Output based on gas concentrations (gas type dependent)
//---------------------------------------------------------------------
// RS/R0 = A*conc^B (a line in the loglog scale)
float resistance_variation = 0.0;
//Handle multiple gases
for (int i=0; i<GT_gas_concentrations.positions[0].concentration.size(); i++)
{
int gas_id;
if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"ethanol"))
gas_id = 0;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"methane"))
gas_id = 1;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"hydrogen"))
gas_id = 2;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"propanol"))
gas_id = 3;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"chlorine"))
gas_id = 4;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"fluorine"))
gas_id = 5;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"acetone"))
gas_id = 6;
else
{
ROS_ERROR("[fake_mox] MOX response is not configured for this gas type!");
return 0.0;
}
//JUST FOR VIDEO DEMO
/*
if (input_sensor_model == 0)
{
GT_gas_concentrations.gas_conc[i] *= 10;
}
else if (input_sensor_model ==2)
{
GT_gas_concentrations.gas_conc[i] *= 20;
}
*/
//Value of RS/R0 for the given gas and concentration
RS_R0 = sensitivity_lineloglog[input_sensor_model][gas_id][0] * pow(GT_gas_concentrations.positions[0].concentration[i], sensitivity_lineloglog[input_sensor_model][gas_id][1]);
//ROS_INFO("Sensor model: %d - Gas conc: %f", input_sensor_model, GT_gas_concentrations.positions[0].concentration[i]);
//Ensure we never overpass the baseline level (max allowed)
if (RS_R0 > Sensitivity_Air[input_sensor_model])
RS_R0 = Sensitivity_Air[input_sensor_model];
//Increment with respect the Baseline
resistance_variation += Sensitivity_Air[input_sensor_model] - RS_R0;
}
//Calculate final RS_R0 given the final resistance variation
RS_R0 = Sensitivity_Air[input_sensor_model] - resistance_variation;
//Ensure a minimum sensor resitance
if (RS_R0 <= 0.0)
RS_R0 = 0.01;
//2. Simulate transient response (dynamic behaviour, tau_r and tau_d)
//---------------------------------------------------------------------
float tau;
if (RS_R0 < previous_sensor_output) //rise
tau = tau_value[input_sensor_model][0][0];
else //decay
tau = tau_value[input_sensor_model][0][1];
// Use a low pass filter
//alpha value = At/(tau+At)
float alpha = (1/node_rate) / (tau+(1/node_rate));
//filtered response (uses previous estimation):
sensor_output = (alpha*RS_R0) + (1-alpha)*previous_sensor_output;
//Update values
previous_sensor_output = sensor_output;
}
// Return Sensor response for current time instant as the Sensor Resistance in Ohms
return (sensor_output * R0[input_sensor_model]);
}
// Simulate PID response : Weighted Sum of all gases
float simulate_pid(gaden_player::GasPositionResponse GT_gas_concentrations)
{
//Handle multiple gases
float accumulated_conc = 0.0;
for (int i=0; i<GT_gas_concentrations.positions[0].concentration.size(); i++)
{
if (use_PID_correction_factors)
{
int gas_id;
if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"ethanol"))
gas_id = 0;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"methane"))
gas_id = 1;
else if (!strcmp(GT_gas_concentrations.gas_type[i].c_str(),"hydrogen"))
gas_id = 2;
else
{
ROS_ERROR("[fake_PID] PID response is not configured for this gas type!");
return 0.0;
}
if (PID_correction_factors[gas_id] != 0)
accumulated_conc += GT_gas_concentrations.positions[0].concentration[i] / PID_correction_factors[gas_id];
}
else
accumulated_conc += GT_gas_concentrations.positions[0].concentration[i];
}
return accumulated_conc;
}
// ===============================//
// Load Node Parameters //
// ===============================//
void loadNodeParameters(ros::NodeHandle private_nh)
{
//fixed frame
private_nh.param<std::string>("fixed_frame", input_fixed_frame, "map");
//Sensor Model
private_nh.param<int>("sensor_model", input_sensor_model, DEFAULT_SENSOR_MODEL);
//sensor_frame
private_nh.param<std::string>("sensor_frame", input_sensor_frame, DEFAULT_SENSOR_FRAME);
//PID_correction_factors
private_nh.param<bool>("use_PID_correction_factors", use_PID_correction_factors, false);
ROS_INFO("The data provided in the roslaunch file is:");
ROS_INFO("Sensor model: %d", input_sensor_model);
ROS_INFO("Fixed frame: %s",input_fixed_frame.c_str());
ROS_INFO("Sensor frame: %s",input_sensor_frame.c_str());
}
| 15,494 | C++ | 39.883905 | 188 | 0.550471 |
tudelft/autoGDMplus/gaden_ws/src/gaden/test_env/decompress/src/comp.cpp | #include <fstream>
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <boost/format.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/copy.hpp>
int main(int argc, char *argv[]){
using namespace std;
if(argc!=3){
cout << "Correct format is \"decompress inputFile outputFile\"";
}else{
ifstream infile(argv[1], ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::zlib_decompressor());
inbuf.push(infile);
ofstream out(argv[2]);
boost::iostreams::copy(inbuf,out);
}
}
| 705 | C++ | 26.153845 | 77 | 0.655319 |
tudelft/autoGDMplus/gaden_ws/src/gaden/test_env/decompress/src/toASCII.cpp | #include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <boost/format.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/copy.hpp>
int main(int argc, char *argv[]){
if(argc!=3){
std::cout << "Correct format is \"toASCII inputFile outputFile\"";
return -1;
}
std::ifstream infile(argv[1], std::ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::zlib_decompressor());
inbuf.push(infile);
std::stringstream decompressed;
boost::iostreams::copy(inbuf,decompressed);
std::ofstream outFile (argv[2], std::ios::out);
double bufferD;
int bufferInt;
decompressed.read((char*) &bufferInt, sizeof(int));
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<"env_min "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD<<"\n";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<"env_max "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD<<"\n";
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<"NumCells_XYZ "<<bufferInt;
int cells_x=bufferInt;
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<" "<<bufferInt;
int cells_y=bufferInt;
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<" "<<bufferInt<<"\n";
int cells_z=bufferInt;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<"CellSizes_XYZ "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD<<"\n";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<"GasSourceLocation_XYZ "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD;
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<" "<<bufferD<<"\n";
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<"GasType "<<bufferInt<<"\n";
outFile<<"Number of moles per filament ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<"\nMoles of all gases in cm3 ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<"\n";
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<bufferInt<<"\n";
while(decompressed.peek()!=EOF){
decompressed.read((char*) &bufferInt, sizeof(int));
outFile<<bufferInt<<" ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<" ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<" ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<" ";
decompressed.read((char*) &bufferD, sizeof(double));
outFile<<bufferD<<"\n";
}
outFile.close();
return 0;
} | 3,274 | C++ | 31.75 | 74 | 0.635614 |
tudelft/autoGDMplus/gaden_ws/src/gaden/gaden_gui/gui.py | from tkinter import *
from tkinter import filedialog
import re
root = Tk()
root.geometry('780x700')
left=Frame(root, width=350)
right=Frame(root, width=350)
left.grid(row=0, column=0, sticky=N)
right.grid(row=0, column=1, sticky=N)
leftList=[]
modelFiles=[]
windF = ""
###################################################################################################################################
# GADEN_preprocessing.launch
###################################################################################################################################
def getModelFile(ent):
file= filedialog.askopenfilename(filetypes=(("STL files", "*.stl"), ("All files", "*.*") ) )
ent.delete(0,END)
ent.insert(0, file)
def getCSVFile(ent):
file= filedialog.askopenfilename(filetypes=(("CSV files", "*.csv"), ("All files", "*.*") ) )
ent.delete(0,END)
ent.insert(0, file)
def addFile():
entryModel = Entry(left)
modelLabel = Label(left, text="Model "+str(len(modelFiles)))
modelFileButton = Button(left, text="...", command=lambda: getModelFile(entryModel))
#rearrange the grid to fit the new entry field
leftList.insert(len(modelFiles)+2,[modelLabel,entryModel,modelFileButton])
modelFiles.append(entryModel)
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid(row=row, column=col)
#entry field for size of cell side
cellSizeLabel= Label(left, text="Cell size: ")
cellSizeEntry = Entry(left)
#label for list of models
modelsLabel= Label(left, text="STL models of environment")
#button to create more filepath entry fields
addFileButton= Button(left, text="+", command=addFile)
#empty point coordinates
emptyPointLabel=Label(left, text="Coordinates of empty point")
xEmptyPoint = Entry(left)
yEmptyPoint = Entry(left)
zEmptyPoint = Entry(left)
xEmptyPoint.insert(END, "x")
yEmptyPoint.insert(END, "y")
zEmptyPoint.insert(END, "z")
#wind files
windLabel = Label(left, text="Wind files")
homogeneous=BooleanVar()
homogeneous.set(False)
check = Checkbutton(left, text="Homogeneous", variable=homogeneous, onvalue=True, offvalue=False)
windEntry=Entry(left)
windFileButton = Button(left, text="...", command=lambda: getCSVFile(windEntry))
leftList.append([cellSizeLabel, cellSizeEntry])
leftList.append([modelsLabel])
leftList.append([addFileButton])
leftList.append([emptyPointLabel])
leftList.append([xEmptyPoint])
leftList.append([yEmptyPoint])
leftList.append([zEmptyPoint])
leftList.append([windLabel])
leftList.append([check,windEntry,windFileButton])
#create the first file entry field for CAD models automatically
addFile()
#right side of window
outletModelFiles=[]
rightList=[]
def addOutletFile():
entryModel = Entry(right)
modelLabel = Label(right, text="Outlet model "+str(len(outletModelFiles)))
modelFileButton = Button(right, text="...", command=lambda: getModelFile(entryModel))
#rearrange the grid to fit the new entry field
rightList.insert(len(outletModelFiles)+2,[modelLabel,entryModel,modelFileButton])
outletModelFiles.append(entryModel)
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
def getOutputFile(ent):
file= filedialog.askdirectory()
ent.delete(0,END)
ent.insert(0, file)
#empty row
emptyLabel= Label(right, text=" ")
#label for list of outlet
outletsLabel= Label(right, text="STL models of outlets")
#button to create more filepath entry fields
addOutletButton= Button(right, text="+", command=addOutletFile)
#output path for files
outputLabel = Label(right, text="Preprocessing output path: ")
outputEntry=Entry(right)
outputButton = Button(right, text="...", command=lambda: getOutputFile(outputEntry))
#save launch file
def savePreprocessingFile():
global windF
f=open("GADEN_preprocessing.launch","w")
f.write(
"<launch>\n"+
" <node pkg=\"gaden_preprocessing\" type=\"preprocessing\" name=\"preprocessing\" output=\"screen\">\n"+
" <param name=\"cell_size\" value=\""+cellSizeEntry.get()+"\"/>\n\n"+
" <param name=\"number_of_models\" value=\""+str(len(modelFiles))+"\"/>\n"
)
for ind in range(0,len(modelFiles)):
f.write(
" <param name=\"model_"+str(ind)+"\" value=\""+modelFiles[ind].get()+"\"/>\n")
f.write("\n"+
" <param name=\"number_of_outlet_models\" value=\""+str(len(outletModelFiles))+"\"/>\n")
for ind in range(0,len(outletModelFiles)):
f.write(
" <param name=\"outlets_model_"+str(ind)+"\" value=\""+outletModelFiles[ind].get()+"\"/>\n")
windF = re.sub("_0.csv","",windEntry.get())
f.write(
"\n"+
" <param name=\"empty_point_x\" value=\""+str(xEmptyPoint.get())+"\"/>\n"+
" <param name=\"empty_point_y\" value=\""+str(yEmptyPoint.get())+"\"/>\n"+
" <param name=\"empty_point_z\" value=\""+str(zEmptyPoint.get())+"\"/>\n\n"+
" <param name=\"uniformWind\" value=\""+str(homogeneous.get())+"\"/>\n"
" <param name=\"wind_files\" value=\""+windF+"\"/>\n\n"+
" <param name=\"output_path\" value=\""+outputEntry.get()+"\"/>\n"
" </node>\n"+
"</launch>"
)
savedLabel= Label(right, text="Launch file saved!")
nextButton = Button(right, text="Continue", command=filamentSim)
rightList.append([savedLabel])
rightList.append([nextButton])
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
saveButton = Button(right, text="Save", command=savePreprocessingFile)
rightList.append([emptyLabel])
rightList.append([outletsLabel])
rightList.append([addOutletButton])
rightList.append([outputLabel, outputEntry, outputButton])
rightList.append([saveButton])
addOutletFile()
###################################################################################################################################
# GADEN.launch
###################################################################################################################################
def getColladaFile(ent):
file= filedialog.askopenfilename(filetypes=(("Collada files", "*.dae"), ("All files", "*.*") ) )
ent.delete(0,END)
ent.insert(0, file)
def getWindFile(ent):
file= filedialog.askopenfilename(filetypes=(("Wind files", "*_U"), ("All files", "*.*") ) )
ent.delete(0,END)
ent.insert(0, file)
def addColladaFile():
entryModel = Entry(left)
modelLabel = Label(left, text="Model "+str(len(modelFiles)))
modelFileButton = Button(left, text="...", command=lambda: getColladaFile(entryModel))
#rearrange the grid to fit the new entry field
leftList.insert(len(modelFiles)+2,[modelLabel,entryModel,modelFileButton])
modelFiles.append(entryModel)
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid(row=row, column=col)
startWind = Entry(left)
endWind = Entry(left)
def loopWind(*args):
if looping.get():
startLabel = Label(left,text="From:")
endLabel = Label(left,text="To:")
leftList.append([startLabel, startWind])
leftList.append([endLabel, endWind])
else:
for col in range(0,len(leftList[len(leftList)-1])):
leftList[len(leftList)-1][col].grid_forget()
leftList.pop(len(leftList)-1)
for col in range(0,len(leftList[len(leftList)-1])):
leftList[len(leftList)-1][col].grid_forget()
leftList.pop(len(leftList)-1)
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid(row=row, column=col)
def filamentSim():
global leftList, rightList, modelFiles, looping
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid_forget()
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid_forget()
leftList=[]
rightList=[]
modelFiles=[]
windEntryFilament.insert(END, windF+"_0.csv_U")
occupancy3DEntry.insert(END, outputEntry.get()+"/OccupancyGrid3D.csv")
leftList.append([occupancyLabel,occupancy3DEntry,occupancy3DButton])
leftList.append([modelsLabel])
leftList.append([addFileButton])
leftList.append([SourcePosLabel])
leftList.append([xSourcePos])
leftList.append([ySourcePos])
leftList.append([zSourcePos])
leftList.append([windLabelFilament,windEntryFilament,windButtonFilament])
leftList.append([windDurationLabel, windDurationEntry])
leftList.append([checkLooping])
addColladaFile()
rightList.append([checkVerbose])
rightList.append([simTimeLabel,simTimeEntry])
rightList.append([numFilamentsLabel,numFilamentsEntry])
rightList.append([checkVariableRate])
rightList.append([ppmLabel,ppmEntry])
rightList.append([initialStdLabel,initialStdEntry])
rightList.append([growthGammaLabel,growthGammaEntry])
rightList.append([initialStdLabel,initialStdEntry])
rightList.append([noiseLabel,noiseEntry])
rightList.append([gasTypeLabel,gasTypeChoice])
rightList.append([temperatureLabel,temperatureEntry])
rightList.append([pressureLabel,pressureEntry])
rightList.append([emptyLabel])
rightList.append([resultsPathLabel,resultsPathEntry,resultsPathButton])
rightList.append([resultsMinLabel,resultsMinEntry])
rightList.append([resultsIntervalLabel,resultsIntervalEntry])
rightList.append([saveFilButton])
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
occupancyLabel = Label(left, text="Occupancy3D file: ")
occupancy3DEntry=Entry(left)
occupancy3DButton = Button(left, text="...", command=lambda: getCSVFile(occupancy3DEntry))
#label for list of models
modelsLabel= Label(left, text="Collada models (visualization)")
#button to create more filepath entry fields
addFileButton= Button(left, text="+", command=addColladaFile)
#source position
SourcePosLabel=Label(left, text="Coordinates of gas source")
xSourcePos = Entry(left)
ySourcePos = Entry(left)
zSourcePos = Entry(left)
xSourcePos.insert(END, "x")
ySourcePos.insert(END, "y")
zSourcePos.insert(END, "z")
#wind options
windLabelFilament = Label(left, text="Wind filepath: ")
windEntryFilament=Entry(left)
windButtonFilament = Button(left, text="...", command=lambda: getWindFile(windEntryFilament))
windDurationLabel = Label(left, text="Seconds per\nwind snapshot")
windDurationEntry = Entry(left)
looping = BooleanVar()
looping.set(False)
checkLooping = Checkbutton(left, text="Allow looping", variable=looping, onvalue=True, offvalue=False)
looping.trace("w",loopWind)
### right side
verbose = BooleanVar()
verbose.set(False)
checkVerbose = Checkbutton(right, text="Verbose", variable=verbose, onvalue=True, offvalue=False)
simTimeLabel= Label(right, text="Simulation length (s)")
simTimeEntry = Entry(right)
simTimeEntry.insert(END, "300")
timeStepLabel= Label(right, text="Time step (s)")
timeStepEntry = Entry(right)
timeStepEntry.insert(END, "0.1")
numFilamentsLabel= Label(right, text="Filaments/second")
numFilamentsEntry = Entry(right)
numFilamentsEntry.insert(END, "10")
variableRate = BooleanVar()
variableRate.set(False)
checkVariableRate = Checkbutton(right, text="Variable rate", variable=variableRate, onvalue=True, offvalue=False)
ppmLabel= Label(right, text="Concentration at\nfilament center(ppm)")
ppmEntry = Entry(right)
ppmEntry.insert(END, "10")
initialStdLabel= Label(right, text="Initial stdDev (cm)")
initialStdEntry = Entry(right)
initialStdEntry.insert(END, "5")
growthGammaLabel= Label(right, text="Filament growth (cm²/s)")
growthGammaEntry = Entry(right)
growthGammaEntry.insert(END, "5")
noiseLabel= Label(right, text="Movement noise (m)")
noiseEntry = Entry(right)
noiseEntry.insert(END, "0.01")
gasTypeLabel=Label(right, text="Gas Type:")
gasTypeList=["Ethanol","Methane","Hydrogen","Propanol","Chlorine","Fluorine","Acetone","Neon","Helium"]
gasType = StringVar(root)
gasType.set("Ethanol")
gasTypeChoice=OptionMenu(right, gasType, *gasTypeList)
temperatureLabel= Label(right, text="Temperature (K)")
temperatureEntry = Entry(right)
temperatureEntry.insert(END, "298")
pressureLabel= Label(right, text="Pressure (atm)")
pressureEntry = Entry(right)
pressureEntry.insert(END, "1")
#output path for files
resultsPathLabel = Label(right, text="Results directory path: ")
resultsPathEntry=Entry(right)
resultsPathButton = Button(right, text="...", command=lambda: getOutputFile(resultsPathEntry))
resultsMinLabel= Label(right, text="Results start (s)")
resultsMinEntry = Entry(right)
resultsMinEntry.insert(END, "0.0")
resultsIntervalLabel= Label(right, text="Results interval (s)")
resultsIntervalEntry = Entry(right)
resultsIntervalEntry.insert(END, "0.5")
#save launch file
def saveFilamentSimFile():
global windF
f=open("GADEN.launch","w")
f.write(
"<launch>\n"+
" <node pkg=\"gaden_environment\" type=\"environment\" name=\"environment\" output=\"screen\">\n"+
" <param name=\"verbose\" value=\"false\"/>\n"+
" <param name=\"wait_preprocessing\" value=\"false\"/>\n"+
" <param name=\"number_of_CAD\" value=\""+str(len(modelFiles))+"\"/>\n"+
" <rosparam subst_value=\"True\">\n"
)
for ind in range(0,len(modelFiles)):
f.write(
" CAD_"+str(ind)+": file:// "+modelFiles[ind].get()+"\n"+
" CAD_"+str(ind)+"_color: [0.5,0.5,0.5]\n")
f.write(" </rosparam>\n\n"+
" <param name=\"occupancy3D_data\" value=\""+occupancy3DEntry.get()+"\"/>\n\n"+
" <param name=\"number_of_sources\" value=\"1\"/>\n"+
" <param name=\"source_0_position_x\" value=\""+xSourcePos.get()+"\"/>\n"+
" <param name=\"source_0_position_y\" value=\""+ySourcePos.get()+"\"/>\n"+
" <param name=\"source_0_position_z\" value=\""+zSourcePos.get()+"\"/>\n"+
" <rosparam>\n"+
" source_0_scale: 0.2\n"
" source_0_color: [0.0, 1.0, 0.0]\n"
" </rosparam>\n"+
"</node>\n\n")
f.write(
" <node pkg=\"gaden_filament_simulator\" type=\"filament_simulator\" name=\"filament_simulator\" output=\"screen\">\n"+
" <param name=\"verbose\" value=\""+str(verbose.get())+"\"/>\n"+
" <param name=\"wait_preprocessing\" value=\"false\"/>\n"+
" <param name=\"sim_time\" value=\""+simTimeEntry.get()+"\"/>\n"+
" <param name=\"time_step\" value=\""+timeStepEntry.get()+"\"/>\n"+
" <param name=\"num_filaments_sec\" value=\""+numFilamentsEntry.get()+"\"/>\n"+
" <param name=\"variable_rate\" value=\""+str(variableRate.get())+"\"/>\n"+
" <param name=\"filaments_stop_steps\" value=\"0\"/>\n"+
" <param name=\"ppm_filament_center\" value=\""+ppmEntry.get()+"\"/>\n"+
" <param name=\"filament_initial_std\" value=\""+initialStdEntry.get()+"\"/>\n"+
" <param name=\"filament_growth_gamma\" value=\""+growthGammaEntry.get()+"\"/>\n"+
" <param name=\"filament_noise_std\" value=\""+noiseEntry.get()+"\"/>\n"+
" <param name=\"gas_type\" value=\""+str(gasTypeList.index(gasType.get()))+"\"/>\n"+
" <param name=\"temperature\" value=\""+temperatureEntry.get()+"\"/>\n"+
" <param name=\"pressure\" value=\""+pressureEntry.get()+"\"/>\n"+
" <param name=\"concentration_unit_choice\" value=\"1\"/>\n"+
" <param name=\"occupancy3D_data\" value=\""+occupancy3DEntry.get()+"\"/>\n"+
" <param name=\"fixed_frame\" value=\"map\"/>\n\n"+
" <param name=\"wind_data\" value=\""+re.sub("0.csv_U","",windEntryFilament.get())+"\"/>\n"+
" <param name=\"wind_time_step\" value=\""+windDurationEntry.get()+"\"/>\n"+
" <param name=\"allow_looping\" value=\""+str(looping.get())+"\"/>\n"+
" <param name=\"loop_from_step\" value=\""+startWind.get()+"\"/>\n"+
" <param name=\"loop_to_step\" value=\""+endWind.get()+"\"/>\n\n"+
" <param name=\"source_position_x\" value=\""+xSourcePos.get()+"\"/>\n"+
" <param name=\"source_position_y\" value=\""+ySourcePos.get()+"\"/>\n"+
" <param name=\"source_position_z\" value=\""+zSourcePos.get()+"\"/>\n\n"+
" <param name=\"save_results\" value=\"1\"/>\n"+
" <param name=\"results_min_time\" value=\""+resultsMinEntry.get()+"\"/>\n"+
" <param name=\"results_time_step\" value=\""+resultsIntervalEntry.get()+"\"/>\n"+
" <param name=\"writeConcentrations\" value=\"true\"/>\n"+
" <param name=\"results_location\" value=\""+resultsPathEntry.get()+"\"/>\n"+
" </node>\n\n"
)
f.write(
" <node name=\"rviz\" pkg=\"rviz\" type=\"rviz\" args=\"-d $(find test_env)/10x6_empty_room/launch/ros/gaden.rviz\"/>\n"+
"</launch>")
savedLabel= Label(right, text="Launch file saved!")
nextButton = Button(right, text="Continue",command=player)
rightList.append([savedLabel])
rightList.append([nextButton])
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
saveFilButton = Button(right, text="Save", command=saveFilamentSimFile)
###################################################################################################################################
# GADEN_player.launch
###################################################################################################################################
def parseF(st):
try:
return "{:.2f}".format(float(st))
except ValueError:
return st
def player():
global leftList, rightList, startWind, endWind
looping.set(False)
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid_forget()
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid_forget()
leftList = []
rightList = []
leftList.append([occupancyLabel,occupancy3DEntry,occupancy3DButton])
leftList.append([modelsLabel])
for index in range(0,len(modelFiles)):
entryModel = modelFiles[index]
modelLabel = Label(left, text="Model "+str(index))
modelFileButton = Button(left, text="...", command=lambda: getColladaFile(entryModel))
leftList.append([modelLabel, entryModel, modelFileButton])
leftList.append([addFileButton])
leftList.append([initialIterationLabel, initialIterationEntry])
startWind = Entry(left)
endWind = Entry(left)
leftList.append([checkLooping])
for row in range(0,len(leftList)):
for col in range(0,len(leftList[row])):
leftList[row][col].grid(row=row, column=col)
####
rightList.append([logFilesLabel])
rightList.append([logFilesEntry, logFilesButton])
logFilesEntry.insert(0,
resultsPathEntry.get()+"/FilamentSimulation_gasType_"+str(gasTypeList.index(gasType.get()))
+"_sourcePosition_"+parseF(xSourcePos.get())+"_"+parseF(ySourcePos.get())+"_"+parseF(zSourcePos.get())+"_iteration_"
)
rightList.append([frequencyLabel, frequencyEntry])
try:
frequencyEntry.insert(0, int(1.0/float(resultsIntervalEntry.get())))
except:
pass
xSourcePos_2 = Entry(right)
xSourcePos_2.insert(0, xSourcePos.get())
ySourcePos_2 = Entry(right)
ySourcePos_2.insert(0, ySourcePos.get())
zSourcePos_2 = Entry(right)
zSourcePos_2.insert(0, zSourcePos.get())
SourcePosLabel=Label(right, text="Coordinates of gas source")
rightList.append([SourcePosLabel])
rightList.append([xSourcePos_2])
rightList.append([ySourcePos_2])
rightList.append([zSourcePos_2])
rightList.append([savePlayerButton])
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
def savePlayer():
f=open("GADEN_player.launch","w")
f.write(
"<launch>\n"+
" <node pkg=\"gaden_environment\" type=\"environment\" name=\"environment\" output=\"screen\">\n"+
" <param name=\"verbose\" value=\"false\"/>\n"+
" <param name=\"wait_preprocessing\" value=\"false\"/>\n"+
" <param name=\"number_of_CAD\" value=\""+str(len(modelFiles))+"\"/>\n"+
" <rosparam subst_value=\"True\">\n"
)
for ind in range(0,len(modelFiles)):
f.write(
" CAD_"+str(ind)+": file:// "+modelFiles[ind].get()+"\n"+
" CAD_"+str(ind)+"_color: [0.5,0.5,0.5]\n")
f.write(" </rosparam>\n\n"+
" <param name=\"occupancy3D_data\" value=\""+occupancy3DEntry.get()+"\"/>\n\n"+
" <param name=\"number_of_sources\" value=\"1\"/>\n"+
" <param name=\"source_0_position_x\" value=\""+xSourcePos.get()+"\"/>\n"+
" <param name=\"source_0_position_y\" value=\""+ySourcePos.get()+"\"/>\n"+
" <param name=\"source_0_position_z\" value=\""+zSourcePos.get()+"\"/>\n"+
" <rosparam>\n"+
" source_0_scale: 0.2\n"
" source_0_color: [0.0, 1.0, 0.0]\n"
" </rosparam>\n"+
"</node>\n\n")
f.write(
" <node pkg=\"gaden_player\" type=\"gaden_player\" name=\"gaden_player\" output=\"screen\">\n"+
" <param name=\"verbose\" value=\"false\" />\n"+
" <param name=\"player_freq\" value=\""+frequencyEntry.get()+"\"/>\n"+
" <param name=\"initial_iteration\" value=\""+initialIterationEntry.get()+"\"/>\n"+
" <param name=\"num_simulators\" value=\"1\" />\n"+
" <param name=\"simulation_data_0\" value=\""+logFilesEntry.get()+"\" />\n"+
" <param name=\"allow_looping\" value=\""+str(looping.get())+"\" />\n"+
" <param name=\"loop_from_iteration\" value=\""+startWind.get()+"\" />\n"+
" <param name=\"loop_to_iteration\" value=\""+endWind.get()+"\" />\n"
" </node>\n\n"
)
f.write(
" <node name=\"rviz\" pkg=\"rviz\" type=\"rviz\" args=\"-d $(find test_env)/10x6_empty_room/launch/ros/gaden.rviz\"/>\n"+
"</launch>")
doneLabel = Label(right, text="Done!")
rightList.append([doneLabel])
for row in range(0,len(rightList)):
for col in range(0,len(rightList[row])):
rightList[row][col].grid(row=row, column=col)
def getLogs(ent):
file= filedialog.askopenfilename()
ent.delete(0,END)
ent.insert(0, re.sub("iteration_.*","iteration_",file))
initialIterationLabel = Label(left, text="Initial iteration:")
initialIterationEntry = Entry(left)
initialIterationEntry.insert(0, "0")
frequencyLabel = Label(right, text="Playback frequency (Hz):")
frequencyEntry = Entry(right)
logFilesLabel= Label(right, text="Simulation log files:")
logFilesEntry = Entry(right)
logFilesButton = Button(right, text="...", command=lambda: getLogs(logFilesEntry))
savePlayerButton = Button(right, text="Save", command=savePlayer)
root.mainloop()
| 23,348 | Python | 38.176174 | 131 | 0.620953 |
elsayedelsheikh/dishwaher/README.md | # DishWasher
Calculate the dimesions of an object (cm)
```bash
import omni.isaac.core.utils.bounds as bounds_utils
cache = bounds_utils.create_bbox_cache()
bounds = bounds_utils.compute_aabb(cache, prim_path="/Root/bin/Visuals/FOF_Mesh_Magenta_Box")
length_x = bounds[3] - bounds[0]
length_y = bounds[4] - bounds[1]
length_z = bounds[5] - bounds[2]
print("length of x:",length_x)
print("length of y:",length_y)
print("length of z:",length_z)
```
| 451 | Markdown | 22.789472 | 93 | 0.707317 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
title = "omni.isaac.dish.washer.manipulator"
description = "Dish Washing Manipulator Project"
authors = ["NVIDIA"]
repository = ""
keywords = []
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.uiapp" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
[[python.module]]
name = "omni_isaac_dish_washer_manipulator_python" | 501 | TOML | 19.079999 | 50 | 0.694611 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/global_variables.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "omni.isaac.dish.washer.manipulator"
EXTENSION_DESCRIPTION = "Dish Washing Manipulator Project"
| 547 | Python | 41.153843 | 76 | 0.809872 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/scenario.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
class ScenarioTemplate:
def __init__(self):
pass
def setup_scenario(self):
pass
def teardown_scenario(self):
pass
def update_scenario(self):
pass
import numpy as np
from omni.isaac.core.utils.types import ArticulationAction
"""
This scenario takes in a robot Articulation and makes it move through its joint DOFs.
Additionally, it adds a cuboid prim to the stage that moves in a circle around the robot.
The particular framework under which this scenario operates should not be taken as a direct
recomendation to the user about how to structure their code. In the simple example put together
in this template, this particular structure served to improve code readability and separate
the logic that runs the example from the UI design.
"""
class ExampleScenario(ScenarioTemplate):
def __init__(self):
pass
def setup_scenario(self, articulation, object_prim):
pass
def teardown_scenario(self):
pass
def update_scenario(self, step: float):
pass
# class ExampleScenario(ScenarioTemplate):
# def __init__(self):
# self._object = None
# self._articulation = None
# self._running_scenario = False
# self._time = 0.0 # s
# self._object_radius = 0.5 # m
# self._object_height = 0.5 # m
# self._object_frequency = 0.25 # Hz
# self._joint_index = 0
# self._max_joint_speed = 4 # rad/sec
# self._lower_joint_limits = None
# self._upper_joint_limits = None
# self._joint_time = 0
# self._path_duration = 0
# self._calculate_position = lambda t, x: 0
# self._calculate_velocity = lambda t, x: 0
# def setup_scenario(self, articulation, object_prim):
# self._articulation = articulation
# self._object = object_prim
# self._initial_object_position = self._object.get_world_pose()[0]
# self._initial_object_phase = np.arctan2(self._initial_object_position[1], self._initial_object_position[0])
# self._object_radius = np.linalg.norm(self._initial_object_position[:2])
# self._running_scenario = True
# self._joint_index = 0
# self._lower_joint_limits = articulation.dof_properties["lower"]
# self._upper_joint_limits = articulation.dof_properties["upper"]
# # teleport robot to lower joint range
# epsilon = 0.001
# articulation.set_joint_positions(self._lower_joint_limits + epsilon)
# self._derive_sinusoid_params(0)
# def teardown_scenario(self):
# self._time = 0.0
# self._object = None
# self._articulation = None
# self._running_scenario = False
# self._joint_index = 0
# self._lower_joint_limits = None
# self._upper_joint_limits = None
# self._joint_time = 0
# self._path_duration = 0
# self._calculate_position = lambda t, x: 0
# self._calculate_velocity = lambda t, x: 0
# def update_scenario(self, step: float):
# if not self._running_scenario:
# return
# self._time += step
# x = self._object_radius * np.cos(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi)
# y = self._object_radius * np.sin(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi)
# z = self._initial_object_position[2]
# self._object.set_world_pose(np.array([x, y, z]))
# self._update_sinusoidal_joint_path(step)
# def _derive_sinusoid_params(self, joint_index: int):
# # Derive the parameters of the joint target sinusoids for joint {joint_index}
# start_position = self._lower_joint_limits[joint_index]
# P_max = self._upper_joint_limits[joint_index] - start_position
# V_max = self._max_joint_speed
# T = P_max * np.pi / V_max
# # T is the expected time of the joint path
# self._path_duration = T
# self._calculate_position = (
# lambda time, path_duration: start_position
# + -P_max / 2 * np.cos(time * 2 * np.pi / path_duration)
# + P_max / 2
# )
# self._calculate_velocity = lambda time, path_duration: V_max * np.sin(2 * np.pi * time / path_duration)
# def _update_sinusoidal_joint_path(self, step):
# # Update the target for the robot joints
# self._joint_time += step
# if self._joint_time > self._path_duration:
# self._joint_time = 0
# self._joint_index = (self._joint_index + 1) % self._articulation.num_dof
# self._derive_sinusoid_params(self._joint_index)
# joint_position_target = self._calculate_position(self._joint_time, self._path_duration)
# joint_velocity_target = self._calculate_velocity(self._joint_time, self._path_duration)
# action = ArticulationAction(
# np.array([joint_position_target]),
# np.array([joint_velocity_target]),
# joint_indices=np.array([self._joint_index]),
# )
# self._articulation.apply_action(action)
| 5,597 | Python | 33.9875 | 120 | 0.624084 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/extension.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import gc
import omni
import omni.kit.commands
import omni.physx as _physx
import omni.timeline
import omni.ui as ui
import omni.usd
from omni.isaac.ui.element_wrappers import ScrollingWindow
from omni.isaac.ui.menu import MenuItemDescription
from omni.kit.menu.utils import add_menu_items, remove_menu_items
from omni.usd import StageEventType
from .global_variables import EXTENSION_DESCRIPTION, EXTENSION_TITLE
from .ui_builder import UIBuilder
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self.ext_id = ext_id
self._usd_context = omni.usd.get_context()
# Build Window
self._window = ScrollingWindow(
title=EXTENSION_TITLE, width=600, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.register_action(
ext_id,
f"CreateUIExtension:{EXTENSION_TITLE}",
self._menu_callback,
description=f"Add {EXTENSION_TITLE} Extension to UI toolbar",
)
self._menu_items = [
MenuItemDescription(name=EXTENSION_TITLE, onclick_action=(ext_id, f"CreateUIExtension:{EXTENSION_TITLE}"))
]
add_menu_items(self._menu_items, EXTENSION_TITLE)
# Filled in with User Functions
self.ui_builder = UIBuilder()
# Events
self._usd_context = omni.usd.get_context()
self._physxIFace = _physx.acquire_physx_interface()
self._physx_subscription = None
self._stage_event_sub = None
self._timeline = omni.timeline.get_timeline_interface()
def on_shutdown(self):
self._models = {}
remove_menu_items(self._menu_items, EXTENSION_TITLE)
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_action(self.ext_id, f"CreateUIExtension:{EXTENSION_TITLE}")
if self._window:
self._window = None
self.ui_builder.cleanup()
gc.collect()
def _on_window(self, visible):
if self._window.visible:
# Subscribe to Stage and Timeline Events
self._usd_context = omni.usd.get_context()
events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = events.create_subscription_to_pop(self._on_stage_event)
stream = self._timeline.get_timeline_event_stream()
self._timeline_event_sub = stream.create_subscription_to_pop(self._on_timeline_event)
self._build_ui()
else:
self._usd_context = None
self._stage_event_sub = None
self._timeline_event_sub = None
self.ui_builder.cleanup()
def _build_ui(self):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_extension_ui()
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_TITLE, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
#################################################################
# Functions below this point call user functions
#################################################################
def _menu_callback(self):
self._window.visible = not self._window.visible
self.ui_builder.on_menu_callback()
def _on_timeline_event(self, event):
if event.type == int(omni.timeline.TimelineEventType.PLAY):
if not self._physx_subscription:
self._physx_subscription = self._physxIFace.subscribe_physics_step_events(self._on_physics_step)
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self._physx_subscription = None
self.ui_builder.on_timeline_event(event)
def _on_physics_step(self, step):
self.ui_builder.on_physics_step(step)
def _on_stage_event(self, event):
if event.type == int(StageEventType.OPENED) or event.type == int(StageEventType.CLOSED):
# stage was opened or closed, cleanup
self._physx_subscription = None
self.ui_builder.cleanup()
self.ui_builder.on_stage_event(event)
def _build_extension_ui(self):
# Call user function for building UI
self.ui_builder.build_ui()
| 6,165 | Python | 37.298136 | 118 | 0.651095 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/__init__.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import *
| 456 | Python | 44.699996 | 76 | 0.809211 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/ui_builder.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
import omni.timeline
import omni.ui as ui
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.objects.cuboid import FixedCuboid
from omni.isaac.core.prims import XFormPrim, GeometryPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import is_prim_path_valid
from omni.isaac.core.utils.stage import add_reference_to_stage, create_new_stage, get_current_stage
from omni.isaac.core.world import World
from omni.isaac.ui.element_wrappers import CollapsableFrame, StateButton
from omni.isaac.ui.element_wrappers.core_connectors import LoadButton, ResetButton
from omni.isaac.ui.ui_utils import get_style
from omni.usd import StageEventType
from pxr import Sdf, UsdLux
from .scenario import ExampleScenario
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper instance
self.wrapped_ui_elements = []
# Get access to the timeline to control stop/pause/play programmatically
self._timeline = omni.timeline.get_timeline_interface()
# Run initialization for the provided example
self._on_init()
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
if event.type == int(omni.timeline.TimelineEventType.STOP):
# When the user hits the stop button through the UI, they will inevitably discover edge cases where things break
# For complete robustness, the user should resolve those edge cases here
# In general, for extensions based off this template, there is no value to having the user click the play/stop
# button instead of using the Load/Reset/Run buttons provided.
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = False
def on_physics_step(self, step: float):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
if event.type == int(StageEventType.OPENED):
# If the user opens a new stage, the extension should completely reset
self._reset_extension()
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
world_controls_frame = CollapsableFrame("World Controls", collapsed=False)
with world_controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._load_btn = LoadButton(
"Load Button", "LOAD", setup_scene_fn=self._setup_scene, setup_post_load_fn=self._setup_scenario
)
self._load_btn.set_world_settings(physics_dt=1 / 60.0, rendering_dt=1 / 60.0)
self.wrapped_ui_elements.append(self._load_btn)
self._reset_btn = ResetButton(
"Reset Button", "RESET", pre_reset_fn=None, post_reset_fn=self._on_post_reset_btn
)
self._reset_btn.enabled = False
self.wrapped_ui_elements.append(self._reset_btn)
run_scenario_frame = CollapsableFrame("Run Scenario")
with run_scenario_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._scenario_state_btn = StateButton(
"Run Scenario",
"RUN",
"STOP",
on_a_click_fn=self._on_run_scenario_a_text,
on_b_click_fn=self._on_run_scenario_b_text,
physics_callback_fn=self._update_scenario,
)
self._scenario_state_btn.enabled = False
self.wrapped_ui_elements.append(self._scenario_state_btn)
######################################################################################
# Functions Below This Point Support The Provided Example And Can Be Deleted/Replaced
######################################################################################
def _on_init(self):
self._articulation = None
self._cuboid = None
self._scenario = ExampleScenario()
# def _add_light_to_stage(self):
# """
# A new stage does not have a light by default. This function creates a spherical light
# """
# sphereLight = UsdLux.SphereLight.Define(get_current_stage(), Sdf.Path("/World/SphereLight"))
# sphereLight.CreateRadiusAttr(2)
# sphereLight.CreateIntensityAttr(100000)
# XFormPrim(str(sphereLight.GetPath())).set_world_pose([6.5, 0, 12])
def _setup_scene(self):
"""
This function is attached to the Load Button as the setup_scene_fn callback.
On pressing the Load Button, a new instance of World() is created and then this function is called.
The user should now load their assets onto the stage and add them to the World Scene.
In this example, a new stage is loaded explicitly, and all assets are reloaded.
If the user is relying on hot-reloading and does not want to reload assets every time,
they may perform a check here to see if their desired assets are already on the stage,
and avoid loading anything if they are. In this case, the user would still need to add
their assets to the World (which has low overhead). See commented code section in this function.
"""
## Environment
create_new_stage()
add_reference_to_stage(get_assets_root_path() + "/Isaac/Environments/Grid/default_environment.usd", "/background")
## Assets
ASSETS_USER_PATH = "/home/sayed/Desktop/DishWasher/github/dishwasher/Assets/"
# Load the UR10e
# robot_prim_path = "/ur10e"
# path_to_robot_usd = get_assets_root_path() + "/Isaac/Robots/UniversalRobots/ur10e/ur10e.usd"
# add_reference_to_stage(path_to_robot_usd, robot_prim_path)
## Load Custom UR10e
robot_prim_path = "/robot"
path_to_robot_usd = ASSETS_USER_PATH + "ur10e.usd"
add_reference_to_stage(path_to_robot_usd, robot_prim_path)
## Load Plate
plate_prim_path = "/theplate"
path_to_plate_usd = ASSETS_USER_PATH + "plate.usd"
add_reference_to_stage(path_to_plate_usd, plate_prim_path)
## Load Bin
bin_prim_path = "/thebin"
path_to_bin_usd = ASSETS_USER_PATH + "bin_fullmodel.usd"
add_reference_to_stage(path_to_bin_usd, bin_prim_path)
# self._articulation = Articulation(robot_prim_path + "/ur_10")
# Add user-loaded objects to the World
world = World.instance()
world.scene.add(XFormPrim(name="manipulator", prim_path= robot_prim_path, position=[0.0, 0.0, 0.52]))
world.scene.add(XFormPrim(name="packing_bin", prim_path= bin_prim_path, position=[0.5, -0.5, 0.0]))
world.scene.add(XFormPrim(name="plate_01", prim_path= plate_prim_path, position=[0.5, 0.5, 0.01]))
# world.scene.add(self._articulation)
# world.scene.add(self._cuboid)
def _setup_scenario(self):
"""
This function is attached to the Load Button as the setup_post_load_fn callback.
The user may assume that their assets have been loaded by their setup_scene_fn callback, that
their objects are properly initialized, and that the timeline is paused on timestep 0.
In this example, a scenario is initialized which will move each robot joint one at a time in a loop while moving the
provided prim in a circle around the robot.
"""
self._reset_scenario()
# UI management
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = True
self._reset_btn.enabled = True
def _reset_scenario(self):
self._scenario.teardown_scenario()
self._scenario.setup_scenario(self._articulation, self._cuboid)
def _on_post_reset_btn(self):
"""
This function is attached to the Reset Button as the post_reset_fn callback.
The user may assume that their objects are properly initialized, and that the timeline is paused on timestep 0.
They may also assume that objects that were added to the World.Scene have been moved to their default positions.
I.e. the cube prim will move back to the position it was in when it was created in self._setup_scene().
"""
self._reset_scenario()
# UI management
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = True
def _update_scenario(self, step: float):
"""This function is attached to the Run Scenario StateButton.
This function was passed in as the physics_callback_fn argument.
This means that when the a_text "RUN" is pressed, a subscription is made to call this function on every physics step.
When the b_text "STOP" is pressed, the physics callback is removed.
Args:
step (float): The dt of the current physics step
"""
self._scenario.update_scenario(step)
def _on_run_scenario_a_text(self):
"""
This function is attached to the Run Scenario StateButton.
This function was passed in as the on_a_click_fn argument.
It is called when the StateButton is clicked while saying a_text "RUN".
This function simply plays the timeline, which means that physics steps will start happening. After the world is loaded or reset,
the timeline is paused, which means that no physics steps will occur until the user makes it play either programmatically or
through the left-hand UI toolbar.
"""
self._timeline.play()
def _on_run_scenario_b_text(self):
"""
This function is attached to the Run Scenario StateButton.
This function was passed in as the on_b_click_fn argument.
It is called when the StateButton is clicked while saying a_text "STOP"
Pausing the timeline on b_text is not strictly necessary for this example to run.
Clicking "STOP" will cancel the physics subscription that updates the scenario, which means that
the robot will stop getting new commands and the cube will stop updating without needing to
pause at all. The reason that the timeline is paused here is to prevent the robot being carried
forward by momentum for a few frames after the physics subscription is canceled. Pausing here makes
this example prettier, but if curious, the user should observe what happens when this line is removed.
"""
self._timeline.pause()
def _reset_extension(self):
"""This is called when the user opens a new stage from self.on_stage_event().
All state should be reset.
"""
self._on_init()
self._reset_ui()
def _reset_ui(self):
self._scenario_state_btn.reset()
self._scenario_state_btn.enabled = False
self._reset_btn.enabled = False
| 12,816 | Python | 44.130282 | 138 | 0.63686 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/omni_isaac_dish_washer_manipulator_python/README.md | # Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template extension creates a Load, Reset, and Run button in a simple UI.
The Load and Reset buttons interact with the omni.isaac.core World() in order
to simplify user interaction with the simulator and provide certain gurantees to the user
at the times their callback functions are called.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
scenario.py:
This file contains an implementation of an example "Scenario" that implements a "teardown", "setup", and "update" function.
This particular structure was chosen to make a clear code separation between UI management and the scenario logic. In this way, the
ExampleScenario() class serves as a simple backend to the UI. The user should feel encouraged to implement the backend to their UI
that best suits their needs.
| 2,078 | Markdown | 58.399998 | 137 | 0.783927 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/docs/CHANGELOG.md | # Changelog
## [0.1.0] - 2024-05-28
### Added
- Initial version of omni.isaac.dish.washer.manipulator Extension
| 115 | Markdown | 13.499998 | 65 | 0.695652 |
elsayedelsheikh/dishwaher/omni.isaac.dish.washer.manipulator/docs/README.md | # Usage
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
| 129 | Markdown | 24.999995 | 118 | 0.736434 |
NVIDIA-Omniverse/kit-extension-sample-scatter/README.md | # Scatter Kit Extension Sample
## [Scatter Tool (omni.example.ui_scatter_tool)](exts/omni.example.ui_scatter_tool)

### About
This Extension uses `Scatter Properties` to scatter a selected primitive on the X, Y, and Z Axis per object count, distance, and randomization set by the user.
### [README](exts/omni.example.ui_scatter_tool)
See the [README for this extension](exts/omni.example.ui_scatter_tool) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scatter_tool/Tutorial/Scatter_Tool_Guide.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
In the tutorial you will learn how to build upon modules provided to you to create the `Scatter Window UI` and the `Scatter Properties`.
[Get started with the tutorial.](exts/omni.example.ui_scatter_tool/Tutorial/Scatter_Tool_Guide.md)
## Adding This Extension
To add this extension to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter?branch=main&dir=exts`
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app code
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,109 | Markdown | 37.363636 | 193 | 0.760076 |
NVIDIA-Omniverse/kit-extension-sample-scatter/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
NVIDIA-Omniverse/kit-extension-sample-scatter/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
NVIDIA-Omniverse/kit-extension-sample-scatter/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/Tutorial/Scatter_Tool_Guide.md | 
# How to Create a Scatter Tool
In this tutorial, you learn how to create a scatter tool that can randomize prims around the world space. You create a tool that can scatter on X, Y, and Z axes by the amount of objects, their distance, and their random count. This tutorial is well suited for intermediate engineers.
## Learning Objectives
- Use the Omniverse UI framework
- Add an Extension from your local path
- Set scatter properties
- Analyze a random number generator
- Use the USD API to set up a PointInstancer
- Understand the `undo` function
## Prerequisites
Before you begin, install [Omniverse Code](https://docs.omniverse.nvidia.com/app_code/app_code/overview.html) version 2022.1.2 or higher.
We recommend that you understand the concepts in the following tutorials before proceeding:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [Spawn Prims Extension Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
## Step 1: Install the Starter Project Extension
In this section, you download our sample Extension project and install it in Omniverse Code.
### Step 1.1: Download the Scatter Project
Clone the `tutorial-start` branch of the `kit-extension-sample-scatter` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter/tree/tutorial-start):
```bash
git clone -b tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter.git
```
This repository contains the assets you use in this tutorial.
### Step 1.2: Open the Extensions Tab
In Omniverse Code, click the _Extensions_ tab:

> **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**:
>
> 
### Step 1.3: Add the Extension From Your Local Path
In the *Extensions* tab, click the **gear** icon to open *Extension Search Paths*. Then, click the **green plus** icon to add a new path. Finally, copy and paste the local path of the `exts` folder from the `tutorial-start` branch:

Here, you imported the extension into the *Extension Manager* in Omniverse Code by adding the local path of the `tutorial-start` branch you cloned from our [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter/tree/tutorial-start).
### Step 1.4: Activate Your New Extension
Type "scatter" into the search box at the top of the *Extensions* list, and activate the `OMNI.UI WINDOW SCATTER` Extension:

Now that your Extension is imported and active, you can make changes to the code and see them in your Application.
## Step 2: Implement `_build_source()`
This tutorial starts with a blank *Scatter Window*. In the following steps, you learn to use [Omniverse UI Framework](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html) to build the window's user interface (UI).
### Step 2.1: Navigate to `window.py`
From the root directory of the project, navigate to `exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/window.py`.
### Step 2.2: Create a Collapsable Frame
Create a [`CollapsableFrame`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.CollapsableFrame) in `_build_source()` as the first component of your UI:
```python
def _build_source(self):
"""Build the widgets of the "Source" group"""
# Create frame
with ui.CollapsableFrame("Source", name="group"):
```
`_build_source()` creates a place to display the source path of the prim you want to scatter. Here, you added a `CollapsableFrame`, which is a frame widget from Omniverse UI Framework that can hide or show its content.
### Step 2.3: Lay Out Your Frame
Use a [`VStack`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.VStack) to create a column and an [`HStack`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.HStack) to create a row:
```python
def _build_source(self):
"""Build the widgets of the "Source" group"""
# Create frame
with ui.CollapsableFrame("Source", name="group"):
# Create column
with ui.VStack(height=0, spacing=SPACING):
# Create row
with ui.HStack():
```
The `VStack` is a vertical stack container that holds one `HStack`, a horizontal stack container.
### Step 2.4: Create and Name an Input Field
Create a [`Label`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Label) and a [`StringField`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.StringField):
```python
def _build_source(self):
"""Build the widgets of the "Source" group"""
# Create frame
with ui.CollapsableFrame("Source", name="group"):
# Create column
with ui.VStack(height=0, spacing=SPACING):
# Create row
with ui.HStack():
# Give name of field
ui.Label("Prim", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model)
```
The `StringField` is an input field that accepts the prim. The `Label`, called "Prim", describes the field to your users.
### Step 2.5: Populate Your Field
Add a [`Button`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Button) that takes the user's current selection and populates the `StringField`:
```python
def _build_source(self):
"""Build the widgets of the "Source" group"""
# Create frame
with ui.CollapsableFrame("Source", name="group"):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
# Give name of field
ui.Label("Prim", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model)
# Button that puts the selection to the string field
ui.Button(
" S ",
width=0,
height=0,
style={"margin": 0},
clicked_fn=self._on_get_selection,
tooltip="Get From Selection",
)
```
This `Button`, labeled "S", places the prim selection in the `StringField`.
## Step 3: Implement `_build_scatter()`
Now that you've built functionality that selects a source prim to scatter, you need to implement `_build_scatter()`.
### Step 3.1: Create a Collapsable Frame
Start your `_build_scatter()` interface with a `CollapsableFrame`:
```python
def _build_scatter(self):
"""Build the widgets of the "Scatter" group"""
with ui.CollapsableFrame("Scatter", name="group"):
```
### Step 3.2: Lay Out Your Frame
Create one column with three rows, each with a `Label` and an input:
```python
def _build_scatter(self):
"""Build the widgets of the "Scatter" group"""
with ui.CollapsableFrame("Scatter", name="group"):
# Column
with ui.VStack(height=0, spacing=SPACING):
# Row
with ui.HStack():
ui.Label("Prim Path", name="attribute_name", width=self.label_width)
ui.StringField(model=self._scatter_prim_model)
# Row
with ui.HStack():
ui.Label("Prim Type", name="attribute_name", width=self.label_width)
ui.ComboBox(self._scatter_type_model)
# Row
with ui.HStack():
ui.Label("Seed", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000)
```
Like before, you've created a layout with `VStack` and `HStack`, but this time, your column includes three rows. Each row has a `Label` and an input. The first row is labeled "Prim Path" and accepts a string. The second row is labeled "Prim Type" and accepts a [`ComboBox`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ComboBox) selection. The third row is labeled "Seed" and accepts the result of an [integer drag widget](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.IntDrag).
## Step 4: Implement `_build_axis()`
Implement the `_build_axis()` UI to set the scatter parameters on the X, Y, and Z axes.
### Step 4.1: Lay Out Your Frame
In `_build_axis()`, establish a structure similar to `_build_scatter()`, with a Collapsable Frame, one column, and three rows:
```python
def _build_axis(self, axis_id, axis_name):
"""Build the widgets of the "X" or "Y" or "Z" group"""
with ui.CollapsableFrame(axis_name, name="group"):
# Column
with ui.VStack(height=0, spacing=SPACING):
# Row
with ui.HStack():
ui.Label("Object Count", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100)
# Row
with ui.HStack():
ui.Label("Distance", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000)
# Row
with ui.HStack():
ui.Label("Random", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000)
```
Like with `_build_scatter()`, each row has a `Label` and an input. This time, the first row is labeled "Object Count" and accepts the result of an integer drag widget. The second row is labeled "Distance" and accepts the results of a [`FloatDrag` widget](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.FloatDrag). The third row is labeled "Random" and also accepts the results of a `FloatDrag` widget.
Even though there are three axes on which you want to scatter your prim, you only need one function, since you can reuse it for each axis.
## Step 5: Implement `_build_fn()`
Now that you've established the user interface for the *Scatter Window* in a collection of functions, you implement `_build_fn()`, which calls those functions and draws their UIs to the screen.
### Step 5.1: Lay Out Your Frame
In `_build_fn()`, lay out a [`ScrollingFrame`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ScrollingFrame) with a single column composed of your previously-built UIs:
```python
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
# Frame
with ui.ScrollingFrame():
# Column
with ui.VStack(height=0):
# Build it
self._build_source()
self._build_scatter()
self._build_axis(0, "X Axis")
self._build_axis(1, "Y Axis")
self._build_axis(2, "Z Axis")
# The Go button
ui.Button("Scatter", clicked_fn=self._on_scatter)
```
Here, you used `ScrollingFrame` instead of `CollapsableFrame` so that the frame can scroll to accommodate all the UIs. In your `VStack`, you call all of your UI build functions in sequence to establish a visual hierarchy. You call `_build_axis()` three times with arguments that identify the axis it represents. Finally, you add a **Scatter** button that scatters the selected prim.
### Step 5.2: Review Your Work
In Omniverse Code, review your *Scatter Window*:

> **Note:** If you don't see your changes to the window, try deactivating and reactivating the Extension:
>
> 
## Step 6: Implement `_on_scatter()`
In this step, you implement`_on_scatter()`, which scatters the prim when the **Scatter** button is clicked.
### Step 6.1: Implement the Scatter Logic
Implement the logic to scatter the selected prims:
```python
def _on_scatter(self):
"""Called when the user presses the "Scatter" button"""
prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")]
if not prim_names:
prim_names = get_selection()
if not prim_names:
pass
transforms = scatter(
count=[m.as_int for m in self._scatter_count_models],
distance=[m.as_float for m in self._scatter_distance_models],
randomization=[m.as_float for m in self._scatter_random_models],
id_count=len(prim_names),
seed=self._scatter_seed_model.as_int,
)
duplicate_prims(
transforms=transforms,
prim_names=prim_names,
target_path=self._scatter_prim_model.as_string,
mode=self._scatter_type_model.get_current_item().as_string,
)
```
We defined `prim_names` in the sample code. You got the scatter properties from the models and passed them to `duplicate_prims()`, which scatters the prims for you.
> **Optional Challenge:** While we provide some arrays and loops for the properties, we encourage you to experiment with your own.
### Step 6.2: Review Your Work
In your *Scatter Window*, click `Scatter`:

Your prim scatters using the properties set above.
## Congratulations
Great job completing this tutorial! Interested in learning more about the ins and outs of the code? Continue reading.
### Further Reading: Understanding `scatter.py`
This section introduces `scatter.py` and briefly showcases its function in the scatter tool.
Navigate to `scatter.py` in your `exts` folder hierarchy. This script is where `on_scatter()` in `window.py` pulls its information from. Notice the following arguments in `scatter.py`:
```python
def scatter(
count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None
):
...
```
These arguments match up with the properties in `transforms` from the previous step of `on_scatter`.
The docstring below provides a description for each parameter:
```python
"""
Returns generator with pairs containing transform matrices and ids to
arrange multiple objects.
### Arguments:
`count: List[int]`
Number of matrices to generage per axis
`distance: List[float]`
The distance between objects per axis
`randomization: List[float]`
Random distance per axis
`id_count: int`
Count of differrent id
`seed: int`
If seed is omitted or None, the current system time is used. If seed
is an int, it is used directly.
""""
```
Below this comment is where the loop is initialized to randomly generated a sets of points as well as create a matrix with position randomization for each axis:
```python
# Initialize the random number generator.
random.seed(seed)
for i in range(count[0]):
x = (i - 0.5 * (count[0] - 1)) * distance[0]
for j in range(count[1]):
y = (j - 0.5 * (count[1] - 1)) * distance[1]
for k in range(count[2]):
z = (k - 0.5 * (count[2] - 1)) * distance[2]
# Create a matrix with position randomization
result = Gf.Matrix4d(1)
result.SetTranslate(
Gf.Vec3d(
x + random.random() * randomization[0],
y + random.random() * randomization[1],
z + random.random() * randomization[2],
)
)
id = int(random.random() * id_count)
yield (result, id)
```
`scatter.py` is where you can adjust to create different types of scatters, such as scatter on the geometry or a scatter that uses texture.
### Further Reading: Understanding `command.py`
This section introduces `command.py` and briefly showcases its function in the scatter tool.
Navigate to `command.py` in the `exts` folder, and review what's inside. At the start of the `ScatterCreatePointInstancerCommand` class, the docstring provides descriptions for each of the parameters:
```python
"""
Create PointInstancer undoable **Command**.
### Arguments:
`path_to: str`
The path for the new prims
`transforms: List`
Pairs containing transform matrices and ids to apply to new objects
`prim_names: List[str]`
Prims to duplicate
"""
```
Below the comment is where these arguments are initialized, sets the USD stage, and unzips the list of tuples:
```python
def __init__(
self,
path_to: str,
transforms: List[Tuple[Gf.Matrix4d, int]],
prim_names: List[str],
stage: Optional[Usd.Stage] = None,
context_name: Optional[str] = None,
):
omni.usd.commands.stage_helper.UsdStageHelper.__init__(self, stage, context_name)
self._path_to = path_to
# We have it like [(tr, id), (tr, id), ...]
# It will be transformaed to [[tr, tr, ...], [id, id, ...]]
unzipped = list(zip(*transforms))
self._positions = [m.ExtractTranslation() for m in unzipped[0]]
self._proto_indices = unzipped[1]
self._prim_names = prim_names.copy()
```
Following that, the `PointInstancer` command is set up. This where the USD API is used to create the geometry and create the points during scatter.
```python
def do(self):
stage = self._get_stage()
# Set up PointInstancer
instancer = UsdGeom.PointInstancer.Define(stage, Sdf.Path(self._path_to))
attr = instancer.CreatePrototypesRel()
for name in self._prim_names:
attr.AddTarget(Sdf.Path(name))
instancer.CreatePositionsAttr().Set(self._positions)
instancer.CreateProtoIndicesAttr().Set(self._proto_indices)
```
Finally, the `undo()` function is defined. This is called when the user undoes the scatter to restore the prior state of the stage. In this case, the state is restored by simply deleting the PointInstancer. The reason `delete_cmd.do()` is used rather than calling `omni.kit.commands.execute()` is so that the "DeletePrimsCommand" doesn't show up in the Commands History.
```python
def undo(self):
delete_cmd = omni.usd.commands.DeletePrimsCommand([self._path_to])
delete_cmd.do()
``` | 18,268 | Markdown | 38.888646 | 569 | 0.680315 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/Tutorial/Final Scripts/window.py | # Copyright (c) 2022, 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.
#
__all__ = ["ScatterWindow"]
import omni.ui as ui
from .style import scatter_window_style
from .utils import get_selection
from .combo_box_model import ComboBoxModel
from .scatter import scatter
from .utils import duplicate_prims
LABEL_WIDTH = 120
SPACING = 4
class ScatterWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Models
self._source_prim_model = ui.SimpleStringModel()
self._scatter_prim_model = ui.SimpleStringModel()
self._scatter_type_model = ComboBoxModel("Reference", "Copy", "PointInstancer")
self._scatter_seed_model = ui.SimpleIntModel()
self._scatter_count_models = [ui.SimpleIntModel(), ui.SimpleIntModel(), ui.SimpleIntModel()]
self._scatter_distance_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()]
self._scatter_random_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()]
# Defaults
self._scatter_prim_model.as_string = "/World/Scatter01"
self._scatter_count_models[0].as_int = 50
self._scatter_count_models[1].as_int = 1
self._scatter_count_models[2].as_int = 1
self._scatter_distance_models[0].as_float = 500
self._scatter_distance_models[1].as_float = 500
self._scatter_distance_models[2].as_float = 500
# Apply the style to all the widgets of this window
self.frame.style = scatter_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _on_get_selection(self):
"""Called when tthe user presses the "Get From Selection" button"""
self._source_prim_model.as_string = ", ".join(get_selection())
def _on_scatter(self):
"""Called when the user presses the "Scatter" button"""
prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")]
if not prim_names:
prim_names = get_selection()
if not prim_names:
pass
transforms = scatter(
count=[m.as_int for m in self._scatter_count_models],
distance=[m.as_float for m in self._scatter_distance_models],
randomization=[m.as_float for m in self._scatter_random_models],
id_count=len(prim_names),
seed=self._scatter_seed_model.as_int,
)
duplicate_prims(
transforms=transforms,
prim_names=prim_names,
target_path=self._scatter_prim_model.as_string,
mode=self._scatter_type_model.get_current_item().as_string,
)
def _build_source(self):
"""Build the widgets of the "Source" group"""
# Create frame
with ui.CollapsableFrame("Source", name="group"):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
# Give name of field
ui.Label("Prim", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model)
# Button that puts the selection to the string field
ui.Button(
" S ",
width=0,
height=0,
style={"margin": 0},
clicked_fn=self._on_get_selection,
tooltip="Get From Selection",
)
def _build_scatter(self):
"""Build the widgets of the "Scatter" group"""
with ui.CollapsableFrame("Scatter", name="group"):
# Column
with ui.VStack(height=0, spacing=SPACING):
# Row
with ui.HStack():
ui.Label("Prim Path", name="attribute_name", width=self.label_width)
ui.StringField(model=self._scatter_prim_model)
# Row
with ui.HStack():
ui.Label("Prim Type", name="attribute_name", width=self.label_width)
ui.ComboBox(self._scatter_type_model)
# Row
with ui.HStack():
ui.Label("Seed", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000)
def _build_axis(self, axis_id, axis_name):
"""Build the widgets of the "X" or "Y" or "Z" group"""
with ui.CollapsableFrame(axis_name, name="group"):
# Column
with ui.VStack(height=0, spacing=SPACING):
# Row
with ui.HStack():
ui.Label("Object Count", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100)
# Row
with ui.HStack():
ui.Label("Distance", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000)
# Row
with ui.HStack():
ui.Label("Random", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
# Frame
with ui.ScrollingFrame():
# Column
with ui.VStack(height=0):
# Build it
self._build_source()
self._build_scatter()
self._build_axis(0, "X Axis")
self._build_axis(1, "Y Axis")
self._build_axis(2, "Z Axis")
# The Go button
ui.Button("Scatter", clicked_fn=self._on_scatter)
| 6,835 | Python | 38.062857 | 109 | 0.571178 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/config/extension.toml | [package]
title = "omni.ui Window Scatter"
description = "The full end to end example of the window"
version = "1.0.1"
category = "Scatter"
authors = ["Victor Yudin"]
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows"
keywords = ["example", "window", "ui"]
changelog = "docs/CHANGELOG.md"
icon = "data/icon.png"
preview_image = "data/preview.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.example.ui_scatter_tool"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.core",
"omni.kit.renderer.capture",
]
| 717 | TOML | 22.16129 | 84 | 0.668061 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/style.py | # Copyright (c) 2022, 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.
#
__all__ = ["scatter_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.scatter_window_hovered = cl("#2b2e2e")
cl.scatter_window_text = cl("#9e9e9e")
fl.scatter_window_attr_hspacing = 10
fl.scatter_window_attr_spacing = 1
fl.scatter_window_group_spacing = 2
# The main style dict
scatter_window_style = {
"Label::attribute_name": {
"color": cl.scatter_window_text,
"margin_height": fl.scatter_window_attr_spacing,
"margin_width": fl.scatter_window_attr_hspacing,
},
"CollapsableFrame::group": {"margin_height": fl.scatter_window_group_spacing},
"CollapsableFrame::group:hovered": {"secondary_color": cl.scatter_window_hovered},
}
| 1,408 | Python | 35.128204 | 89 | 0.740767 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/commands.py | # Copyright (c) 2022, 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.
#
__all__ = ["ScatterCreatePointInstancerCommand"]
from pxr import Gf
from pxr import Sdf
from pxr import Usd
from pxr import UsdGeom
from typing import List
from typing import Optional
from typing import Tuple
import omni.kit.commands
import omni.usd.commands
class ScatterCreatePointInstancerCommand(omni.kit.commands.Command, omni.usd.commands.stage_helper.UsdStageHelper):
"""
Create PointInstancer undoable **Command**.
### Arguments:
`path_to: str`
The path for the new prims
`transforms: List`
Pairs containing transform matrices and ids to apply to new objects
`prim_names: List[str]`
Prims to duplicate
"""
def __init__(
self,
path_to: str,
transforms: List[Tuple[Gf.Matrix4d, int]],
prim_names: List[str],
stage: Optional[Usd.Stage] = None,
context_name: Optional[str] = None,
):
omni.usd.commands.stage_helper.UsdStageHelper.__init__(self, stage, context_name)
self._path_to = path_to
# We have it like [(tr, id), (tr, id), ...]
# It will be transformaed to [[tr, tr, ...], [id, id, ...]]
unzipped = list(zip(*transforms))
self._positions = [m.ExtractTranslation() for m in unzipped[0]]
self._proto_indices = unzipped[1]
self._prim_names = prim_names.copy()
def do(self):
stage = self._get_stage()
# Set up PointInstancer
instancer = UsdGeom.PointInstancer.Define(stage, Sdf.Path(self._path_to))
attr = instancer.CreatePrototypesRel()
for name in self._prim_names:
attr.AddTarget(Sdf.Path(name))
instancer.CreatePositionsAttr().Set(self._positions)
instancer.CreateProtoIndicesAttr().Set(self._proto_indices)
def undo(self):
delete_cmd = omni.usd.commands.DeletePrimsCommand([self._path_to])
delete_cmd.do()
| 2,346 | Python | 32.056338 | 115 | 0.663257 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/extension.py | # Copyright (c) 2022, 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.
#
__all__ = ["ScatterWindowExtension"]
from .window import ScatterWindow
from functools import partial
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
class ScatterWindowExtension(omni.ext.IExt):
"""The entry point for Scatter Window"""
WINDOW_NAME = "Scatter Window"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
ScatterWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(ScatterWindowExtension.WINDOW_NAME)
def on_shutdown(self):
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(ScatterWindowExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
if value:
self._window = ScatterWindow(ScatterWindowExtension.WINDOW_NAME, width=300, height=500)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
| 2,849 | Python | 36.012987 | 108 | 0.662338 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/scatter.py | # Copyright (c) 2022, 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.
#
__all__ = ["scatter"]
from typing import List, Optional
import random
from pxr import Gf
def scatter(
count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None
):
"""
Returns generator with pairs containing transform matrices and ids to
arrange multiple objects.
### Arguments:
`count: List[int]`
Number of matrices to generage per axis
`distance: List[float]`
The distance between objects per axis
`randomization: List[float]`
Random distance per axis
`id_count: int`
Count of differrent id
`seed: int`
If seed is omitted or None, the current system time is used. If seed
is an int, it is used directly.
"""
# Initialize the random number generator.
random.seed(seed)
for i in range(count[0]):
x = (i - 0.5 * (count[0] - 1)) * distance[0]
for j in range(count[1]):
y = (j - 0.5 * (count[1] - 1)) * distance[1]
for k in range(count[2]):
z = (k - 0.5 * (count[2] - 1)) * distance[2]
# Create a matrix with position randomization
result = Gf.Matrix4d(1)
result.SetTranslate(
Gf.Vec3d(
x + random.random() * randomization[0],
y + random.random() * randomization[1],
z + random.random() * randomization[2],
)
)
id = int(random.random() * id_count)
yield (result, id)
| 2,076 | Python | 30 | 118 | 0.577553 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/__init__.py | # Copyright (c) 2018-2020, 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.
#
__all__ = ["ScatterCreatePointInstancerCommand", "ScatterWindowExtension", "ScatterWindow"]
from .commands import ScatterCreatePointInstancerCommand
from .extension import ScatterWindowExtension
from .window import ScatterWindow
| 663 | Python | 46.428568 | 91 | 0.820513 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/combo_box_model.py | # Copyright (c) 2022, 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.
#
__all__ = ["ComboBoxModel"]
from typing import Optional
import omni.ui as ui
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
@property
def as_string(self):
"""Return the string of the name model"""
return self.name_model.as_string
class ComboBoxModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ComboBoxModel(*string_list)
ui.ComboBox(model)
"""
def __init__(self, *args, default=0):
super().__init__()
self._children = [ListItem(t) for t in args]
self._default = ui.SimpleIntModel()
self._default.as_int = default
# Update the combo box when default is changed
self._default.add_value_changed_fn(lambda _: self._item_changed(None))
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item: Optional[ListItem], column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
if item is None:
return self._default
return item.name_model
def get_current_item(self) -> ListItem:
"""Returns the currently selected item in ComboBox"""
return self._children[self._default.as_int]
| 2,391 | Python | 30.893333 | 82 | 0.637808 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/utils.py | # Copyright (c) 2022, 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.
#
__all__ = ["get_selection", "duplicate_prims"]
from typing import List
import omni.usd
import omni.kit.commands
from pxr import Sdf
def get_selection() -> List[str]:
"""Get the list of currently selected prims"""
return omni.usd.get_context().get_selection().get_selected_prim_paths()
def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy"):
"""
Returns generator with pairs containing transform matrices and ids to
arrange multiple objects.
### Arguments:
`transforms: List`
Pairs containing transform matrices and ids to apply to new objects
`prim_names: List[str]`
Prims to duplicate
`target_path: str`
The parent for the new prims
`mode: str`
"Reference": Create a reference of the given prim path
"Copy": Create a copy of the given prim path
"PointInstancer": Create a PointInstancer
"""
if mode == "PointInstancer":
omni.kit.commands.execute(
"ScatterCreatePointInstancer",
path_to=target_path,
transforms=transforms,
prim_names=prim_names,
)
return
usd_context = omni.usd.get_context()
# Call commands in a single undo group. So the user will undo everything
# with a single press of ctrl-z
with omni.kit.undo.group():
# Create a group
omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Scope")
for i, matrix in enumerate(transforms):
id = matrix[1]
matrix = matrix[0]
path_from = Sdf.Path(prim_names[id])
path_to = Sdf.Path(target_path).AppendChild(f"{path_from.name}{i}")
# Create a new prim
if mode == "Copy":
omni.kit.commands.execute("CopyPrims", paths_from=[path_from.pathString], paths_to=[path_to.pathString])
elif mode == "Reference":
omni.kit.commands.execute(
"CreateReference", usd_context=usd_context, prim_path=path_from, path_to=path_to, asset_path=""
)
else:
continue
# Move
omni.kit.commands.execute("TransformPrim", path=path_to, new_transform_matrix=matrix)
| 2,762 | Python | 33.5375 | 120 | 0.627806 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/window.py | # Copyright (c) 2022, 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.
#
__all__ = ["ScatterWindow"]
import omni.ui as ui
from .style import scatter_window_style
from .utils import get_selection
from .combo_box_model import ComboBoxModel
from .scatter import scatter
from .utils import duplicate_prims
LABEL_WIDTH = 120
SPACING = 4
class ScatterWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Models
self._source_prim_model = ui.SimpleStringModel()
self._scatter_prim_model = ui.SimpleStringModel()
self._scatter_type_model = ComboBoxModel("Reference", "Copy", "PointInstancer")
self._scatter_seed_model = ui.SimpleIntModel()
self._scatter_count_models = [ui.SimpleIntModel(), ui.SimpleIntModel(), ui.SimpleIntModel()]
self._scatter_distance_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()]
self._scatter_random_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()]
# Defaults
self._scatter_prim_model.as_string = "/World/Scatter01"
self._scatter_count_models[0].as_int = 50
self._scatter_count_models[1].as_int = 1
self._scatter_count_models[2].as_int = 1
self._scatter_distance_models[0].as_float = 500
self._scatter_distance_models[1].as_float = 500
self._scatter_distance_models[2].as_float = 500
# Apply the style to all the widgets of this window
self.frame.style = scatter_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _on_get_selection(self):
"""Called when tthe user presses the "Get From Selection" button"""
self._source_prim_model.as_string = ", ".join(get_selection())
def _on_scatter(self):
"""Called when the user presses the "Scatter" button"""
prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")]
if not prim_names:
prim_names = get_selection()
if not prim_names:
# TODO: "Can't clone" message
pass
transforms = scatter(
count=[m.as_int for m in self._scatter_count_models],
distance=[m.as_float for m in self._scatter_distance_models],
randomization=[m.as_float for m in self._scatter_random_models],
id_count=len(prim_names),
seed=self._scatter_seed_model.as_int,
)
duplicate_prims(
transforms=transforms,
prim_names=prim_names,
target_path=self._scatter_prim_model.as_string,
mode=self._scatter_type_model.get_current_item().as_string,
)
def _build_source(self):
"""Build the widgets of the "Source" group"""
with ui.CollapsableFrame("Source", name="group"):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Prim", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model)
# Button that puts the selection to the string field
ui.Button(
" S ",
width=0,
height=0,
style={"margin": 0},
clicked_fn=self._on_get_selection,
tooltip="Get From Selection",
)
def _build_scatter(self):
"""Build the widgets of the "Scatter" group"""
with ui.CollapsableFrame("Scatter", name="group"):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Prim Path", name="attribute_name", width=self.label_width)
ui.StringField(model=self._scatter_prim_model)
with ui.HStack():
ui.Label("Prim Type", name="attribute_name", width=self.label_width)
ui.ComboBox(self._scatter_type_model)
with ui.HStack():
ui.Label("Seed", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000)
def _build_axis(self, axis_id, axis_name):
"""Build the widgets of the "X" or "Y" or "Z" group"""
with ui.CollapsableFrame(axis_name, name="group"):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Object Count", name="attribute_name", width=self.label_width)
ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100)
with ui.HStack():
ui.Label("Distance", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000)
with ui.HStack():
ui.Label("Random", name="attribute_name", width=self.label_width)
ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_source()
self._build_scatter()
self._build_axis(0, "X Axis")
self._build_axis(1, "Y Axis")
self._build_axis(2, "Z Axis")
# The Go button
ui.Button("Scatter", clicked_fn=self._on_scatter)
| 6,573 | Python | 39.580247 | 109 | 0.585729 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/tests/__init__.py | # Copyright (c) 2022, 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 .test_window import TestWindow | 463 | Python | 50.55555 | 76 | 0.812095 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/omni/example/ui_scatter_tool/tests/test_window.py | # Copyright (c) 2022, 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.
#
__all__ = ["TestWindow"]
from omni.example.ui_scatter_tool import ScatterWindow
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.test
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestWindow(OmniUiTest):
async def test_general(self):
"""Testing general look of section"""
window = ScatterWindow("Test")
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=550,
)
# Wait for images
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
| 1,344 | Python | 34.394736 | 115 | 0.706101 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/docs/CHANGELOG.md | # Changelog
## [1.0.0] - 2022-06-27
### Added
- Initial window
| 64 | Markdown | 9.833332 | 23 | 0.59375 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/docs/README.md | # Scatter Tool (omni.example.ui_scatter_tool)

## Overview
This Extension creates a new UI and function to `Scatter` a selected primitive along the X, Y, and Z Axis. The user can set parameters for Objecct Count, Distance, and Randomization.
## [Tutorial](../Tutorial/Scatter_Tool_Guide.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
In the tutorial you will learn how to build off exisitng modules using `Omniverse Ui Framework` and create `Scatter Properties`. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along.
[Get started with the tutorial.](../Tutorial/Scatter_Tool_Guide.md)
## Usage
Once the extension is enabled in the `Extension Manager` the `Scatter Window` will appear. You may dock this window or keep it floating in the console. Select your primitive in the hierarchy that you want to scatter and then click the `S` button next to the `Source > Prim` pathway to set the selected primitive. Then, set your `Scatter Properties` and click the `Scatter` button. | 1,259 | Markdown | 65.315786 | 380 | 0.77363 |
NVIDIA-Omniverse/kit-extension-sample-scatter/exts/omni.example.ui_scatter_tool/docs/index.rst | omni.example.ui_scatter_tool
########################################
Scatter of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 159 | reStructuredText | 12.333332 | 40 | 0.522013 |
NVIDIA-Omniverse/sample-ackermann-amr/pyproject.toml | [tool.poetry]
name = "sample-ackermann-amr"
version = "0.1.0"
description = ""
authors = ["Your Name <[email protected]>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.10"
torch = "^2.3.0"
torchvision = "^0.18.0"
pynput = "^1.7.6"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
| 332 | TOML | 17.499999 | 41 | 0.659639 |
NVIDIA-Omniverse/sample-ackermann-amr/README.md | # ackermann AMR Sample
This repository includes a working sample (source code and assets) that can be used to train an AI model to steer an ackermann AMR through a scene.
### README
See the README files for this to learn more about it, including how to use it:
* [ackermann AMR Controller](exts/omni.sample.ackermann_amr_controller/docs/README.md)
* [ackermann AMR Trainer](exts/omni.sample.ackermann_amr_trainer/docs/README.md)
* [ROS Packages](ros_packages/f1_tenth_trainer/docs/README.md)
## Tutorial
Follow the [step-by-step tutorial](/tutorial/tutorial.md) to learn how to train a self-driving car.
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions. | 728 | Markdown | 39.499998 | 147 | 0.777473 |
NVIDIA-Omniverse/sample-ackermann-amr/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
NVIDIA-Omniverse/sample-ackermann-amr/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
NVIDIA-Omniverse/sample-ackermann-amr/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
NVIDIA-Omniverse/sample-ackermann-amr/tutorial/tutorial.md | # Train an ackermann Autonomous Mobile Robot to drive Itself with NVIDIA Omniverse and ROS
Follow along with this tutorial to learn how to use a combination of CAD templates, NVIDIA Omniverse Extensions, and Robot Operating System (ROS) to build and train your own virtual ackermann autonomous mobile robot (AMR).
## Learning Objectives
* Learn the entire workflow to take an Autonomous Mobile Robot (AMR) from concept to reality
* See a USD pipeline in action
* Create a USD scene to train an AMR
* Use Robot Operating System (ROS) 2 to manually control an AMR
* Write an Omniverse extension to train an AMR
* Create ROS 2 nodes to autonomously control the robot
## Prerequisites
* Ubuntu 22.04
* Isaac Sim 2023.1.1 or higher
* ROS 2 Humble
* Clone this Repository
* Install ROS dependencies. (This can be done by running `prerequisites.sh` in the repository's `ros2_f1_tenth_trainer` folder)
## 1 From Concept to Simulation
An ackermann AMR is an autonomous mobile robot that steers and drives like a car. It has four wheels, two or four-wheel drive, and the two front wheels steer. In this tutorial you will be shown an end-to-end workflow that can be used to train a 1/10 scale remote control car to drive itself in a virtual environment.
### 1.1 The Ackermann AMR Onshape Template
The first step to develop a real-world AMR is to model one in CAD.
#### 1.1.1 Open the OnShape ackermann AMR Template
Open the OnShape <a href="https://cad.onshape.com/documents/836767cd08a2800e8a9d4cb0/w/91eb0ff38b3ab8b03ea0db77/e/9015511e4d7c44d4d48e3cf2?renderMode=0&uiState=65bd4308b58f851a1d4b4096" target="_blank">ackermann AMR template</a>
<figure style="text-align: center;">
<img src="Images/OnShapeTemplate.png" alt="ackermann AMR Template" width="800"/>
<figcaption>Onshape Ackermann AMR Template</figcaption>
</figure>
The ackermann AMR template makes this easy; if you wanted to customize the template, you would just enter your car's measurements into the parameter table and then import the model into Omniverse. If you are working with the a traxxas slash-based vehicle such as the F1Tenth platform you do not need to change anything because it already matches your suspension geometry!
### 1.2 The ackermann AMR Template USD Pipeline
The Ackermann AMR template has been imported directly into Omniverse with the OnShape Importer extension. The resulting USD file has geometry and basic joint definitions, but is far from ready to simulate. This section demonstrates a powerful USD pipeline that will automatically prepare an imported ackerman AMR template model for simulation.
#### 1.2.1 Open Isaac Sim
Open Isaac Sim, making sure that under `ROS Bridge Extension`, `omni.isaac.ros2_bridge` is selected.
<figure style="text-align: center;">
<img src="Images/Launch_Isaac.gif" alt="Launch Isaac Sim" width="800"/>
<figcaption>Launch Isaac Sim</figcaption>
</figure>
#### 1.2.2 Open the Fully Rigged Vehicle
Go to the content browser tab at the bottom of the screen and enter `/home/nvidia/source/sample-ackermann-amr/assets/` into its address bar where *nvidia* should be replaced with your logged in username. This will open a folder with a number of useful assets for this tutorial. Double click on the *F1Tenth.usd* file to open it.
<figure style="text-align: center;">
<img src="Images/Open_F1Tenth.gif" alt="Open F1Tenth.usd" width="800"/>
<figcaption>Open F1Tenth.usd</figcaption>
</figure>
#### 1.2.3 Simulate the Vehicle
Press the `play` button to see the car simulate. `Shift+click` on the car and then drag the mouse to interact with it during simulation. Press the `stop` button to reset the simulation. Take note that the simulation behaves well and that there are no warnings or errors.
<figure style="text-align: center;">
<img src="Images/F1Tenth_Simulation.gif" alt="Simulate F1Tenth.usd" width="800"/>
<figcaption>Simulate the Working Vehicle</figcaption>
</figure>
> **_NOTE_**: If at any time you edit this asset, it may not work properly. If your edits show up as deltas in the `Root Layer` in the Layer pane, this layer is intentionally left empty for this very reason; you can delete any deltas in that layer. If that doesn't work, just re-open `F1Tenth.usd` and do not save your changes. Accidently saved your changes? Check out the appendix at the end to see how to reset your files.
#### 1.2.4 Mute All Layers
Open the Layer tab and mute each layer by clicking on the `eye` icon until the car disapears completely.
<figure style="text-align: center;">
<img src="Images/Mute_Layers.gif" alt="Mute All Layers in F1Tenth.usd" width="800"/>
<figcaption>Mute All Layers in F1Tenth.usd</figcaption>
</figure>
USD Layers do not simply serve for organization; they work more like macros! Layers have a list of changes, or deltas, that are made to the USD stage tree. In this case, we import the CAD template and then these layers automatically prepare it for simulation.
> **_NOTE_**: Roughly speaking, any prim attributes values (opinions) in a layer take precedence over layers below them. For more detailed information on the prioritization of layer opinions (LIVRPS), please read the [USD Documentation](https://openusd.org/release/glossary.html#livrps-strength-ordering)
#### 1.2.5 Unmute Full_Car_base.usd
Unmute `Full_Car_base.usd` by clicking on its `eye` icon to make the car appear.
Select `Full_Car_base.usd` and press the `F` key to fit the robot to the screen.
<figure style="text-align: center;">
<img src="Images/Unmute_Full_Car_Base.gif" alt="Unmute Full_Car_Base.usd" width="800"/>
<figcaption>Unmute Full_Car_Base.usd</figcaption>
</figure>
This layer is created by the OnShape import and is the base of the asset. Press the `play` button to start a simulation, you will notice that the car simply falls, has incorrect joint rigging and quite a few errors. Press the `stop` button to reset the simulation.
#### 1.2.6 Unmute Reparenting.usd, Mass_Properties.usd and Joint_Rigging.usd fff
Unmute `Reparenting.usd`, `Mass_Properties.usd`, and `Joint_Rigging.usd`.
Expand `Joint_Rigging.usd`, select `World` → `Full_Car` and press the `F` key to fit the ackermann robot to the screen.
<figure style="text-align: center;">
<img src="Images/Unmute_Three.gif" alt="Unmute the Next Three Layers" width="800"/>
<figcaption>Unmute the Next Three Layers</figcaption>
</figure>
These layers rearrange the stage tree, apply correct mass properties and fix a number of issues with the joints.
#### 1.2.7 Simulate Robot
Press `play` now; the car should once again simulate well and without errors.
<figure style="text-align: center;">
<img src="Images/Bounce.gif" alt="Simulate Vehicle with Rigged Joints" width="800"/>
<figcaption>Simulate the Vehicle with Rigged Joints</figcaption>
</figure>
#### 1.2.8 Unmute Remaining Layers
Unmute `Materials.usd`, `Cameras.usd`, and `Make_Asset.usd`.
<figure style="text-align: center;">
<img src="Images/Unmute_Remaining.gif" alt="Unmute Remaining Layers" width="800"/>
<figcaption>Unmute Remaining Layers</figcaption>
</figure>
If you replace `Full_Car_Base.usd` with a new CAD import, these layers will make the same changes to that version of the template, giving you an asset that is ready to drive around a scene.
### 1.3 Add a ROS Isaac Sim bridge Action Graph to the F1Tenth Car
Next we will add two Robot Operating System (ROS) action graphs to the `F1Tenth` asset so that it can send images to and be controlled by ROS.
#### 1.3.1 Add `ROS_Actiongraph.usd` to the Pipeline
Drag `ROS_Actiongraph.usd` from the content browser and drop it into the **Layer** window, making sure it is above all other sub-layers.
<figure style="text-align: center;">
<img src="Images/Add_ActionGraphs.gif" alt="Add ROS Action Graphs to the Scene" width="800"/>
<figcaption>Add ROS Action Graphs to the Scene</figcaption>
</figure>
#### 1.3.2 See the Changes to the Scene
Navigate to the stage tree to see the two action graph nodes that have been added to the scene.
<figure style="text-align: center;">
<img src="Images/Added_ActionGraphs.gif" alt="View Added Action Graphs in the Stage Tree" width="800"/>
<figcaption>View Added Action Graphs in the Stage Tree</figcaption>
</figure>
This layer behaves as a macro that adds the two action graphs to the stage tree under the *Full_Car* prim. The `ROS_Sensors` graph publishes the cameras and sensors from the template for other ROS nodes to subscribe to. The `ROS_Ackermann_Drive` graph listens for ROS nodes that send driving commands so that it can be controlled by other ROS nodes.
> **_NOTE_**: You can open `F1Tenth_ROS.usd` to catch up to this point.
### 1.4 Create a USD Scene of a Race Track
Now that the car is ready for physics simulation, we will create a scene with a race track and add the car to it.
#### 1.4.1 `Open Raceing_Grid_Start.usd`
Find `Racing_Grid_Start.usd` in the content browser and double click it to open it.
<figure style="text-align: center;">
<img src="Images/Open_Racing_Grid_Start.gif" alt="Open Racing_Grid_Start.usd" width="800"/>
<figcaption>Open Racing_Grid_Start.usd</figcaption>
</figure>
#### 1.4.2 Add the `F1Tenth_ROS.usd` to the scene
To add the car to the scene, drag the `F1Tenth_ROS.usd` asset from the content browser and drop it into the stage tree window.
<figure style="text-align: center;">
<img src="Images/Add_Car.gif" alt="Add the Car to the Scene" width="800"/>
<figcaption>Add the Car to the Scene</figcaption>
</figure>
#### 1.4.3 Rotate the Robot 90 degrees
Click on the `F1Tenth_ROS` prim in the stage tree and in the properties pane, set it's `Z` rotation to `-90`.
<figure style="text-align: center;">
<img src="Images/Rotate_Car.gif" alt="Rotate the Car -90 degrees about the Z-axis" width="800"/>
<figcaption>Rotate the Car -90 degrees about the Z-axis</figcaption>
</figure>
#### 1.4.4 Simulate the Robot
You can press `play` to start the physics simulation. Press `stop` to reset the simulation. Please keep in mind that the car will not roll during simulation because the wheels are locked until they receive a ROS message.
<figure style="text-align: center;">
<img src="Images/Car_Simulation.gif" alt="Simulate the Car in the Scene" width="800"/>
<figcaption>Simulate the Car in the Scene</figcaption>
</figure>
> **_NOTE_**: To catch up to this point, open `Racing_Grid.usd` in the content browser.
### 1.5 Write a ROS 2 Node to Manually Control the Robot
Next we will write a ROS 2 node in python that can manually control the robot.
> **_NOTE_**: If you are new to python, the indentation of your code is critical! Your code will not work correctly if it is not indented correctly because the indentation defines the scope. The Comment for each line of code you will insert is indented correctly, so if you copy-paste the code from this tutorial, align it with the matching comments in the source files, and double check the indentation is the same there as it is in this tutorial, your indentation should be correct.
#### 1.5.1 Open the `sample-ackermann-amr` Folder in Visual Studio Code
In a terminal run the following commands to change to the sample-ackermann-amr directory and open it in Visual Studio Code:
```bash
cd ~/source/sample-ackermann-amr/
code .code
```
<figure style="text-align: center;">
<img src="Images/Open_VSCode.gif" alt="Launch VS Code" width="800"/>
<figcaption>Launch VS Code</figcaption>
</figure>
#### 1.5.2 Open *teleop_ackermann_key_start*
Next, open *teleop_ackermann_key_start.py* found in *ros2_f1_tenth_trainer*.
<figure style="text-align: center;">
<img src="Images/Open_Teleop.gif" alt="Open teleop_ackermann_key_start.py" width="800"/>
<figcaption>Open <em>teleop_ackermann_key_start.py</em></figcaption>
</figure>
This ROS Node uses `pynput` to access keyboard events. It detects whether a key has been pressed and then sends that as a message from a ROS node for other ROS nodes to list and respond to.
#### 1.5.3 Respond to Key Presses
Second, in the `on_press` function, add the following code:
```python
# 1.5.3 Create ROS Messages based on keys pressed
if key.char == 'w':
self.drive_msg.drive.speed = 2.0 # Drive Forward
elif key.char == 's':
self.drive_msg.drive.speed = -2.0 # Drive Backward
elif key.char == 'a':
self.drive_msg.drive.steering_angle = 0.523599 # Turn left by 30 degrees
elif key.char == 'd':
self.drive_msg.drive.steering_angle = -0.523599 # Turn right by 30 degrees
```
This code responds to `wasd` key presses by steering and driving the car.
<details>
<summary>Completed Code</summary>
```Python
def __init__(self):
super().__init__('keyboard_teleop')
# 1. Create the publisher and message
self.publisher_ = self.create_publisher(AckermannDriveStamped, 'ackermann_cmd', 10)
self.drive_msg = AckermannDriveStamped()
self.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
self.listener.start()
self.timer_period = 0.1 # seconds
self.timer = self.create_timer(self.timer_period, self.publish_cmd)
def on_press(self, key):
try:
# 2. Create ROS Messages based on keys pressed
if key.char == 'w':
self.drive_msg.drive.speed = 2.0 # Drive Forward
elif key.char == 's':
self.drive_msg.drive.speed = -2.0 # Drive Backward
elif key.char == 'a':
self.drive_msg.drive.steering_angle = 0.523599 # Turn left by 30 degrees
elif key.char == 'd':
self.drive_msg.drive.steering_angle = -0.523599 # Turn right by 30 degrees
except AttributeError:
pass
def on_release(self, key):
try:
# 3. If no keys are pressed, stop the car
if key.char in ['w', 's']:
self.drive_msg.drive.speed = 0.0 # stop driving
elif key.char in ['a', 'd']:
self.drive_msg.drive.steering_angle = 0.0 # stop turning
except AttributeError:
pass
def publish_cmd(self):
# 4. Publish the Message
self.drive_msg.header.frame_id = "f1_tenth"
self.drive_msg.header.stamp = self.get_clock().now().to_msg()
self.publisher_.publish(self.drive_msg)
```
</details>
#### 1.5.4 Start the ROS Node
To run the ROS2 node, open a terminal and run the following command:
```bash
cd ~/source/sample-ackermann-amr/ros2_f1_tenth_trainer
```
Then launch the ROS2 node with this command:
```bash
python3 teleop_ackermann_key_start.py
```
If you are having trouble, run the completed code instead:
```bash
python3 teleop_ackermann_key.py
```
#### 1.5.5 Change to the Chase Camera
Click on the camera icon on the upper left of the viewport and change to `Cameras` → `camera_chase`.
<figure style="text-align: center;">
<img src="Images/Chase_Camera.gif" alt="Change to the chase camera" width="800"/>
<figcaption>Change to the chase camera</em></figcaption>
</figure>
#### 1.5.6 Start the Omniverse Simulation
Open Omniverse and click the `play` button or press the `spacebar` to start the physics simulation.
<figure style="text-align: center;">
<img src="Images/1_5_6_Start_Simulation.gif" alt="Start the simulation" width="800"/>
<figcaption>Start the simulation</em></figcaption>
</figure>
#### 1.5.7 Drive the Car in the Scene
Drive the car in the scene with the `wasd` keys.
<figure style="text-align: center;">
<img src="Images/1_5_7_Drive_Car.gif" alt="Drive the car with the WASD keys" width="800"/>
<figcaption>Drive the car with the WASD keys</em></figcaption>
</figure>
Be careful, if you have a text-entry window or element selected such as the terminal or text box, it will capture your key presses.
> **_NOTE_**: Is the car slipping and sliding when you drive it? This material should be applied to any ground planes when you add this asset to a scene or else the friction will only be half what you expect!
#### 1.5.8 Stop the Simulation
Stop and reset the simulation by clicking the `stop` button or by pressing the `spacebar`.
<figure style="text-align: center;">
<img src="Images/1_5_8_Stop_Simulation.gif" alt="Stop the simulation" width="800"/>
<figcaption>Stop the simulation</em></figcaption>
</figure>
#### 1.5.9 Stop the ROS Node
Stop the ROS node by selecting its terminal and pressing `ctrl + c`.
> **_CHALLENGE_**: Remember, `teleop_ackermann_key.py` will be used to drive the car as you collect annotated data for AI model training. With that in mind, how might you change how the robot is controlled to make it easier to collect data?
## 2 Write an Omniverse Extension to Train the Driving Model
Now that we can perform a physics simulation of the robot navigating an environment, the next step is to collect annotated data and train a model that can drive the car autonomously.
### 2.1 The Ackermann Trainer Extension User Interface
In this section we will create the Ackermann Trainer Extension's graphical user interface.
#### 2.1.1 Training Workflow Overview
In order to train a computer-vision based supervised-learning AI for an AMR we need to take the following steps:
* Capture images from the robot's camera.
* Annotate the images with data we would like the model to predict
* Train a model from the dataset
* Validate whether the model is trained well enough
* Save the model so we can use it to actually drive our autonomous robot!
Here is the user interface that guides a user through that workflow:
<figure style="text-align: center;">
<img src="Images/Trainer_UI.png" alt="The Ackermann Trainer Window User Interface" width="600"/>
<figcaption>The Ackermann Trainer Window User Interface</figcaption>
</figure>
The controls of the window are as follows.
1. The `Capture` button captures the current viewport, saves a copy and displays it in the user interface.
2. The captured viewport is displayed here.
3. Clicking on a captured image annotates the image with the coordinates you have clicked.
4. `Count` displays the number of annotated images in your currently loaded dataset.
5. The `Train` button trains the model for one epoch
6. The `Evaluate` starts repeatedly capturing the current viewport and evaluating it with your current model.
7. With each iteration of `Evaluate`, the predicted point appears as a green dot. Clicking the `Evaluate` button again will stop evaluation.
8. The `Model Path` attribute determines the file name your model will load from and save to.
9. The `Load Model` button loads the model.
10. The `Save Model` buttons saves the model.
#### 2.1.2 Capture the Viewport to File
Next we will write the code for most of these UI elements. In VS Code, navigate to *exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer*, open `ackermann_trainer_window_start.py`, and find the `capture_image` function. Enter the following snippet which captures the viewport to file:
```python
# 2.1.2 Capture the Viewport to File
viewport = get_active_viewport()
capture_viewport_to_file(viewport, file_path=file_path)
```
When you click on the `Capture` button, it calls the `OnCapture` function. `OnCapture` calls `capture_image` asynchrounously which in turn calls `replace_image`.
#### 2.1.3 Update the UI Thumbnail Image
In the `replace_image` function, paste `self.file_name` into the `ui.Image()` constructor as shown below:
```python
# 2.1.3 Update the image from the capture
ui.Image(self.file_path)
```
The `replace_image` function redraws the thumbnail image and its annotations.
#### 2.1.4 Add Annotation to Dataset
The image displayed in the user interface is clickable and fires the `onMouseReleased` function when clicked. Add the following code to capture the click coordinates and add the image with its annotation to the model's dataset.
```python
# 2.1.4 Capture Click Position
self.click_x, self.click_y = canvas.screen_to_canvas(x, y)
# 2.1.4 Add Image to Dataset
self.file_path = self.model.add_item(self.click_y,
self.click_x,
self.file_path)
```
> **_NOTE_**: The `add_item` function is a member of `ackermann_amr_model`, which will be discussed in section 2.2.
#### 2.1.5 Update the Image Annotation
Next we return to `replace_image` where we set the `x` and `y` positions of the red annotation dot. This is done by adding `self.click_x` and `self.click_y` to the spacers above and to the left of the red dot:
```python
# 2.1.5 Set Annotation Y-Position
ui.Spacer()
with ui.HStack(height=self.click_y):
# 2.1.5 Set Annotation Z-Position
ui.Spacer(width=self.click_x)
style = {"Circle": {"background_color": cl("#cc0000"),
"border_color": cl("#cc0000"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.
Alignment.LEFT_TOP,
style=style)
```
This places the red dot where the user clicked.
#### 2.1.6 Train the Model
Next, inside the `train` function, add the following code to train the model:
```python
# 2.1.6 Train AI Model
self.model.train()
```
This function will train the model for one epoch each time it is run.
> **_NOTE_**: The model and its training function will be discussed in section 2.2
#### 2.1.7 Evaluating the Model
Add the viewport capture code to `on_update`:
```python
# 2.1.7 Capture the Viewport to Buffer
viewport_api = get_active_viewport()
capture_viewport_to_buffer(viewport_api, self.on_viewport_captured)
```
This captures the viewport to a buffer and then calls `on_viewport_captured`. Add the following to `on_viewport_captured` to evaluate the given viewport capture:
```python
# 2.1.7 Evaluate Viewport Image
self.prediction_y, self.prediction_x = self.model.Evaluate(buffer,
buffer_size,
width,
height,
self.thumbnail_width,
self.thumbnail_height)
```
> **_NOTE_**: The `Evaluate` function is in `ackermann_amr_model`, which will be discussed in section 2.2.
The evaluate model functionality in this extension can be toggled on and off with a toggle-button. While on, the extension will send the current viewport through the AI model every 30 frames and will annotate the window's thumbnail with the predicted coordinates continuously. While toggled off, no evaluations are made.
#### 2.1.8 Load and Save Model
The final step in the workflow is to load and save the model with the following functions which are tied to the callbacks from the `load` and `save` buttons:
```python
# 2.1.8 Load the Model
def onLoadModel(self):
self.model.load(self.model_path_model.as_string)
# 2.1.8 Save the Model
def onSaveModel(self):
self.model.save(self.model_path_model.as_string)
```
<details>
<summary>Completed Code</summary>
```python
def __init__(self, *args, **kwargs):
self.file_path = ""
self.click_x = 0
self.click_y = 0
self.prediction_x = 0
self.prediction_y = 0
self.thumbnail_height = 300
self.thumbnail_width = 600
# Configure Directory Where Data Will Be Saved
self.save_dir = tempfile.gettempdir()
self.save_dir = os.path.join(self.save_dir, 'road_following')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
self.save_dir = os.path.join(self.save_dir, 'apex')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
# Initialize AI Model
self.model = ackermann_amr_model(self.thumbnail_height,
self.thumbnail_width,
self.save_dir)
self.update_stream = omni.kit.app.get_app().get_update_event_stream()
self.frame_update_count = 0
self.ov_update = None
self.build_ui()
# Capture Image
def onCapture(self):
# Get Filename
filename = '%s.png' % (str(uuid.uuid1()))
self.file_path = os.path.join(self.save_dir, filename)
# Request Image Capture Asynchronously
asyncio.ensure_future(self.capture_image(self.replace_image,
self.file_path))
# Capture the Viewport to File
async def capture_image(self, on_complete_fn: callable, file_path) -> str:
# 2.1.2 Capture the Viewport to File
viewport = get_active_viewport()
capture_viewport_to_file(viewport, file_path=file_path)
# Wait for the Capture to Complete
if on_complete_fn:
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Update the User Interface
on_complete_fn()
# Thumbnail Clicked Callback
def onMouseReleased(self, x, y, button, modifier, canvas):
# 2.1.4 Capture Click Position
self.click_x, self.click_y = canvas.screen_to_canvas(x, y)
# 2.1.4 Add Image to Dataset
self.file_path = self.model.add_item(self.click_y,
self.click_x,
self.file_path)
# Update Image Annotation
self.replace_image()
# Update Count
self.count_model.set_value(str(len(self.model.dataset)))
# Replace the Thumbnail with the latest image
def replace_image(self):
counter = 0
while not os.path.exists(self.file_path) and counter < 10:
time.sleep(0.1)
counter += 1
with self.ClickableCanvas:
with ui.ZStack():
# 2.1.3 Update the image from the capture
ui.Image(self.file_path)
with ui.VStack():
# 2.1.5 Set Annotation Y-Position
ui.Spacer()
with ui.HStack():
# 2.1.5 Set Annotation Z-Position
ui.Spacer(width=self.click_x)
style = {"Circle": {"background_color": cl("#cc0000"),
"border_color": cl("#cc0000"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.
Alignment.LEFT_TOP,
style=style)
# Add Prediction Dot
with ui.VStack():
ui.Spacer(height=self.prediction_y)
with ui.HStack():
ui.Spacer(width=self.prediction_x)
style = {"Circle": {"background_color": cl("#00cc00"),
"border_color": cl("#00cc00"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.Alignment.LEFT_TOP,
style=style)
# Train the AI Model
def train(self):
self.train_button.enabled = False
# 2.1.6 Train AI Model
self.model.train()
self.train_button.enabled = True
carb.log_info("Training Complete")
# Turn Evaluation On and Off
def toggle_eval(self, model):
# Toggle Evaluation On and Off
if self.eval_model.get_value_as_bool():
self.ov_update = self.update_stream.create_subscription_to_pop(
self.on_update,
name="Eval_Subscription")
else:
self.ov_update.unsubscribe()
# Omniverse Update Callback
def on_update(self, e: carb.events.IEvent):
# Capture the Viewport Every 30 Frames
self.frame_update_count += 1
if self.frame_update_count % 30 == 0:
self.frame_update_count = 1
# 2.1.7 Capture the Viewport to Buffer
viewport_api = get_active_viewport()
capture_viewport_to_buffer(viewport_api, self.on_viewport_captured)
# Evaluate the Viewport with the AI Model
def on_viewport_captured(self, buffer, buffer_size, width, height, format):
# 2.1.7 Evaluate Viewport Image
self.prediction_y, self.prediction_x = self.model.Evaluate(buffer,
buffer_size,
width,
height,
self.thumbnail_width,
self.thumbnail_height)
self.replace_image()
# 2.1.8 Load Model
def onLoadModel(self):
self.model.load(self.model_path_model.as_string)
# 2.1.8 Save Model
def onSaveModel(self):
self.model.save(self.model_path_model.as_string)
# Build the UI
def build_ui(self):
# Build UI
self._window = ui.Window("Ackermann AMR Trainer", width=600, height=500)
with self._window.frame:
with ui.ScrollingFrame():
with ui.VStack():
ui.Spacer(height=40)
# Capture Image
with ui.HStack(height=self.thumbnail_height):
with ui.HStack():
ui.Spacer()
self.ClickableCanvas = ui.CanvasFrame(
draggable=False,
width=self.thumbnail_width,
height=self.thumbnail_height)
self.ClickableCanvas.set_mouse_released_fn(
lambda x, y, b, m, c=self.ClickableCanvas:
self.onMouseReleased(x, y, b, m, c))
ui.Spacer()
# Capture Button
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"Capture",
clicked_fn=lambda: self.onCapture(),
style={"margin": 5},
height=30,
width=self.thumbnail_width)
ui.Spacer()
# Count Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'Count: ',
style={"margin": 5},
width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.count_model = ui.SimpleStringModel(
str(len(self.model.dataset)))
ui.StringField(
self.count_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Train and Eval Buttons
with ui.HStack(height=40):
ui.Spacer()
self.train_button = ui.Button(
"Train",
clicked_fn=lambda: self.train(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_button = ui.ToolButton(
text="Evaluate",
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_model = self.eval_button.model
self.eval_model.add_value_changed_fn(
lambda m: self.toggle_eval(m))
ui.Spacer()
# Model File Path Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'model path: ',
style={"margin": 5},
height=30, width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.model_path_model = ui.SimpleStringModel(
'road_following_model.pth')
ui.StringField(
self.model_path_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Model Load and Save Buttons
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"load model",
clicked_fn=lambda: self.onLoadModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Button(
"save model",
clicked_fn=lambda: self.onSaveModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
ui.Spacer()
```
</details>
### 2.2 The Pytorch Model used to Train and Drive the AMR
With a clear user interface that allows the user to navigate the training workflow, the next step in the extension development is to implement an AI model with its training and evaluation functions.
#### 2.2.1 Open `ackermann_amr_policy_start.py`
Open `ackermann_amr_policy_start.py` in the `exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer`folder. This class defines the nature of the AI model. In this case we are using a very typical fully-connected model based off of resnet18. If you would like to learn more detail on how neural networks work; I highly reccomend the Deep Learning Institute's [*Getting Started With Deep Learning*](https://courses.nvidia.com/courses/course-v1:DLI+S-FX-01+V1/). Here are the main components of the AI policy:
1. Its base model
2. How the layers are connected
3. How the nodes are activated
4. How the images are processed
5. How forward propogation is performed
#### 2.2.2 Add Image Processing Transform
To preprocess the images add the following code to `ackermann_amr_policy.__init__(self)`:
```python
# 2.3.2 Image Processing Transform
self.transform = transforms.Compose([transforms.ColorJitter(0.2,
0.2,
0.2,
0.2),
transforms.Resize((224,
224)),
transforms.Normalize([0.485,
0.456,
0.406],
[0.229,
0.224,
0.225])])
```
This code modifies the images' brightness, contrast, saturation and hue to improve training. It also resizes the images and normalizes the image data.
<details>
<summary>Completed Code</summary>
```python
def __init__(self):
super().__init__()
# Initialize Base Model
full_model = resnet18(weights=ResNet18_Weights.DEFAULT)
# Configure Layer Connections
self.model = nn.Sequential(*list(full_model.children())[:-1])
self.fc = nn.Linear(512, 2)
# Node Activation Function
self.sigma = nn.Tanh()
# 6.3.2 Image Processing Transform
self.transform = transforms.Compose([transforms.ColorJitter(0.2,
0.2,
0.2,
0.2),
transforms.Resize((224,
224)),
transforms.Normalize([0.485,
0.456,
0.406],
[0.229,
0.224,
0.225])])
```
</details>
#### 2.2.3 Open `ackermann_amr_data_start`
Open `ackermann_amr_data_start.py`. This class stores the annotated images and makes them available to the model.
#### 2.2.4 Prepend the Annotation to the Image
Look in the `Add_Item` function, and insert this code to add the coordinates to the beginning of a clicked image as it is added to the dataset:
```python
# 2.2.4 Prepend file name with x and y coordinates for later loading
file_name = Path(file_path).stem
file_directory = os.path.dirname(file_path)
file_name = '%d_%d_%s.png' % (col, row, file_name)
full_path = os.path.join(file_directory, file_name)
os.rename(file_path, full_path)
file_path = full_path
return full_path
```
This is how the annotations are associated with the images so that it can read in the dataset when you reload the extension.
<details>
<summary>Completed Code</summary>
```python
# Adding an image to the dataset
def Add_Item(self, row, col, width, height, file_path):
# Read the image from file
image = torchvision.io.read_image(file_path)
# Save the image raw data
self._raw_images.append((image[:-1]/255).float().unsqueeze(0))
# Convert from `click` coordinates to image coordinates
x, y = self.rowcol2xy(row, col, height, width)
# Process and save click annotation
col_ratio = float(col/width)
row_ratio = float(row/height)
self._raw_click.append([row, col])
self._raw_ratio.append([row_ratio, col_ratio])
self._raw_coords.append([x, y])
# Convert data to pytorch-compatible values
self._click_tensor = torch.from_numpy(
np.array(self._raw_click)).float().to(self.device)
self._ratio_tensor = torch.from_numpy(
np.array(self._raw_ratio)).float().to(self.device)
self._coords_tensor = torch.from_numpy(
np.array(self._raw_coords)).float().to(self.device)
self._image_tensor = torch.cat(self._raw_images, dim=0).to(self.device)
self._total_length = self._image_tensor.shape[0]
# 2.2.4 Prepend file name with x and y coordinates for later loading
file_name = Path(file_path).stem
file_directory = os.path.dirname(file_path)
file_name = '%d_%d_%s.png' % (col, row, file_name)
full_path = os.path.join(file_directory, file_name)
os.rename(file_path, full_path)
file_path = full_path
return full_path
```
</details>
#### 2.2.5 Open `ackermann_amr_model_start`
Finally, `ackermann_amr_model` trains and evaluates an AI model that can drive an AMR.
#### 2.2.6 Load Training Data in the `train` function
Add the following code to the `train` function to load the annotated data set:
```python
# 2.2.6 Load Training Data
loader = DataLoader(self.dataset, batch_size=10, shuffle=True)
```
Now that the data is loaded, the training loop will train the model correctly.
#### 2.2.7 Load Viewport Capture to GPU
Add the following code to the `evaluate` function to convert the captured viewport buffer to an image compatible with pytorch and add it to the GPU:
```python
# 2.2.7 Load the viewport capture from buffer and add it to the GPU
img = PIL.Image.frombuffer('RGBA',
(source_width, source_height),
content.contents)
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
```
Your model is now complete.
<details>
<summary>Completed Code</summary>
```python
# Train Model
def train(self):
time.sleep(0.1)
mse = torch.nn.MSELoss(reduction='mean')
optimizer = optim.Adam(self.model.parameters(),
lr=1E-4,
weight_decay=1E-5)
# 2.2.6 Load Training Data
loader = DataLoader(self.dataset, batch_size=10, shuffle=True)
self.model.train()
temp_losses = []
for images, coords in loader:
prediction = self.model(images)
optimizer.zero_grad()
loss = mse(prediction, coords)
loss.backward()
optimizer.step()
temp_losses.append(loss.detach().item())
print(np.mean(temp_losses))
# Evaluate Model
def Evaluate(self,
buffer,
buffer_size,
source_width,
source_height,
dest_width,
dest_height):
try:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(
ctypes.c_byte * buffer_size)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object,
ctypes.c_char_p]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
except Exception as e:
carb.log_error(f"Failed to capture viewport: {e}")
return
# Evaluate Model
self.model.eval()
# 2.2.7 Load the viewport capture from buffer and add it to the GPU
img = PIL.Image.frombuffer('RGBA',
(source_width, source_height),
content.contents)
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
rows = dest_height
cols = dest_width
self.prediction_y, self.prediction_x = self.dataset.xy2rowcol(
*prediction.squeeze().cpu(),
num_rows=rows, num_cols=cols)
carb.log_info(
"prediction made: %.1f %.1f" % (
self.prediction_x, self.prediction_y))
return [self.prediction_y, self.prediction_x]
```
</details>
The extension is now complete.
### 2.3 Collect Data
Now that the extension is complete, you can use it to collect a dataset of annotated images.
#### 2.3.1 Start the ROS Node
To enable control of the car, open a terminal and run the following commands:
```bash
cd ~/source/sample-ackermann-amr/ros2_f1_tenth_trainer
python3 teleop_ackermann_key.py
```
#### 2.3.2 Change to the Left Camera
Open Omniverse and click on the camera icon on the upper left of the viewport and change to `Cameras` → `Camera_Left`
<figure style="text-align: center;">
<img src="Images/Left_Camera.gif" alt="Change to the chase camera" width="600"/>
<figcaption>Change to the chase camera</figcaption>
</figure>
#### 2.3.3 Start the Omniverse Simulation
Click the `play` button or press the `spacebar` to start the physics simulation.
<figure style="text-align: center;">
<img src="Images/1_5_6_Start_Simulation.gif" alt="Start the simulation" width="600"/>
<figcaption>Start the simulation</figcaption>
</figure>
#### 2.3.4 Drive the Car in the Scene
Drive the car in the scene with that `WASD` keys.
<figure style="text-align: center;">
<img src="Images/1_5_7_Drive_Car.gif" alt="Drive the car around the track" width="600"/>
<figcaption>Drive the car around the track</figcaption>
</figure>
#### 2.3.5 Capture One Image
Capture an Image by clicking the `Capture` button in the `Ackermann AMR Trainer`.
<figure style="text-align: center;">
<img src="Images/Capture.gif" alt="Capture one image" width="600"/>
<figcaption>Capture one image_</figcaption>
</figure>
This will capture the viewport and save it to a temporary directory.
#### 2.3.4 Annotate One Image
Click on the point on the image the car should drive towards.
<figure style="text-align: center;">
<img src="Images/Annotate_Image.gif" alt="Annotate one image" width="600"/>
<figcaption>Annotate one image</figcaption>
</figure>
This will add the coordinates you clicked to the image as an annotation.
#### 2.3.4 Train the Model
Click on the `Train` button to train the model for one epoch.
<figure style="text-align: center;">
<img src="Images/Train_Model.gif" alt="Train the model for one epoch per click" width="600"/>
<figcaption>Train the model for one epoch per click</figcaption>
</figure>
The current model loss is printed to the console at the `information` level.
#### 2.3.5 Save the Model
Save the model by clicking the `save model` button in the `Ackermann AMR Trainer` extension.
#### 2.3.6 Toggle Evaluation On and off.
Click the `Evaluate` button to turn on model evaluation; click it again to turn off model evaluation.
<figure style="text-align: center;">
<img src="Images/Evaluate.gif" alt="Click the evaluate button to turn evaluation on and off" width="600"/>
<figcaption>Click the evaluate button to turn evaluation on and off</figcaption>
</figure>
> **_WARNING_**: This sends the viewport, not the extension thumbnail, through evaluation. If you drive the car during evaluation, the green dot will show the model prediction for the **Current** position of the car, not the position shown in the extension's thumbnail.
> **_Challenge_**: See if you can train a model that could control the robot. It does not have to be perfect, it just needs to generally predict more to the right or more to the left correctly depending on the car's position. An imperfect model can work well with the right controller code as will be demonstrated in the next section. Expect to build a dataset with about 400 annotated images and to train on that dataset for 5-10 epochs for a workable model. It is important as you are training to drive along the ideal and non-ideal paths to teach the robot both how to drive the ideal path as well as get back on track if it gets off course.
## 3 Create a ROS 2 Node to Automatically Control the Car
With a trained model that, in theory, can control the car, the next step is to deploy the model to a ROS node that actually controlls the robot.
### 3.1 Open `model_evaluate_start.py`
Open `ros2_f1_tenth_trainer/model_evaluate_start.py`. When this class is initialized it loads the model the user trained and saved. It then subscribes to viewport images published by Isaac Sim and uses those to predict where it think a user would click on that image. In this section we will respond to that prediction.
### 3.2 Compute Steering Angle
First, in `image_callback`, compute the raw steering angle from the predicted `x` and `y` values:
```python
# 3.2. Compute Steering Angle
forward = np.array([0.0, -1.0])
offset = np.array([0.0, 1.0])
traj = np.array([prediction_x.item(), prediction_y.item()]) - offset
unit_traj = traj / np.linalg.norm(traj)
unit_forward = forward / np.linalg.norm(forward)
steering_angle = np.arccos(np.dot(unit_traj, unit_forward)) / 2.0 - np.deg2rad(15.0)
```
Here we use the dot product of the forward vector and the vector from the bottom, center to the annotated point to find the steering angle.
<figure style="text-align: center;">
<img src="Images/Steering_Angle.png" alt="Steering Angle Schematic" width="600"/>
<figcaption>Steering Angle Schematic</figcaption>
</figure>
> **_Tip_** Notice that in the last line a few adjustments to the steering angle are made. the value is reduced by half and biased by fifteen degrees. These correction factors will be a key to your success in making this car drive faster! Because the track we trained with only has left-hand turns, the model is biased towards the left. We have introduced a reverse-bias to help the vehicle go stright and turn right when needed. You might be able to find a better bias value! Also, we found the car made large turns it sometimes could not recover from so we divided all angles by a scaling factor to help the car drive more smoothly. Once again, you may be able to find a better value for this correction factor.
### 3.3 Create and Send ROS Message
Second, we create and send a message through ROS with the following snippet:
```python
# 2. Create and Send Message
msg = AckermannDriveStamped()
msg.header.frame_id = "f1_tenth"
msg.header.stamp = self.get_clock().now().to_msg()
msg.drive.steering_angle = steering_angle
# Challenge: Increase the drive speed as much as you can!
msg.drive.speed = 2.0
self.publisher.publish(msg)
```
This code is very similar to the code used to steer the car with the keyboard. Rather than take keyboard input, however, we use model predictions to determine the steering and throttle values.
<details>
<summary>Completed Code</summary>
```Python
def image_callback(self, msg):
width = msg.width
height = msg.height
# Evaluate Model
self.model.eval()
img = PIL.Image.frombuffer('RGB', (width, height), msg.data.tobytes())
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
prediction_x, prediction_y = self.xy2rowcol(*prediction.squeeze().cpu())
# 1. Compute Steering Angle
forward = np.array([0.0, -1.0])
offset = np.array([0.0, 1.0])
traj = np.array([prediction_x.item(), prediction_y.item()]) - offset
import math
unit_traj = traj / np.linalg.norm(traj)
unit_forward = forward / np.linalg.norm(forward)
steering_angle = np.arccos(np.dot(unit_traj, unit_forward)) / 2.0 - np.deg2rad(15.0)
# 2. Create and Send Message
msg = AckermannDriveStamped()
msg.header.frame_id = "f1_tenth"
msg.header.stamp = self.get_clock().now().to_msg()
msg.drive.steering_angle = steering_angle
# Challenge: Increase the drive speed as much as you can!
msg.drive.speed = 2.0
self.publisher.publish(msg)
```
</details>
### 3.4 Run the Model
To run the model replace `road_following_model.pth` with a model you have trained and enter the following command from the `ros2_f1_tenth_trainer` directory and start the omniverse simulation.
```bash
python3 model_evaluate_start.py
```
> **_NOTE_**: Use the final code: `model_evalaute.py`, if needed.
#### 3.5 Start the Simulation
Open Omniverse and click the `play` icon or press the `spacebar` to start the simulation.
<figure style="text-align: center;">
<img src="Images/1_5_6_Start_Simulation.gif" alt="Start the simulation and watch the robot drive itself!" width="600"/>
<figcaption>Start the simulation and watch the robot drive itself!</figcaption>
</figure>
> **_Challenge_**: Increasing the drive speed will have a dramatic effect on your lap time. How much can you increase it? Could you make the drive speed variable instead of constant?
## Conclusions
Take a moment to reflect on what you have just done; you have taken an ackermann AMR from mere concept to driving around a virtual track under its own intelligence. You have done it with ROS so you can deploy this synthetically trained model to a real robot. Great job!
## Appendix: How to Revert Changes You Have Made to this Repository
If you have made a change to a file and now the project isn't working and you are not sure what to do; feel free to simply revert back to the original state of this repository.
Open your terminal and enter this command to navigate to the git repository:
```bash
cd ~/source/sample-ackermann-amr
```
To keep any new files you have added while reverting any files that came with the repository:
```bash
git reset
```
If you want to completely reset the repository to its original state use this command:
```bash
git clean
``` | 51,968 | Markdown | 39.888277 | 714 | 0.646436 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "ackermann AMR Trainer"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.sample.ackermann_amr_controller".
[[python.module]]
name = "omni.sample.ackermann_amr_trainer"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,616 | TOML | 32.687499 | 125 | 0.748144 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_model.py | # Copyright (c) 2020-2024, 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 .ackermann_amr_policy import ackermann_amr_policy
from .ackermann_amr_data import ackermann_amr_data
import time
import carb
import numpy as np
import torch
import PIL.Image
import ctypes
import os
from torch import optim
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
class ackermann_amr_model():
def __init__(self, rows, columns, image_directory):
self.device = torch.device('cuda')
self.model = ackermann_amr_policy()
self.model = self.model.to(self.device)
self.save_directory = image_directory
self.rows = rows
self.columns = columns
# Initialize Dataset
self.dataset = ackermann_amr_data([image_directory],
self.device,
self.columns,
self.rows)
# Add Item to Dataset
def add_item(self, click_y, click_x, file_path):
return self.dataset.Add_Item(click_y,
click_x,
self.columns,
self.rows,
file_path)
# Train Model
def train(self):
time.sleep(0.1)
mse = torch.nn.MSELoss(reduction='mean')
optimizer = optim.Adam(self.model.parameters(),
lr=1E-4,
weight_decay=1E-5)
# 2.2.6 Load Training Data
loader = DataLoader(self.dataset, batch_size=10, shuffle=True)
self.model.train()
temp_losses = []
for images, coords in loader:
prediction = self.model(images)
optimizer.zero_grad()
loss = mse(prediction, coords)
loss.backward()
optimizer.step()
temp_losses.append(loss.detach().item())
print(np.mean(temp_losses))
# Evaluate Model
def Evaluate(self,
buffer,
buffer_size,
source_width,
source_height,
dest_width,
dest_height):
try:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(
ctypes.c_byte * buffer_size)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object,
ctypes.c_char_p]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
except Exception as e:
carb.log_error(f"Failed to capture viewport: {e}")
return
# Evaluate Model
self.model.eval()
# 2.2.7 Load the viewport capture from buffer and add it to the GPU
img = PIL.Image.frombuffer('RGBA',
(source_width, source_height),
content.contents)
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
rows = dest_height
cols = dest_width
self.prediction_y, self.prediction_x = self.dataset.xy2rowcol(
*prediction.squeeze().cpu(),
num_rows=rows, num_cols=cols)
carb.log_info(
"prediction made: %.1f %.1f" % (
self.prediction_x, self.prediction_y))
return [self.prediction_y, self.prediction_x]
# Load Model
def load(self, model_name):
model_path = os.path.join(self.save_directory,
model_name)
self.model.load_state_dict(torch.load(model_path))
carb.log_warn("Model Loaded: {0}".format(model_path))
# Save Model
def save(self, model_name):
model_path = os.path.join(self.save_directory,
model_name)
torch.save(self.model.state_dict(), model_path)
carb.log_warn("Model Saved: {0}".format(model_path))
| 4,662 | Python | 34.325757 | 79 | 0.554269 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_trainer_window.py |
# Copyright (c) 2020-2024, 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 .ackermann_amr_model import ackermann_amr_model
import omni.ext
import omni.ui as ui
import carb.events
import os
import tempfile
import time
import omni.usd
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility import capture_viewport_to_file
from omni.kit.viewport.utility import capture_viewport_to_buffer
import omni.kit.app
import uuid
from omni.ui import color as cl
import asyncio
class ackermann_trainer_window(ui.Window):
def __init__(self, *args, **kwargs):
super(ackermann_trainer_window, self).__init__(*args, **kwargs)
self.file_path = ""
self.click_x = 0
self.click_y = 0
self.prediction_x = 0
self.prediction_y = 0
self.thumbnail_height = 300
self.thumbnail_width = 600
# Configure Directory Where Data Will Be Saved
self.save_dir = tempfile.gettempdir()
self.save_dir = os.path.join(self.save_dir, 'road_following')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
self.save_dir = os.path.join(self.save_dir, 'apex')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
# Initialize AI Model
self.model = ackermann_amr_model(self.thumbnail_height,
self.thumbnail_width,
self.save_dir)
self.update_stream = omni.kit.app.get_app().get_update_event_stream()
self.frame_update_count = 0
self.ov_update = None
self.build_ui()
# Capture Image
def onCapture(self):
# Get Filename
filename = '%s.png' % (str(uuid.uuid1()))
self.file_path = os.path.join(self.save_dir, filename)
# Request Image Capture Asynchronously
asyncio.ensure_future(self.capture_image(self.replace_image,
self.file_path))
# Capture the Viewport to File
async def capture_image(self, on_complete_fn: callable, file_path) -> str:
# 2.1.2 Capture the Viewport to File
viewport = get_active_viewport()
capture_viewport_to_file(viewport, file_path=file_path)
carb.log_warn("Image Captured: {file_path}")
# Wait for the Capture to Complete
if on_complete_fn:
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Update the User Interface
on_complete_fn()
# Thumbnail Clicked Callback
def onMouseReleased(self, x, y, button, modifier, canvas):
# 2.1.4 Capture Click Position
self.click_x, self.click_y = canvas.screen_to_canvas(x, y)
# 2.1.4 Add Image to Dataset
self.file_path = self.model.add_item(self.click_y,
self.click_x,
self.file_path)
carb.log_warn("Image Annotated: {self.file_path}")
# Update Image Annotation
self.replace_image()
# Update Count
self.count_model.set_value(str(len(self.model.dataset)))
# Replace the Thumbnail with the latest image
def replace_image(self):
counter = 0
while not os.path.exists(self.file_path) and counter < 10:
time.sleep(0.1)
counter += 1
with self.ClickableCanvas:
with ui.ZStack():
# 2.1.3 Update the image from the capture
ui.Image(self.file_path)
with ui.VStack():
# 2.1.5 Set Annotation Y-Position
ui.Spacer(height=self.click_y)
with ui.HStack():
# 2.1.5 Set Annotation Z-Position
ui.Spacer(width=self.click_x)
style = {"Circle": {"background_color": cl("#cc0000"),
"border_color": cl("#cc0000"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.
Alignment.LEFT_TOP,
style=style)
# Add Prediction Dot
with ui.VStack():
ui.Spacer(height=self.prediction_y)
with ui.HStack():
ui.Spacer(width=self.prediction_x)
style = {"Circle": {"background_color": cl("#00cc00"),
"border_color": cl("#00cc00"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.Alignment.LEFT_TOP,
style=style)
# Train the AI Model
def train(self):
self.train_button.enabled = False
# 2.1.6 Train AI Model
self.model.train()
self.train_button.enabled = True
carb.log_info("Training Complete")
# Turn Evaluation On and Off
def toggle_eval(self, model):
# Toggle Evaluation On and Off
if self.eval_model.get_value_as_bool():
self.ov_update = self.update_stream.create_subscription_to_pop(
self.on_update,
name="Eval_Subscription")
else:
self.ov_update.unsubscribe()
# Omniverse Update Callback
def on_update(self, e: carb.events.IEvent):
# Capture the Viewport Every 30 Frames
self.frame_update_count += 1
if self.frame_update_count % 30 == 0:
self.frame_update_count = 1
# 2.1.7 Capture the Viewport to Buffer
viewport_api = get_active_viewport()
capture_viewport_to_buffer(viewport_api, self.on_viewport_captured)
# Evaluate the Viewport with the AI Model
def on_viewport_captured(self, buffer, buffer_size, width, height, format):
# 2.1.7 Evaluate Viewport Image
self.prediction_y, self.prediction_x = self.model.Evaluate(buffer,
buffer_size,
width,
height,
self.thumbnail_width,
self.thumbnail_height)
self.replace_image()
# 2.1.8 Load Model
def onLoadModel(self):
self.model.load(self.model_path_model.as_string)
# 2.1.8 Save Model
def onSaveModel(self):
self.model.save(self.model_path_model.as_string)
# Build the UI
def build_ui(self):
# Build UI
with self.frame:
with ui.ScrollingFrame():
with ui.VStack():
ui.Spacer(height=40)
# Capture Image
with ui.HStack(height=self.thumbnail_height):
with ui.HStack():
ui.Spacer()
self.ClickableCanvas = ui.CanvasFrame(
draggable=False,
width=self.thumbnail_width,
height=self.thumbnail_height)
self.ClickableCanvas.set_mouse_released_fn(
lambda x, y, b, m, c=self.ClickableCanvas:
self.onMouseReleased(x, y, b, m, c))
ui.Spacer()
# Capture Button
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"Capture",
clicked_fn=lambda: self.onCapture(),
style={"margin": 5},
height=30,
width=self.thumbnail_width)
ui.Spacer()
# Count Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'Count: ',
style={"margin": 5},
width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.count_model = ui.SimpleStringModel(
str(len(self.model.dataset)))
ui.StringField(
self.count_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Train and Eval Buttons
with ui.HStack(height=40):
ui.Spacer()
self.train_button = ui.Button(
"Train",
clicked_fn=lambda: self.train(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_button = ui.ToolButton(
text="Evaluate",
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_model = self.eval_button.model
self.eval_model.add_value_changed_fn(
lambda m: self.toggle_eval(m))
ui.Spacer()
# Model File Path Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'model path: ',
style={"margin": 5},
height=30, width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.model_path_model = ui.SimpleStringModel(
'road_following_model.pth')
ui.StringField(
self.model_path_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Model Load and Save Buttons
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"load model",
clicked_fn=lambda: self.onLoadModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Button(
"save model",
clicked_fn=lambda: self.onSaveModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
ui.Spacer()
def destroy(self):
super().destroy()
if self.ov_update:
self.ackerman_trainer_window.ov_update.unsubscribe()
self.ov_update = None
| 12,045 | Python | 38.887417 | 89 | 0.464757 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_data.py | # Copyright (c) 2020-2024, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
import os
from pathlib import Path
class ackermann_amr_data(Dataset):
# Initializing the dataset
def __init__(self, root_paths, device, thumbnail_width, thumbnail_height):
super().__init__()
# Initialize variables
self.device = device
self._THUMB_ROWS = thumbnail_height
self._THUMB_COLS = thumbnail_width
self._raw_click = []
self._raw_ratio = []
self._raw_coords = []
self._raw_images = []
self._root_paths = root_paths
# Iterate through all pre-existing images
for i, path in enumerate(root_paths):
files = os.listdir(path)
for fname in files:
# Only process .png files
if fname.endswith(('.png')):
# Split out the x coord, y coord and UID of the image
stokens = fname.split("_")
# Only process images that have an x, y, and UID
if len(stokens) == 3:
# Read image from file
image = torchvision.io.read_image(
os.path.join(path, fname))
# Store raw image data for future use
self._raw_images.append(
(image[:-1]/255).float().unsqueeze(0))
# Get x coord
col = int(stokens[0])
# Get y coord
row = int(stokens[1])
# Convert from "click" coords to image coords
x, y = self.rowcol2xy(row,
col,
self._THUMB_ROWS,
self._THUMB_COLS)
# Determine Aspect Ratio
col_ratio = float(col/self._THUMB_COLS)
row_ratio = float(row/self._THUMB_ROWS)
# Save Raw Annotation for later use
self._raw_click.append([row, col])
self._raw_ratio.append([row_ratio, col_ratio])
self._raw_coords.append([x, y])
else:
# Delete any images that are not properly annotated
fpath = os.path.join(path, fname)
if os.path.isfile(fpath):
os.remove(fpath)
# Convert raw data to pytorch-compatible data
self._click_tensor = torch.from_numpy(
np.array(self._raw_click)).float().to(device)
self._ratio_tensor = torch.from_numpy(
np.array(self._raw_ratio)).float().to(device)
self._coords_tensor = torch.from_numpy(
np.array(self._raw_coords)).float().to(device)
# Compute dataset length
if len(self._raw_images) > 0:
self._image_tensor = torch.cat(self._raw_images, dim=0).to(device)
self._total_length = self._image_tensor.shape[0]
else:
self._total_length = 0
# Adding an image to the dataset
def Add_Item(self, row, col, width, height, file_path):
# Read the image from file
image = torchvision.io.read_image(file_path)
# Save the image raw data
self._raw_images.append((image[:-1]/255).float().unsqueeze(0))
# Convert from `click` coordinates to image coordinates
x, y = self.rowcol2xy(row, col, height, width)
# Process and save click annotation
col_ratio = float(col/width)
row_ratio = float(row/height)
self._raw_click.append([row, col])
self._raw_ratio.append([row_ratio, col_ratio])
self._raw_coords.append([x, y])
# Convert data to pytorch-compatible values
self._click_tensor = torch.from_numpy(
np.array(self._raw_click)).float().to(self.device)
self._ratio_tensor = torch.from_numpy(
np.array(self._raw_ratio)).float().to(self.device)
self._coords_tensor = torch.from_numpy(
np.array(self._raw_coords)).float().to(self.device)
self._image_tensor = torch.cat(self._raw_images, dim=0).to(self.device)
self._total_length = self._image_tensor.shape[0]
# 2.2.4 Prepend file name with x and y coordinates for later loading
file_name = Path(file_path).stem
file_directory = os.path.dirname(file_path)
file_name = '%d_%d_%s.png' % (col, row, file_name)
full_path = os.path.join(file_directory, file_name)
os.rename(file_path, full_path)
file_path = full_path
return full_path
# Get a single image from the dataset
def __getitem__(self, index):
img = self._image_tensor[index]
coords = self._coords_tensor[index]
return img, coords
# Find the number of images in the dataset
def __len__(self):
return self._total_length
# Convert from image to annotation coordinates
def rowcol2xy(self, row, col, num_rows=224, num_cols=224):
x = 2*col/num_cols - 1
y = 1 - 2*row/num_rows
return float(x), float(y)
# Convert from annotation to image coordinates
def xy2rowcol(self, x, y, num_rows=224, num_cols=224):
col = 0.5*num_cols*(1 + x)
row = 0.5*num_rows*(1 - y)
return int(row), int(col)
| 5,938 | Python | 38.85906 | 79 | 0.550185 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_policy_start.py | # Copyright (c) 2020-2024, 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 torch import nn
from torchvision import transforms
from torchvision.models import resnet18, ResNet18_Weights
class ackermann_amr_policy(nn.Module):
def __init__(self):
super().__init__()
# Initialize Base Model
full_model = resnet18(weights=ResNet18_Weights.DEFAULT)
# Configure Layer Connections
self.model = nn.Sequential(*list(full_model.children())[:-1])
self.fc = nn.Linear(512, 2)
# Node Activation Function
self.sigma = nn.Tanh()
# 2.3.2 Image Processing Transform
# Forward Propogation
def forward(self, x):
x = self.transform(x)
x = self.model(x)
x = x.view(x.size(0),-1)
x = self.sigma(self.fc(x))
return x
| 1,185 | Python | 31.054053 | 76 | 0.683544 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/extension.py | # Copyright (c) 2020-2024, 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 .ackermann_trainer_window import ackermann_trainer_window
import omni.ext
# omni.kit.pipapi extension is required
import omni.kit.pipapi
omni.kit.pipapi.install(
package="torch"
)
omni.kit.pipapi.install(
package='torchvision'
)
class AckermanAMRTrainerExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("Ackerman AMR Trainer Startup")
# Build UI
self._window = ackermann_trainer_window("Ackerman AMR Trainer",
width=600,
height=500)
def on_shutdown(self):
print("Ackerman AMR Trainer Shutdown")
if self._window:
self._window.destroy()
self._window = None
| 1,197 | Python | 28.949999 | 76 | 0.665831 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/utils.py | # Copyright (c) 2020-2024, 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 torch
import torchvision.transforms as transforms
import torch.nn.functional as F
import cv2
import PIL.Image
import numpy as np
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
def preprocess(image_path):
device = torch.device('cuda')
image = PIL.Image.open(image_path)
tensor_image = transforms.functional.to_tensor(image)
image = tensor_image[:3,...].to(device)
image.sub_(mean[:, None, None]).div_(std[:, None, None])
return image[None, ...]
| 961 | Python | 35.999999 | 76 | 0.740895 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_policy.py | # Copyright (c) 2020-2024, 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 torch import nn
from torchvision import transforms
from torchvision.models import resnet18, ResNet18_Weights
class ackermann_amr_policy(nn.Module):
def __init__(self):
super().__init__()
# Initialize Base Model
full_model = resnet18(weights=ResNet18_Weights.DEFAULT)
# Configure Layer Connections
self.model = nn.Sequential(*list(full_model.children())[:-1])
self.fc = nn.Linear(512, 2)
# Node Activation Function
self.sigma = nn.Tanh()
# 2.3.2 Image Processing Transform
self.transform = transforms.Compose([transforms.ColorJitter(0.2,
0.2,
0.2,
0.2),
transforms.Resize((224,
224)),
transforms.Normalize([0.485,
0.456,
0.406],
[0.229,
0.224,
0.225])])
# Forward Propogation
def forward(self, x):
x = self.transform(x)
x = self.model(x)
x = x.view(x.size(0),-1)
x = self.sigma(self.fc(x))
return x
| 2,066 | Python | 41.183673 | 76 | 0.452081 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_data_start.py | # Copyright (c) 2020-2024, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
import os
from pathlib import Path
class ackermann_amr_data(Dataset):
# Initializing the dataset
def __init__(self, root_paths, device, thumbnail_width, thumbnail_height):
super().__init__()
# Initialize variables
self.device = device
self._THUMB_ROWS = thumbnail_height
self._THUMB_COLS = thumbnail_width
self._raw_click = []
self._raw_ratio = []
self._raw_coords = []
self._raw_images = []
self._root_paths = root_paths
# Iterate through all pre-existing images
for i, path in enumerate(root_paths):
files = os.listdir(path)
for fname in files:
# Only process .png files
if fname.endswith(('.png')):
# Split out the x coord, y coord and UID of the image
stokens = fname.split("_")
# Only process images that have an x, y, and UID
if len(stokens) == 3:
# Read image from file
image = torchvision.io.read_image(
os.path.join(path, fname))
# Store raw image data for future use
self._raw_images.append(
(image[:-1]/255).float().unsqueeze(0))
# Get x coord
col = int(stokens[0])
# Get y coord
row = int(stokens[1])
# Convert from "click" coords to image coords
x, y = self.rowcol2xy(row,
col,
self._THUMB_ROWS,
self._THUMB_COLS)
# Determine Aspect Ratio
col_ratio = float(col/self._THUMB_COLS)
row_ratio = float(row/self._THUMB_ROWS)
# Save Raw Annotation for later use
self._raw_click.append([row, col])
self._raw_ratio.append([row_ratio, col_ratio])
self._raw_coords.append([x, y])
else:
# Delete any images that are not properly annotated
fpath = os.path.join(path, fname)
if os.path.isfile(fpath):
os.remove(fpath)
# Convert raw data to pytorch-compatible data
self._click_tensor = torch.from_numpy(
np.array(self._raw_click)).float().to(device)
self._ratio_tensor = torch.from_numpy(
np.array(self._raw_ratio)).float().to(device)
self._coords_tensor = torch.from_numpy(
np.array(self._raw_coords)).float().to(device)
# Compute dataset length
if len(self._raw_images) > 0:
self._image_tensor = torch.cat(self._raw_images, dim=0).to(device)
self._total_length = self._image_tensor.shape[0]
else:
self._total_length = 0
# Adding an image to the dataset
def Add_Item(self, row, col, width, height, file_path):
# Read the image from file
image = torchvision.io.read_image(file_path)
# Save the image raw data
self._raw_images.append((image[:-1]/255).float().unsqueeze(0))
# Convert from `click` coordinates to image coordinates
x, y = self.rowcol2xy(row, col, height, width)
# Process and save click annotation
col_ratio = float(col/width)
row_ratio = float(row/height)
self._raw_click.append([row, col])
self._raw_ratio.append([row_ratio, col_ratio])
self._raw_coords.append([x, y])
# Convert data to pytorch-compatible values
self._click_tensor = torch.from_numpy(
np.array(self._raw_click)).float().to(self.device)
self._ratio_tensor = torch.from_numpy(
np.array(self._raw_ratio)).float().to(self.device)
self._coords_tensor = torch.from_numpy(
np.array(self._raw_coords)).float().to(self.device)
self._image_tensor = torch.cat(self._raw_images, dim=0).to(self.device)
self._total_length = self._image_tensor.shape[0]
# 2.2.4 Prepend file name with x and y coordinates for later loading
# Get a single image from the dataset
def __getitem__(self, index):
img = self._image_tensor[index]
coords = self._coords_tensor[index]
return img, coords
# Find the number of images in the dataset
def __len__(self):
return self._total_length
# Convert from image to annotation coordinates
def rowcol2xy(self, row, col, num_rows=224, num_cols=224):
x = 2*col/num_cols - 1
y = 1 - 2*row/num_rows
return float(x), float(y)
# Convert from annotation to image coordinates
def xy2rowcol(self, x, y, num_rows=224, num_cols=224):
col = 0.5*num_cols*(1 + x)
row = 0.5*num_rows*(1 - y)
return int(row), int(col)
| 5,630 | Python | 38.93617 | 79 | 0.54849 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_amr_model_start.py | # Copyright (c) 2020-2024, 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 .ackermann_amr_policy import ackermann_amr_policy
from .ackermann_amr_data import ackermann_amr_data
import time
import carb
import numpy as np
import torch
import PIL.Image
import ctypes
import os
from torch import optim
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
class ackermann_amr_model():
def __init__(self, rows, columns, image_directory):
self.device = torch.device('cuda')
self.model = ackermann_amr_policy()
self.model = self.model.to(self.device)
self.save_directory = image_directory
self.rows = rows
self.columns = columns
# Initialize Dataset
self.dataset = ackermann_amr_data([image_directory],
self.device,
self.columns,
self.rows)
# Add Item to Dataset
def add_item(self, click_y, click_x, file_path):
return self.dataset.Add_Item(click_y,
click_x,
self.columns,
self.rows,
file_path)
# Train Model
def train(self):
time.sleep(0.1)
mse = torch.nn.MSELoss(reduction='mean')
optimizer = optim.Adam(self.model.parameters(),
lr=1E-4,
weight_decay=1E-5)
# 2.2.6 Load Training Data
self.model.train()
temp_losses = []
for images, coords in loader:
prediction = self.model(images)
optimizer.zero_grad()
loss = mse(prediction, coords)
loss.backward()
optimizer.step()
temp_losses.append(loss.detach().item())
print(np.mean(temp_losses))
# Evaluate Model
def Evaluate(self,
buffer,
buffer_size,
source_width,
source_height,
dest_width,
dest_height):
try:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(
ctypes.c_byte * buffer_size)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [
ctypes.py_object,
ctypes.c_char_p]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
except Exception as e:
carb.log_error(f"Failed to capture viewport: {e}")
return
# Evaluate Model
self.model.eval()
# 2.2.7 Load the viewport capture from buffer and add it to the GPU
img = PIL.Image.frombuffer('RGBA',
(source_width, source_height),
content.contents)
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
rows = dest_height
cols = dest_width
self.prediction_y, self.prediction_x = self.dataset.xy2rowcol(
*prediction.squeeze().cpu(),
num_rows=rows, num_cols=cols)
carb.log_info(
"prediction made: %.1f %.1f" % (
self.prediction_x, self.prediction_y))
return [self.prediction_y, self.prediction_x]
# Load Model
def load(self, model_name):
model_path = os.path.join(self.save_directory,
model_name)
self.model.load_state_dict(torch.load(model_path))
# Save Model
def save(self, model_name):
model_path = os.path.join(self.save_directory,
model_name)
torch.save(self.model.state_dict(), model_path)
| 4,511 | Python | 33.707692 | 76 | 0.545334 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/omni/sample/ackermann_amr_trainer/ackermann_trainer_window_start.py |
# Copyright (c) 2020-2024, 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 .ackermann_amr_model import ackermann_amr_model
import omni.ext
import omni.ui as ui
import carb.events
import os
import tempfile
import time
import omni.usd
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility import capture_viewport_to_file
from omni.kit.viewport.utility import capture_viewport_to_buffer
import omni.kit.app
import uuid
from omni.ui import color as cl
import asyncio
class ackermann_trainer_window(ui.Window):
def __init__(self, *args, **kwargs):
self.file_path = ""
self.click_x = 0
self.click_y = 0
self.prediction_x = 0
self.prediction_y = 0
self.thumbnail_height = 300
self.thumbnail_width = 600
# Configure Directory Where Data Will Be Saved
self.save_dir = tempfile.gettempdir()
self.save_dir = os.path.join(self.save_dir, 'road_following')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
self.save_dir = os.path.join(self.save_dir, 'apex')
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)
# Initialize AI Model
self.model = ackermann_amr_model(self.thumbnail_height,
self.thumbnail_width,
self.save_dir)
self.update_stream = omni.kit.app.get_app().get_update_event_stream()
self.frame_update_count = 0
self.ov_update = None
self.build_ui()
# Capture Image
def onCapture(self):
# Get Filename
filename = '%s.png' % (str(uuid.uuid1()))
self.file_path = os.path.join(self.save_dir, filename)
# Request Image Capture Asynchronously
asyncio.ensure_future(self.capture_image(self.replace_image,
self.file_path))
# Capture the Viewport to File
async def capture_image(self, on_complete_fn: callable, file_path) -> str:
# 2.1.2 Capture the Viewport to File
# Wait for the Capture to Complete
if on_complete_fn:
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Update the User Interface
on_complete_fn()
# Thumbnail Clicked Callback
def onMouseReleased(self, x, y, button, modifier, canvas):
# 2.1.4 Capture Click Position
# 2.1.4 Add Image to Dataset
# Update Image Annotation
self.replace_image()
# Update Count
self.count_model.set_value(str(len(self.model.dataset)))
# Replace the Thumbnail with the latest image
def replace_image(self):
counter = 0
while not os.path.exists(self.file_path) and counter < 10:
time.sleep(0.1)
counter += 1
with self.ClickableCanvas:
with ui.ZStack():
# 2.1.3 Update the image from the capture
ui.Image()
with ui.VStack():
# 2.1.5 Set Annotation Y-Position
ui.Spacer()
with ui.HStack():
# 2.1.5 Set Annotation Z-Position
ui.Spacer()
style = {"Circle": {"background_color": cl("#cc0000"),
"border_color": cl("#cc0000"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.
Alignment.LEFT_TOP,
style=style)
# Add Prediction Dot
with ui.VStack():
ui.Spacer(height=self.prediction_y)
with ui.HStack():
ui.Spacer(width=self.prediction_x)
style = {"Circle": {"background_color": cl("#00cc00"),
"border_color": cl("#00cc00"),
"border_width": 2}}
ui.Circle(width=10,
height=10,
alignment=ui.Alignment.LEFT_TOP,
style=style)
# Train the AI Model
def train(self):
self.train_button.enabled = False
# 2.1.6 Train AI Model
self.train_button.enabled = True
carb.log_info("Training Complete")
# Turn Evaluation On and Off
def toggle_eval(self, model):
# Toggle Evaluation On and Off
if self.eval_model.get_value_as_bool():
self.ov_update = self.update_stream.create_subscription_to_pop(
self.on_update,
name="Eval_Subscription")
else:
self.ov_update.unsubscribe()
# Omniverse Update Callback
def on_update(self, e: carb.events.IEvent):
# Capture the Viewport Every 30 Frames
self.frame_update_count += 1
if self.frame_update_count % 30 == 0:
self.frame_update_count = 1
# 2.1.7 Capture the Viewport to Buffer
# Evaluate the Viewport with the AI Model
def on_viewport_captured(self, buffer, buffer_size, width, height, format):
# 2.1.7 Evaluate Viewport Image
self.replace_image()
# 2.1.8 Load Model
def onLoadModel(self):
pass
# 2.1.8 Save Model
def onSaveModel(self):
pass
# Build the UI
def build_ui(self):
# Build UI
self._window = ui.Window("Ackermann AMR Trainer", width=600, height=500)
with self._window.frame:
with ui.ScrollingFrame():
with ui.VStack():
ui.Spacer(height=40)
# Capture Image
with ui.HStack(height=self.thumbnail_height):
with ui.HStack():
ui.Spacer()
self.ClickableCanvas = ui.CanvasFrame(
draggable=False,
width=self.thumbnail_width,
height=self.thumbnail_height)
self.ClickableCanvas.set_mouse_released_fn(
lambda x, y, b, m, c=self.ClickableCanvas:
self.onMouseReleased(x, y, b, m, c))
ui.Spacer()
# Capture Button
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"Capture",
clicked_fn=lambda: self.onCapture(),
style={"margin": 5},
height=30,
width=self.thumbnail_width)
ui.Spacer()
# Count Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'Count: ',
style={"margin": 5},
width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.count_model = ui.SimpleStringModel(
str(len(self.model.dataset)))
ui.StringField(
self.count_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Train and Eval Buttons
with ui.HStack(height=40):
ui.Spacer()
self.train_button = ui.Button(
"Train",
clicked_fn=lambda: self.train(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_button = ui.ToolButton(
text="Evaluate",
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
self.eval_model = self.eval_button.model
self.eval_model.add_value_changed_fn(
lambda m: self.toggle_eval(m))
ui.Spacer()
# Model File Path Widget
with ui.HStack(height=40):
ui.Spacer()
ui.Label(
'model path: ',
style={"margin": 5},
height=30, width=self.thumbnail_width/2,
alignment=ui.Alignment.RIGHT_CENTER)
self.model_path_model = ui.SimpleStringModel(
'road_following_model.pth')
ui.StringField(
self.model_path_model,
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
# Model Load and Save Buttons
with ui.HStack(height=40):
ui.Spacer()
ui.Button(
"load model",
clicked_fn=lambda: self.onLoadModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Button(
"save model",
clicked_fn=lambda: self.onSaveModel(),
style={"margin": 5},
height=30,
width=self.thumbnail_width/2)
ui.Spacer()
ui.Spacer()
| 10,649 | Python | 37.172043 | 80 | 0.464832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.