code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def gen_friction_map(
scenario: str, surface_patches: Sequence[sstypes.RoadSurfacePatch]
):
"""Generates friction map file according to the surface patches defined in
scenario file.
"""
_check_if_called_externally()
output_path = os.path.join(scenario, "build", "friction_map.pkl")
with open(output_path, "wb") as f:
pickle.dump(surface_patches, f) | Generates friction map file according to the surface patches defined in
scenario file. | gen_friction_map | python | huawei-noah/SMARTS | smarts/sstudio/genscenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py | MIT |
def gen_missions(
scenario: str,
missions: Sequence[sstypes.Mission],
actors: Sequence[sstypes.Actor],
name: str,
output_dir: str,
map_spec: Optional[sstypes.MapSpec] = None,
):
"""Generates a route file to represent missions (a route per mission). Will
create the output_dir if it doesn't exist already.
"""
_check_if_called_externally()
generator = TrafficGenerator(scenario, map_spec)
def resolve_mission(mission):
route = getattr(mission, "route", None)
kwargs = {}
if route:
kwargs["route"] = generator.resolve_route(route, False)
via = getattr(mission, "via", ())
if via != ():
kwargs["via"] = _resolve_vias(via, generator=generator)
mission = replace(mission, **kwargs)
return mission
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, name + ".pkl")
_validate_missions(missions)
missions = [
ActorAndMission(actor=actor, mission=resolve_mission(mission))
for actor, mission in itertools.product(actors, missions)
]
with open(output_path, "wb") as f:
pickle.dump(missions, f)
return True | Generates a route file to represent missions (a route per mission). Will
create the output_dir if it doesn't exist already. | gen_missions | python | huawei-noah/SMARTS | smarts/sstudio/genscenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py | MIT |
def gen_traffic_histories(
scenario: str,
histories_datasets: Sequence[Union[sstypes.TrafficHistoryDataset, str]],
map_spec: Optional[sstypes.MapSpec] = None,
):
"""Converts traffic history to a format that SMARTS can use.
Args:
scenario:
The scenario directory
histories_datasets:
A sequence of traffic history descriptors.
map_spec:
An optional map specification that takes precedence over scenario directory information.
"""
_check_if_called_externally()
road_map = None # shared across all history_datasets in scenario
for hdsr in histories_datasets:
assert isinstance(hdsr, sstypes.TrafficHistoryDataset)
if not hdsr.input_path:
print(f"skipping placeholder dataset spec '{hdsr.name}'.")
continue
from smarts.sstudio import genhistories
map_bbox = None
if hdsr.filter_off_map or hdsr.flip_y:
if map_spec:
if not road_map:
road_map, _ = map_spec.builder_fn(map_spec)
assert road_map
map_bbox = road_map.bounding_box
else:
logger.warn(
f"no map_spec supplied, so unable to filter off-map coordinates and/or flip_y for {hdsr.name}"
)
output_dir = os.path.join(scenario, "build")
genhistories.import_dataset(hdsr, output_dir, map_bbox) | Converts traffic history to a format that SMARTS can use.
Args:
scenario:
The scenario directory
histories_datasets:
A sequence of traffic history descriptors.
map_spec:
An optional map specification that takes precedence over scenario directory information. | gen_traffic_histories | python | huawei-noah/SMARTS | smarts/sstudio/genscenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py | MIT |
def gen_metadata(scenario: str, scenario_metadata: sstypes.StandardMetadata):
"""Generate the metadata for the scenario
Args:
scenario (str):The scenario directory
scenario_metadata (smarts.sstudio.sstypes.standard_metadata.StandardMetadata): Scenario metadata information.
"""
_check_if_called_externally()
output_path = os.path.join(scenario, "build", "scenario_metadata.yaml")
with open(output_path, "w") as f:
yaml.dump(scenario_metadata._dict_metadata, f) | Generate the metadata for the scenario
Args:
scenario (str):The scenario directory
scenario_metadata (smarts.sstudio.sstypes.standard_metadata.StandardMetadata): Scenario metadata information. | gen_metadata | python | huawei-noah/SMARTS | smarts/sstudio/genscenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py | MIT |
def generate_glb_from_opendrive_file(od_xodr_file: str, out_glb_dir: str):
"""Creates a geometry file from an OpenDRIVE map file."""
map_spec = MapSpec(od_xodr_file)
road_network = OpenDriveRoadNetwork.from_spec(map_spec)
road_network.to_glb(out_glb_dir) | Creates a geometry file from an OpenDRIVE map file. | generate_glb_from_opendrive_file | python | huawei-noah/SMARTS | smarts/sstudio/od2mesh.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/od2mesh.py | MIT |
def scale(self) -> float:
"""The base scale based on the ratio of map lane size to real lane size."""
return self._scale | The base scale based on the ratio of map lane size to real lane size. | scale | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def traffic_light_rows(self) -> Iterable:
"""Iterable dataset rows representing traffic light states (if present)."""
raise NotImplementedError | Iterable dataset rows representing traffic light states (if present). | traffic_light_rows | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def rows(self) -> Iterable:
"""The iterable rows of the dataset."""
raise NotImplementedError | The iterable rows of the dataset. | rows | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def column_val_in_row(self, row, col_name: str) -> Any:
"""Access the value of a dataset row which intersects with the given column name."""
# XXX: this public method is improper because this requires a dataset row but that is
# implementation specific.
raise NotImplementedError | Access the value of a dataset row which intersects with the given column name. | column_val_in_row | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def check_dataset_spec(self, dataset_spec: Dict[str, Any]):
"""Validate the form of the dataset specification."""
errmsg = None
if "input_path" not in dataset_spec:
errmsg = "'input_path' field is required in dataset_spec."
elif dataset_spec.get("flip_y"):
if dataset_spec["source_type"] != "NGSIM":
errmsg = "'flip_y' option only supported for NGSIM datasets."
elif not dataset_spec.get("_map_bbox"):
errmsg = "'_map_bbox' is required if 'flip_y' option used; need to pass in a map_spec."
if errmsg:
self._log.error(errmsg)
raise ValueError(errmsg)
self._dataset_spec = dataset_spec | Validate the form of the dataset specification. | check_dataset_spec | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def _create_tables(self, dbconxn):
ccur = dbconxn.cursor()
ccur.execute(
"""CREATE TABLE Spec (
key TEXT PRIMARY KEY,
value TEXT
) WITHOUT ROWID"""
)
ccur.execute(
"""CREATE TABLE Vehicle (
id INTEGER PRIMARY KEY,
type INTEGER NOT NULL,
length REAL,
width REAL,
height REAL,
is_ego_vehicle INTEGER DEFAULT 0
) WITHOUT ROWID"""
)
ccur.execute(
"""CREATE TABLE Trajectory (
vehicle_id INTEGER NOT NULL,
sim_time REAL NOT NULL,
position_x REAL NOT NULL,
position_y REAL NOT NULL,
heading_rad REAL NOT NULL,
speed REAL DEFAULT 0.0,
lane_id INTEGER DEFAULT 0,
PRIMARY KEY (vehicle_id, sim_time),
FOREIGN KEY (vehicle_id) REFERENCES Vehicle(id)
) WITHOUT ROWID"""
)
ccur.execute(
"""CREATE TABLE TrafficLightState (
sim_time REAL NOT NULL,
state INTEGER NOT NULL,
stop_point_x REAL NOT NULL,
stop_point_y REAL NOT NULL,
lane INTEGER NOT NULL
)"""
)
dbconxn.commit()
ccur.close() | CREATE TABLE Spec (
key TEXT PRIMARY KEY,
value TEXT
) WITHOUT ROWID | _create_tables | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def create_output(self, time_precision: int = 3):
"""Convert the dataset into the output database file.
Args:
time_precision: A limit for digits after decimal for each processed sim_time.
(3 is millisecond precision)
"""
dbconxn = sqlite3.connect(self._output)
self._log.debug("creating tables...")
self._create_tables(dbconxn)
self._log.debug("inserting data...")
iscur = dbconxn.cursor()
insert_kv_sql = "INSERT INTO Spec VALUES (?, ?)"
self._write_dict(self._dataset_spec, insert_kv_sql, iscur)
dbconxn.commit()
iscur.close()
# TAI: can use executemany() and batch insert rows together if this turns out to be too slow...
insert_vehicle_sql = "INSERT INTO Vehicle VALUES (?, ?, ?, ?, ?, ?)"
insert_traj_sql = "INSERT INTO Trajectory VALUES (?, ?, ?, ?, ?, ?, ?)"
insert_traffic_light_sql = (
"INSERT INTO TrafficLightState VALUES (?, ?, ?, ?, ?)"
)
vehicle_ids = set()
itcur = dbconxn.cursor()
x_offset = self._dataset_spec.get("x_offset", 0.0)
y_offset = self._dataset_spec.get("y_offset", 0.0)
for row in self.rows:
vid = int(self.column_val_in_row(row, "vehicle_id"))
if vid not in vehicle_ids:
ivcur = dbconxn.cursor()
# These are not available in all datasets
height = self.column_val_in_row(row, "height")
is_ego = self.column_val_in_row(row, "is_ego_vehicle")
veh_args = (
vid,
int(self.column_val_in_row(row, "type")),
float(self.column_val_in_row(row, "length")) * self.scale,
float(self.column_val_in_row(row, "width")) * self.scale,
float(height) * self.scale if height else None,
int(is_ego) if is_ego else 0,
)
ivcur.execute(insert_vehicle_sql, veh_args)
ivcur.close()
dbconxn.commit()
vehicle_ids.add(vid)
traj_args = (
vid,
# time units are in milliseconds for both NGSIM and Interaction datasets, convert to secs
round(
float(self.column_val_in_row(row, "sim_time")) / 1000,
time_precision,
),
(float(self.column_val_in_row(row, "position_x")) + x_offset)
* self.scale,
(float(self.column_val_in_row(row, "position_y")) + y_offset)
* self.scale,
float(self.column_val_in_row(row, "heading_rad")),
float(self.column_val_in_row(row, "speed")) * self.scale,
self.column_val_in_row(row, "lane_id"),
)
# Ignore datapoints with NaNs
if not any(a is not None and np.isnan(a) for a in traj_args):
itcur.execute(insert_traj_sql, traj_args)
# Insert traffic light states if available
try:
for row in self.traffic_light_rows:
tls_args = (
round(
float(self.column_val_in_row(row, "sim_time")) / 1000,
time_precision,
),
int(self.column_val_in_row(row, "state")),
float(self.column_val_in_row(row, "stop_point_x") + x_offset)
* self.scale,
float(self.column_val_in_row(row, "stop_point_y") + y_offset)
* self.scale,
float(self.column_val_in_row(row, "lane")),
)
itcur.execute(insert_traffic_light_sql, tls_args)
except NotImplementedError:
pass
itcur.close()
dbconxn.commit()
# ensure that sim_time always starts at 0:
self._log.debug("shifting sim_times..")
mcur = dbconxn.cursor()
mcur.execute(
f"UPDATE Trajectory SET sim_time = round(sim_time - (SELECT min(sim_time) FROM Trajectory), {time_precision})"
)
mcur.close()
dbconxn.commit()
self._log.debug("creating indices..")
icur = dbconxn.cursor()
icur.execute("CREATE INDEX Trajectory_Time ON Trajectory (sim_time)")
icur.execute("CREATE INDEX Trajectory_Vehicle ON Trajectory (vehicle_id)")
icur.execute("CREATE INDEX Vehicle_Type ON Vehicle (type)")
icur.execute(
"CREATE INDEX TrafficLightState_SimTime ON TrafficLightState (sim_time)"
)
dbconxn.commit()
icur.close()
dbconxn.close()
self._log.debug("output done") | Convert the dataset into the output database file.
Args:
time_precision: A limit for digits after decimal for each processed sim_time.
(3 is millisecond precision) | create_output | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def import_dataset(
dataset_spec: sstypes.TrafficHistoryDataset,
output_path: str,
map_bbox: Optional[BoundingBox] = None,
):
"""called to pre-process (import) a TrafficHistoryDataset for use by SMARTS"""
if not dataset_spec.input_path:
print(f"skipping placeholder dataset spec '{dataset_spec.name}'.")
return
output = os.path.join(output_path, f"{dataset_spec.name}.shf")
if os.path.exists(output):
os.remove(output)
source = dataset_spec.source_type
dataset_dict = dataset_spec.__dict__
if map_bbox:
assert dataset_spec.filter_off_map
dataset_dict["_map_bbox"] = map_bbox
if source == "NGSIM":
dataset = NGSIM(dataset_dict, output)
elif source == "INTERACTION":
dataset = Interaction(dataset_dict, output)
elif source == "Waymo":
dataset = Waymo(dataset_dict, output)
elif source == "Argoverse":
dataset = Argoverse(dataset_dict, output)
else:
raise ValueError(
f"unsupported TrafficHistoryDataset type: {dataset_spec.source_type}"
)
dataset.create_output() | called to pre-process (import) a TrafficHistoryDataset for use by SMARTS | import_dataset | python | huawei-noah/SMARTS | smarts/sstudio/genhistories.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genhistories.py | MIT |
def generate_bytemap_from_glb_file(
glb_file: str, out_bytemap_file: str, padding: int, inverted=False
):
"""Creates a geometry file from a sumo map file."""
renderer = Renderer("r")
bounds = renderer.load_road_map(glb_file)
size = (*(bounds.max - bounds.min),)
vs = VehicleState(
"a",
pose=Pose(np.array((*bounds.center,)), np.array([0, 0, 0, 1])),
dimensions=Dimensions(1, 1, 1),
)
camera = DrivableAreaGridMapSensor(
vehicle_state=vs,
width=int(size[0]) + padding,
height=int(size[1]) + padding,
resolution=1,
renderer=renderer,
)
renderer.render()
image = camera(renderer)
data = image.data
if inverted:
hf = HeightField(data, (1, 1))
data = hf.inverted().data
from PIL import Image
im = Image.fromarray(data.squeeze(), "L")
im.save(out_bytemap_file)
im.close() | Creates a geometry file from a sumo map file. | generate_bytemap_from_glb_file | python | huawei-noah/SMARTS | smarts/sstudio/graphics/mesh2bytemap.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/mesh2bytemap.py | MIT |
def data(self):
"""The raw underlying data."""
return self._data | The raw underlying data. | data | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def dtype(self):
"""The per element data type."""
return self._data.dtype | The per element data type. | dtype | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def size(self):
"""The width and height."""
return self._size | The width and height. | size | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def resolution(self):
"""Resolution of this height field."""
return self._resolution | Resolution of this height field. | resolution | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def metadata(self):
"""Additional metadata."""
return self._metadata | Additional metadata. | metadata | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def add(self, other: HeightField) -> HeightField:
"""Add by element."""
assert self._check_match(other)
return HeightField(np.add(self._data, other._data), self._size) | Add by element. | add | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def subtract(self, other: HeightField) -> HeightField:
"""Subtract by element."""
assert self._check_match(other)
data = np.subtract(self._data, other._data)
return HeightField(data, self.size) | Subtract by element. | subtract | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def scale_by(self, other: HeightField) -> HeightField:
"""Scale this height field by another height field."""
assert self._check_match(other)
inplace_array = np.multiply(
other._data,
np.reciprocal(np.invert(other._data.dtype.type(0)), dtype=np.float64),
)
np.multiply(self._data, inplace_array, out=inplace_array)
if self.dtype.type in {"u", "i"}:
inplace_array.round(out=inplace_array)
return HeightField(inplace_array.astype(self.dtype), self.size) | Scale this height field by another height field. | scale_by | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def multiply(self, other: HeightField) -> HeightField:
"""Multiply the byte values between these height fields"""
assert self._check_match(other)
return HeightField(np.multiply(self._data, other._data), self.size) | Multiply the byte values between these height fields | multiply | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def max(self, other: HeightField) -> HeightField:
"""Get the maximum value of overlapping height fields."""
assert self._check_match(other)
return HeightField(np.max([self._data, other._data], axis=0), self.size) | Get the maximum value of overlapping height fields. | max | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def inverted(self) -> HeightField:
"""Invert this height field assuming 8 bit."""
data = np.invert(self._data)
return HeightField(data, self._size, self._metadata) | Invert this height field assuming 8 bit. | inverted | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def apply_kernel(
self, kernel: np.ndarray, min_val=-np.inf, max_val=np.inf, pad_mode="edge"
):
"""Apply a kernel to the whole height field.
The kernel can be asymmetric but still needs each dimension to be an odd value.
"""
assert len(kernel.shape) == 2 and np.all(
[k % 2 for k in kernel.shape]
), "Kernel shape must be 2D and shape dimension values must be odd"
k_height, k_width = kernel.shape
m_height, m_width = self.data.shape
k_size = max(k_height, k_width)
padded = np.pad(self.data, (int(k_size / 2), int(k_size / 2)), mode=pad_mode)
if k_size > 1:
if k_height == 1:
padded = padded[1:-1, :]
elif k_width == 1:
padded = padded[:, 1:-1]
# iterate through matrix, apply kernel, and sum
output = np.empty_like(self.data)
for v in range(m_height):
for u in range(m_width):
between = padded[v : k_height + v, u : k_width + u] * kernel
output[v][u] = min(max(np.sum(between), min_val), max_val)
return HeightField(output, self.size) | Apply a kernel to the whole height field.
The kernel can be asymmetric but still needs each dimension to be an odd value. | apply_kernel | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def apply_function(
self,
fn: Callable[[np.ndarray, int, int], np.uint8],
min_val=-np.inf,
max_val=np.inf,
):
"""Apply a function to each element."""
output = np.empty_like(self.data)
for i in range(self.data.shape[0]):
for j in range(self.data.shape[1]):
output[i][j] = min(max(fn(self.data, i, j), min_val), max_val)
return HeightField(output, self.size) | Apply a function to each element. | apply_function | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def write_image(self, file: Union[str, Path, BinaryIO]):
"""Write this out to a greyscale image."""
from PIL import Image
a = self.data.astype(np.uint8)
im = Image.fromarray(a, "L")
im.save(file) | Write this out to a greyscale image. | write_image | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def load_image(cls, file: Union[str, Path]):
"""Load from any image."""
from PIL import Image
with Image.open(file) as im:
data = np.asarray(im)
assert len(data.shape) == 2
return cls(data, data.shape[:2]) | Load from any image. | load_image | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def from_rgb(cls, data: np.ndarray):
"""Load from an rgb array."""
d = np.min(data, axis=2)
return HeightField(d, size=(data.shape[1], data.shape[0])) | Load from an rgb array. | from_rgb | python | huawei-noah/SMARTS | smarts/sstudio/graphics/heightfield.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/graphics/heightfield.py | MIT |
def evaluate(self, **kwargs) -> ConditionState:
"""Used to evaluate if a condition is met.
Returns:
ConditionState: The evaluation result of the condition.
"""
raise NotImplementedError() | Used to evaluate if a condition is met.
Returns:
ConditionState: The evaluation result of the condition. | evaluate | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def requires(self) -> ConditionRequires:
"""Information that the condition requires to evaluate state.
Returns:
ConditionRequires: The types of information this condition needs in order to evaluate.
"""
raise NotImplementedError() | Information that the condition requires to evaluate state.
Returns:
ConditionRequires: The types of information this condition needs in order to evaluate. | requires | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def negation(self) -> "NegatedCondition":
"""Negates this condition giving the opposite result on evaluation.
.. spelling:word-list::
ConditionState
>>> condition_true = LiteralCondition(ConditionState.TRUE)
>>> condition_true.evaluate()
<ConditionState.TRUE: 4>
>>> condition_false = condition_true.negation()
>>> condition_false.evaluate()
<ConditionState.FALSE: 0>
Note\\: This erases temporal values EXPIRED and BEFORE.
>>> condition_before = LiteralCondition(ConditionState.BEFORE)
>>> condition_before.negation().negation().evaluate()
<ConditionState.FALSE: 0>
Returns:
NegatedCondition: The wrapped condition.
"""
return NegatedCondition(self) | Negates this condition giving the opposite result on evaluation.
.. spelling:word-list::
ConditionState
>>> condition_true = LiteralCondition(ConditionState.TRUE)
>>> condition_true.evaluate()
<ConditionState.TRUE: 4>
>>> condition_false = condition_true.negation()
>>> condition_false.evaluate()
<ConditionState.FALSE: 0>
Note\\: This erases temporal values EXPIRED and BEFORE.
>>> condition_before = LiteralCondition(ConditionState.BEFORE)
>>> condition_before.negation().negation().evaluate()
<ConditionState.FALSE: 0>
Returns:
NegatedCondition: The wrapped condition. | negation | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def conjunction(self, other: "Condition") -> "CompoundCondition":
"""Resolve conditions as A AND B.
The bit AND operator has been overloaded to call this method.
>>> condition = DependeeActorCondition("leader")
>>> condition.evaluate(actor_ids={"leader"})
<ConditionState.TRUE: 4>
>>> conjunction = condition & LiteralCondition(ConditionState.FALSE)
>>> conjunction.evaluate(actor_ids={"leader"})
<ConditionState.FALSE: 0>
Note that the resolution has the priority EXPIRED > BEFORE > FALSE > TRUE.
>>> conjunction = LiteralCondition(ConditionState.TRUE) & LiteralCondition(ConditionState.BEFORE)
>>> conjunction.evaluate()
<ConditionState.BEFORE: 1>
>>> (conjunction & LiteralCondition(ConditionState.EXPIRED)).evaluate()
<ConditionState.EXPIRED: 2>
Returns:
CompoundCondition: A condition combining two conditions using an AND operation.
"""
return CompoundCondition(self, other, operator=ConditionOperator.CONJUNCTION) | Resolve conditions as A AND B.
The bit AND operator has been overloaded to call this method.
>>> condition = DependeeActorCondition("leader")
>>> condition.evaluate(actor_ids={"leader"})
<ConditionState.TRUE: 4>
>>> conjunction = condition & LiteralCondition(ConditionState.FALSE)
>>> conjunction.evaluate(actor_ids={"leader"})
<ConditionState.FALSE: 0>
Note that the resolution has the priority EXPIRED > BEFORE > FALSE > TRUE.
>>> conjunction = LiteralCondition(ConditionState.TRUE) & LiteralCondition(ConditionState.BEFORE)
>>> conjunction.evaluate()
<ConditionState.BEFORE: 1>
>>> (conjunction & LiteralCondition(ConditionState.EXPIRED)).evaluate()
<ConditionState.EXPIRED: 2>
Returns:
CompoundCondition: A condition combining two conditions using an AND operation. | conjunction | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def disjunction(self, other: "Condition") -> "CompoundCondition":
"""Resolve conditions as A OR B.
The bit OR operator has been overloaded to call this method.
>>> disjunction = LiteralCondition(ConditionState.TRUE) | LiteralCondition(ConditionState.BEFORE)
>>> disjunction.evaluate()
<ConditionState.TRUE: 4>
Note that the resolution has the priority TRUE > BEFORE > FALSE > EXPIRED.
>>> disjunction = LiteralCondition(ConditionState.FALSE) | LiteralCondition(ConditionState.EXPIRED)
>>> disjunction.evaluate()
<ConditionState.FALSE: 0>
>>> (disjunction | LiteralCondition(ConditionState.BEFORE)).evaluate()
<ConditionState.BEFORE: 1>
"""
return CompoundCondition(self, other, operator=ConditionOperator.DISJUNCTION) | Resolve conditions as A OR B.
The bit OR operator has been overloaded to call this method.
>>> disjunction = LiteralCondition(ConditionState.TRUE) | LiteralCondition(ConditionState.BEFORE)
>>> disjunction.evaluate()
<ConditionState.TRUE: 4>
Note that the resolution has the priority TRUE > BEFORE > FALSE > EXPIRED.
>>> disjunction = LiteralCondition(ConditionState.FALSE) | LiteralCondition(ConditionState.EXPIRED)
>>> disjunction.evaluate()
<ConditionState.FALSE: 0>
>>> (disjunction | LiteralCondition(ConditionState.BEFORE)).evaluate()
<ConditionState.BEFORE: 1> | disjunction | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def implication(self, other: "Condition") -> "CompoundCondition":
"""Resolve conditions as A IMPLIES B. This is the same as A AND B OR NOT A."""
return CompoundCondition(self, other, operator=ConditionOperator.IMPLICATION) | Resolve conditions as A IMPLIES B. This is the same as A AND B OR NOT A. | implication | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def trigger(
self, delay_seconds: float, persistent: bool = False
) -> "ConditionTrigger":
"""Converts the condition to a trigger which becomes permanently TRUE after the first time the inner condition becomes TRUE.
>>> trigger = TimeWindowCondition(2, 5).trigger(delay_seconds=0)
>>> trigger.evaluate(time=1)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=4)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=90)
<ConditionState.TRUE: 4>
>>> start_time = 5
>>> between_time = 10
>>> delay_seconds = 20
>>> trigger = LiteralCondition(ConditionState.TRUE).trigger(delay_seconds=delay_seconds)
>>> trigger.evaluate(time=start_time)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=between_time)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=start_time + delay_seconds)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=between_time)
<ConditionState.BEFORE: 1>
Args:
delay_seconds (float): Applies the trigger after the delay has passed since the inner condition first TRUE. Defaults to False.
persistent (bool, optional): Mixes the inner result with the trigger result using an AND operation.
Returns:
ConditionTrigger: A resulting condition.
"""
return ConditionTrigger(
self, delay_seconds=delay_seconds, persistent=persistent
) | Converts the condition to a trigger which becomes permanently TRUE after the first time the inner condition becomes TRUE.
>>> trigger = TimeWindowCondition(2, 5).trigger(delay_seconds=0)
>>> trigger.evaluate(time=1)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=4)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=90)
<ConditionState.TRUE: 4>
>>> start_time = 5
>>> between_time = 10
>>> delay_seconds = 20
>>> trigger = LiteralCondition(ConditionState.TRUE).trigger(delay_seconds=delay_seconds)
>>> trigger.evaluate(time=start_time)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=between_time)
<ConditionState.BEFORE: 1>
>>> trigger.evaluate(time=start_time + delay_seconds)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=between_time)
<ConditionState.BEFORE: 1>
Args:
delay_seconds (float): Applies the trigger after the delay has passed since the inner condition first TRUE. Defaults to False.
persistent (bool, optional): Mixes the inner result with the trigger result using an AND operation.
Returns:
ConditionTrigger: A resulting condition. | trigger | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def expire(
self, time, expired_state=ConditionState.EXPIRED, relative: bool = False
) -> "ExpireTrigger":
"""This trigger evaluates to the expired state value after the given simulation time.
>>> trigger = LiteralCondition(ConditionState.TRUE).expire(20)
>>> trigger.evaluate(time=10)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=30)
<ConditionState.EXPIRED: 2>
Args:
time (float): The simulation time when this trigger changes.
expired_state (ConditionState, optional): The condition state to use when the simulation is after the given time. Defaults to ConditionState.EXPIRED.
relative (bool, optional): If this trigger should resolve relative to the first evaluated time.
Returns:
ExpireTrigger: The resulting condition.
"""
return ExpireTrigger(
inner_condition=self,
time=time,
expired_state=expired_state,
relative=relative,
) | This trigger evaluates to the expired state value after the given simulation time.
>>> trigger = LiteralCondition(ConditionState.TRUE).expire(20)
>>> trigger.evaluate(time=10)
<ConditionState.TRUE: 4>
>>> trigger.evaluate(time=30)
<ConditionState.EXPIRED: 2>
Args:
time (float): The simulation time when this trigger changes.
expired_state (ConditionState, optional): The condition state to use when the simulation is after the given time. Defaults to ConditionState.EXPIRED.
relative (bool, optional): If this trigger should resolve relative to the first evaluated time.
Returns:
ExpireTrigger: The resulting condition. | expire | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def __and__(self, other: "Condition") -> "CompoundCondition":
"""Resolve conditions as A AND B."""
assert isinstance(other, Condition)
return self.conjunction(other) | Resolve conditions as A AND B. | __and__ | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def __or__(self, other: "Condition") -> "CompoundCondition":
"""Resolve conditions as A OR B."""
assert isinstance(other, Condition)
return self.disjunction(other) | Resolve conditions as A OR B. | __or__ | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def __neg__(self) -> "NegatedCondition":
"""Negates this condition"""
return self.negation() | Negates this condition | __neg__ | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def evaluate(self, **kwargs) -> ConditionState:
"""Used to evaluate if a condition is met.
Args:
actor_info: Information about the currently relevant actor.
Returns:
ConditionState: The evaluation result of the condition.
"""
raise NotImplementedError() | Used to evaluate if a condition is met.
Args:
actor_info: Information about the currently relevant actor.
Returns:
ConditionState: The evaluation result of the condition. | evaluate | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def loitering(cls: Type["VehicleSpeedCondition"], abs_error=0.01):
"""Generates a speed condition which assumes that the subject is stationary."""
return cls(low=abs_error, high=abs_error) | Generates a speed condition which assumes that the subject is stationary. | loitering | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/condition.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/condition.py | MIT |
def to_actor_id(actor, mission_group):
"""Mashes the actor id and mission group to create what needs to be a unique id."""
return SocialAgentId.new(actor.name, group=mission_group) | Mashes the actor id and mission group to create what needs to be a unique id. | to_actor_id | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/bubble.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/bubble.py | MIT |
def is_boid(self):
"""Tests if the actor is to control multiple vehicles."""
return isinstance(self.actor, (BoidAgentActor, TrafficEngineActor)) | Tests if the actor is to control multiple vehicles. | is_boid | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/bubble.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/bubble.py | MIT |
def traffic_provider(self) -> Optional[str]:
"""The name of the traffic provider used if the actor is to be controlled by a traffic engine.
Returns:
(Optional[str]): The name of the traffic provider or `None`.
"""
return (
self.actor.traffic_provider
if isinstance(self.actor, TrafficEngineActor)
else None
) | The name of the traffic provider used if the actor is to be controlled by a traffic engine.
Returns:
(Optional[str]): The name of the traffic provider or `None`. | traffic_provider | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/bubble.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/bubble.py | MIT |
def get(self, __key, __default=None):
"""Retrieve the value or a default.
Args:
__key (Any): The key to find.
__default (Any, optional): The default if the key does not exist. Defaults to None.
Returns:
Optional[Any]: The value or default.
"""
return self._dict_metadata.get(__key, __default) | Retrieve the value or a default.
Args:
__key (Any): The key to find.
__default (Any, optional): The default if the key does not exist. Defaults to None.
Returns:
Optional[Any]: The value or default. | get | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/standard_metadata.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/standard_metadata.py | MIT |
def to_geometry(self, road_map: Optional[RoadMap] = None) -> Polygon:
"""Generates the geometry from this zone."""
raise NotImplementedError | Generates the geometry from this zone. | to_geometry | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/zone.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/zone.py | MIT |
def to_geometry(self, road_map: Optional[RoadMap]) -> Polygon:
"""Generates a map zone over a stretch of the given lanes."""
assert (
road_map is not None
), f"{self.__class__.__name__} requires a road map to resolve geometry."
def resolve_offset(offset, geometry_length, lane_length):
if offset == "base":
return 0
# push off of end of lane
elif offset == "max":
return lane_length - geometry_length
elif offset == "random":
return random.uniform(0, lane_length - geometry_length)
else:
return float(offset)
def pick_remaining_shape_after_split(geometry_collection, expected_point):
lane_shape = geometry_collection
if not isinstance(lane_shape, GeometryCollection):
return lane_shape
# For simplicity, we only deal w/ the == 1 or 2 case
if len(lane_shape.geoms) not in {1, 2}:
return None
if len(lane_shape.geoms) == 1:
return lane_shape.geoms[0]
# We assume that there are only two split shapes to choose from
keep_index = 0
if lane_shape.geoms[1].minimum_rotated_rectangle.contains(expected_point):
# 0 is the discard piece, keep the other
keep_index = 1
lane_shape = lane_shape.geoms[keep_index]
return lane_shape
def split_lane_shape_at_offset(
lane_shape: Polygon, lane: RoadMap.Lane, offset: float
):
# XXX: generalize to n-dim
width_2, _ = lane.width_at_offset(offset)
point = np.array(lane.from_lane_coord(RefLinePoint(offset)))[:2]
lane_vec = lane.vector_at_offset(offset)[:2]
perp_vec_right = rotate_cw_around_point(lane_vec, np.pi / 2, origin=(0, 0))
perp_vec_right = (
perp_vec_right / max(np.linalg.norm(perp_vec_right), 1e-3) * width_2
+ point
)
perp_vec_left = rotate_cw_around_point(lane_vec, -np.pi / 2, origin=(0, 0))
perp_vec_left = (
perp_vec_left / max(np.linalg.norm(perp_vec_left), 1e-3) * width_2
+ point
)
split_line = LineString([perp_vec_left, perp_vec_right])
return split(lane_shape, split_line)
lane_shapes = []
road_id, lane_idx, offset = self.start
road = road_map.road_by_id(road_id)
buffer_from_ends = 1e-6
for lane_idx in range(lane_idx, lane_idx + self.n_lanes):
lane = road.lane_at_index(lane_idx)
lane_length = lane.length
geom_length = self.length
if geom_length > lane_length:
logging.debug(
f"Geometry is too long={geom_length} with offset={offset} for "
f"lane={lane.lane_id}, using length={lane_length} instead"
)
geom_length = lane_length
assert geom_length > 0 # Geom length is negative
lane_offset = resolve_offset(offset, geom_length, lane_length)
lane_offset += buffer_from_ends
width, _ = lane.width_at_offset(lane_offset) # TODO
lane_shape = lane.shape(0.3, width) # TODO
geom_length = max(geom_length - buffer_from_ends, buffer_from_ends)
lane_length = max(lane_length - buffer_from_ends, buffer_from_ends)
min_cut = min(lane_offset, lane_length)
# Second cut takes into account shortening of geometry by `min_cut`.
max_cut = min(min_cut + geom_length, lane_length)
midpoint = Point(
*lane.from_lane_coord(RefLinePoint(s=lane_offset + geom_length * 0.5))
)
lane_shape = split_lane_shape_at_offset(lane_shape, lane, min_cut)
lane_shape = pick_remaining_shape_after_split(lane_shape, midpoint)
if lane_shape is None:
continue
lane_shape = split_lane_shape_at_offset(
lane_shape,
lane,
max_cut,
)
lane_shape = pick_remaining_shape_after_split(lane_shape, midpoint)
if lane_shape is None:
continue
lane_shapes.append(lane_shape)
geom = unary_union(MultiPolygon(lane_shapes))
return geom | Generates a map zone over a stretch of the given lanes. | to_geometry | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/zone.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/zone.py | MIT |
def to_geometry(self, road_map: Optional[RoadMap] = None) -> Polygon:
"""Generates a box zone at the given position."""
w, h = self.size
x, y = self.pos[:2]
p0 = (-w / 2, -h / 2) # min
p1 = (w / 2, h / 2) # max
poly = Polygon([p0, (p0[0], p1[1]), p1, (p1[0], p0[1])])
if self.rotation is not None:
poly = shapely_rotate(poly, self.rotation, use_radians=True)
return shapely_translate(poly, xoff=x, yoff=y) | Generates a box zone at the given position. | to_geometry | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/zone.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/zone.py | MIT |
def to_geometry(self, road_map: Optional[RoadMap] = None) -> Polygon:
"""Generate a polygon according to given coordinates"""
poly = None
if (
len(self.ext_coordinates) == 2
): # if user only specified two points, create a box
x_min = min(self.ext_coordinates[0][0], self.ext_coordinates[1][0])
x_max = max(self.ext_coordinates[0][0], self.ext_coordinates[1][0])
y_min = min(self.ext_coordinates[0][1], self.ext_coordinates[1][1])
y_max = max(self.ext_coordinates[0][1], self.ext_coordinates[1][1])
poly = box(x_min, y_min, x_max, y_max)
else: # else create a polygon according to the coordinates
poly = Polygon(self.ext_coordinates)
if self.rotation is not None:
poly = shapely_rotate(poly, self.rotation, use_radians=True)
return poly | Generate a polygon according to given coordinates | to_geometry | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/zone.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/zone.py | MIT |
def to_edge(self, sumo_road_network) -> str:
"""Queries the road network to see if there is a junction edge between the two
given edges.
"""
return sumo_road_network.get_edge_in_junction(
self.start_edge_id,
self.start_lane_index,
self.end_edge_id,
self.end_lane_index,
) | Queries the road network to see if there is a junction edge between the two
given edges. | to_edge | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/route.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/route.py | MIT |
def id(self) -> str:
"""The unique id of this route."""
return "{}-{}-{}".format(
"_".join(map(str, self.begin)),
"_".join(map(str, self.end)),
str(hash(self))[:6],
) | The unique id of this route. | id | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/route.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/route.py | MIT |
def roads(self):
"""All roads that are used within this route."""
return (self.begin[0],) + self.via + (self.end[0],) | All roads that are used within this route. | roads | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/route.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/route.py | MIT |
def get(self, __key, __default=None):
"""Retrieve the value or a default.
Args:
__key (Any): The key to find.
__default (Any, optional): The default if the key does not exist. Defaults to None.
Returns:
Optional[Any]: The value or default.
"""
if isinstance(__key, ScenarioMetadataFields):
__key = __key.name
return super().get(__key, __default) | Retrieve the value or a default.
Args:
__key (Any): The key to find.
__default (Any, optional): The default if the key does not exist. Defaults to None.
Returns:
Optional[Any]: The value or default. | get | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/scenario.py | MIT |
def id(self) -> str:
"""The unique id of this flow."""
return "{}-{}".format(
self.route.id,
str(hash(self))[:6],
) | The unique id of this flow. | id | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/traffic.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/traffic.py | MIT |
def id(self) -> str:
"""The unique id of this trip."""
return self.vehicle_name | The unique id of this trip. | id | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/traffic.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/traffic.py | MIT |
def sample(self):
"""The next sample from the distribution."""
return random.gauss(self.mean, self.sigma) | The next sample from the distribution. | sample | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/distribution.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/distribution.py | MIT |
def sample(self):
"""Get the next sample."""
return random.uniform(self.a, self.b) | Get the next sample. | sample | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/distribution.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/distribution.py | MIT |
def id(self) -> str:
"""The identifier tag of the traffic actor."""
return "{}-{}".format(self.name, str(hash(self))[:6]) | The identifier tag of the traffic actor. | id | python | huawei-noah/SMARTS | smarts/sstudio/sstypes/actor/traffic_actor.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sstypes/actor/traffic_actor.py | MIT |
def scan_for_vehicle(
target_prefix: str,
angle_a: float,
angle_b: float,
activation_dist_squared: float,
self_vehicle_state,
other_vehicle_state,
) -> bool:
"""Sense test for another vehicle within a semi-circle range of a vehicle.
Args:
target_prefix:
The whitelist of vehicles with vehicle_ids starting with this prefix for quick elimination.
angle_a:
The minimum sweep angle between -pi and pi.
angle_b:
The maximum sweep angle between -pi and pi.
activation_dist_squared:
The distance to check for the target.
self_vehicle_state:
The vehicle state of the vehicle that is scanning.
other_vehicle_state:
The vehicle to test for.
Returns:
If the tested for vehicle is within the semi-circle range of the base vehicle.
"""
if target_prefix and not other_vehicle_state.id.startswith(target_prefix):
return False
min_angle, max_angle = min(angle_a, angle_b), max(angle_a, angle_b)
sqd = squared_dist(self_vehicle_state.position, other_vehicle_state.position)
# check for activation distance
if sqd < activation_dist_squared:
direction = np.sum(
[other_vehicle_state.position, -self_vehicle_state.position], axis=0
)
angle = Heading(vec_to_radians(direction[:2]))
rel_angle = angle.relative_to(self_vehicle_state.heading)
return min_angle <= rel_angle <= max_angle
return False | Sense test for another vehicle within a semi-circle range of a vehicle.
Args:
target_prefix:
The whitelist of vehicles with vehicle_ids starting with this prefix for quick elimination.
angle_a:
The minimum sweep angle between -pi and pi.
angle_b:
The maximum sweep angle between -pi and pi.
activation_dist_squared:
The distance to check for the target.
self_vehicle_state:
The vehicle state of the vehicle that is scanning.
other_vehicle_state:
The vehicle to test for.
Returns:
If the tested for vehicle is within the semi-circle range of the base vehicle. | scan_for_vehicle | python | huawei-noah/SMARTS | smarts/env/custom_observations.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/custom_observations.py | MIT |
def scan_for_vehicles(
target_prefix,
angle_a,
angle_b,
activation_dist_squared,
self_vehicle_state,
other_vehicle_states,
short_circuit: bool = False,
):
"""Sense test for vehicles within a semi-circle radius of a vehicle.
Args:
target_prefix:
The whitelist of vehicles with vehicle_ids starting with this prefix for quick elimination.
angle_a:
The minimum sweep angle between -pi and pi.
angle_b:
The maximum sweep angle between -pi and pi.
activation_dist_squared:
The distance to check for the target.
self_vehicle_state:
The vehicle state of the vehicle that is scanning.
other_vehicle_states:
The set of vehicles to test for.
Returns:
If the tested for vehicle is within the semi-circle range of the base vehicle.
"""
if target_prefix:
other_vehicle_states = filter(
lambda v: v.id.startswith(target_prefix), other_vehicle_states
)
min_angle, max_angle = min(angle_a, angle_b), max(angle_a, angle_b)
vehicles = []
for vehicle_state in other_vehicle_states:
sqd = squared_dist(self_vehicle_state.position, vehicle_state.position)
# check for activation distance
if sqd < activation_dist_squared:
direction = np.sum(
[vehicle_state.position, -self_vehicle_state.position], axis=0
)
angle = Heading(vec_to_radians(direction[:2]))
rel_angle = angle.relative_to(self_vehicle_state.heading)
if min_angle <= rel_angle <= max_angle:
vehicles.append(vehicle_state)
if short_circuit:
break
return vehicles | Sense test for vehicles within a semi-circle radius of a vehicle.
Args:
target_prefix:
The whitelist of vehicles with vehicle_ids starting with this prefix for quick elimination.
angle_a:
The minimum sweep angle between -pi and pi.
angle_b:
The maximum sweep angle between -pi and pi.
activation_dist_squared:
The distance to check for the target.
self_vehicle_state:
The vehicle state of the vehicle that is scanning.
other_vehicle_states:
The set of vehicles to test for.
Returns:
If the tested for vehicle is within the semi-circle range of the base vehicle. | scan_for_vehicles | python | huawei-noah/SMARTS | smarts/env/custom_observations.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/custom_observations.py | MIT |
def lane_ttc(obs: Union[Observation, Dict]) -> Dict[str, np.ndarray]:
"""Computes time-to-collision (TTC) and distance-to-collision (DTC) using
the given agent's observation. TTC and DTC are numpy arrays of shape (3,)
with values for the right lane (at index [0]), current lane (at index [1]),
and left lane (at index [2]).
Args:
obs (Observation): Agent observation.
Returns:
Returns a dictionary with the following key value mapping.
+ distance_from_center: Distance to lane center. Shape=(1,).
+ angle_error: Ego heading relative to the closest waypoint. Shape=(1,).
+ speed: Ego speed. Shape=(1,).
+ steering: Ego steering. Shape=(1,).
+ :spelling:ignore:`ego_ttc`: Time to collision in each lane. Shape=(3,).
+ ego_lane_dist: Closest cars’ distance to ego in each lane. Shape=(3,).
"""
if isinstance(obs, Observation):
ego = obs.ego_vehicle_state
waypoint_paths = obs.waypoint_paths
wps = [path[0] for path in waypoint_paths]
neighborhood_vehicle_states = obs.neighborhood_vehicle_states
elif isinstance(obs, dict):
waypoint_paths = obs["waypoint_paths"]
waypoint_paths = [
[
Waypoint(
position[:2],
Heading(heading),
lane_id,
lane_width,
speed_limit,
lane_index,
np.nan,
)
for position, heading, lane_id, lane_width, speed_limit, lane_index in zip(
waypoint_paths["position"][i],
waypoint_paths["heading"][i],
waypoint_paths["lane_id"][i],
waypoint_paths["lane_width"][i],
waypoint_paths["speed_limit"][i],
waypoint_paths["lane_index"][i],
)
]
for i in range(4)
]
wps = [path[0] for path in waypoint_paths]
evs = obs["ego_vehicle_state"]
ego = _VehicleState(
speed=evs["speed"],
position=evs["position"],
lane_index=evs["lane_index"],
heading=Heading(evs["heading"]),
lane_id=evs["lane_id"],
steering=evs["steering"],
)
neighborhood_vehicle_states_dict = obs["neighborhood_vehicle_states"]
neighborhood_vehicle_states = [
_VehicleState(
position=position,
heading=heading,
speed=speed,
lane_id=lane_id,
lane_index=lane_index,
steering=np.nan,
)
for position, heading, speed, lane_id, lane_index in zip(
neighborhood_vehicle_states_dict["position"],
neighborhood_vehicle_states_dict["heading"],
neighborhood_vehicle_states_dict["speed"],
neighborhood_vehicle_states_dict["lane_id"],
neighborhood_vehicle_states_dict["lane_index"],
)
]
else:
raise NotImplementedError("Cannot generate using given observations")
# distance of vehicle from center of lane
closest_wp = min(wps, key=lambda wp: wp.dist_to(ego.position))
signed_dist_from_center = closest_wp.signed_lateral_error(ego.position)
lane_half_width = closest_wp.lane_width * 0.5
norm_dist_from_center = signed_dist_from_center / lane_half_width
ego_ttc, ego_lane_dist = _ego_ttc_lane_dist(
ego, neighborhood_vehicle_states, waypoint_paths, closest_wp.lane_index
)
return {
"distance_from_center": np.array([norm_dist_from_center]),
"angle_error": np.array([closest_wp.relative_heading(ego.heading)]),
"speed": np.array([ego.speed]),
"steering": np.array([ego.steering]),
"ego_ttc": np.array(ego_ttc),
"ego_lane_dist": np.array(ego_lane_dist),
} | Computes time-to-collision (TTC) and distance-to-collision (DTC) using
the given agent's observation. TTC and DTC are numpy arrays of shape (3,)
with values for the right lane (at index [0]), current lane (at index [1]),
and left lane (at index [2]).
Args:
obs (Observation): Agent observation.
Returns:
Returns a dictionary with the following key value mapping.
+ distance_from_center: Distance to lane center. Shape=(1,).
+ angle_error: Ego heading relative to the closest waypoint. Shape=(1,).
+ speed: Ego speed. Shape=(1,).
+ steering: Ego steering. Shape=(1,).
+ :spelling:ignore:`ego_ttc`: Time to collision in each lane. Shape=(3,).
+ ego_lane_dist: Closest cars’ distance to ego in each lane. Shape=(3,). | lane_ttc | python | huawei-noah/SMARTS | smarts/env/custom_observations.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/custom_observations.py | MIT |
def step(self, agent_actions):
"""Environment step"""
agent_actions = {
agent_id: self._agent_specs[agent_id].action_adapter(action)
for agent_id, action in agent_actions.items()
}
assert isinstance(agent_actions, dict) and all(
isinstance(key, str) for key in agent_actions.keys()
), "Expected Dict[str, any]"
formatted_actions = self._action_formatter.format(agent_actions)
env_observations, rewards, dones, extras = self._smarts.step(formatted_actions)
env_observations = self._observations_formatter.format(env_observations)
# Agent termination: RLlib expects that we return a "last observation"
# on the step that an agent transitions to "done". All subsequent calls
# to env.step(..) will no longer contain actions from the "done" agent.
#
# The way we implement this behavior here is to rely on the presence of
# agent actions to filter out all environment observations/rewards/infos
# to only agents who are actively sending in actions.
observations = {
agent_id: obs
for agent_id, obs in env_observations.items()
if agent_id in formatted_actions
}
rewards = {
agent_id: reward
for agent_id, reward in rewards.items()
if agent_id in formatted_actions
}
scores = {
agent_id: score
for agent_id, score in extras["scores"].items()
if agent_id in formatted_actions
}
infos = {
agent_id: {
"score": value,
"reward": rewards[agent_id],
"speed": observations[agent_id]["ego_vehicle_state"]["speed"],
}
for agent_id, value in scores.items()
}
# Ensure all contain the same agent_ids as keys
assert (
agent_actions.keys()
== observations.keys()
== rewards.keys()
== infos.keys()
)
for agent_id in agent_actions:
agent_spec = self._agent_specs[agent_id]
observation = env_observations[agent_id]
reward = rewards[agent_id]
info = infos[agent_id]
observations[agent_id] = agent_spec.observation_adapter(observation)
rewards[agent_id] = agent_spec.reward_adapter(observation, reward)
infos[agent_id] = agent_spec.info_adapter(observation, reward, info)
for done in dones.values():
self._dones_registered += 1 if done else 0
dones["__all__"] = self._dones_registered >= len(self._agent_specs)
return (
observations,
rewards,
dones,
dones,
infos,
) | Environment step | step | python | huawei-noah/SMARTS | smarts/env/rllib_hiway_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/rllib_hiway_env.py | MIT |
def reset(self, *, seed=None, options=None):
"""Environment reset."""
if seed not in (None, 0):
smarts.core.seed(self._seed + (seed or 0))
scenario = next(self._scenarios_iterator)
self._dones_registered = 0
if self._smarts is None:
self._smarts = self._build_smarts()
self._smarts.setup(scenario=scenario)
env_observations = self._smarts.reset(scenario=scenario)
env_observations = self._observations_formatter.format(
observations=env_observations
)
observations = {
agent_id: self._agent_specs[agent_id].observation_adapter(obs)
for agent_id, obs in env_observations.items()
}
info = {
agent_id: {
"score": 0,
"reward": 0,
"env_obs": agent_obs,
"done": False,
"map_source": self._smarts.scenario.road_map.source,
}
for agent_id, agent_obs in observations.items()
}
return observations, info | Environment reset. | reset | python | huawei-noah/SMARTS | smarts/env/rllib_hiway_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/rllib_hiway_env.py | MIT |
def close(self):
"""Environment close."""
if self._smarts is not None:
self._smarts.destroy() | Environment close. | close | python | huawei-noah/SMARTS | smarts/env/rllib_hiway_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/rllib_hiway_env.py | MIT |
def test_graceful_shutdown():
"""SMARTS should not throw any exceptions when shutdown."""
agent_spec = AgentSpec(
interface=AgentInterface.from_type(AgentType.Laner),
agent_builder=lambda: Agent.from_function(lambda _: "keep_lane"),
)
env = build_env(agent_spec)
agent = agent_spec.build_agent()
obs, _ = env.reset()
for _ in range(10):
obs, _, _, _, _ = env.step({AGENT_ID: agent.act(obs)})
env.close() | SMARTS should not throw any exceptions when shutdown. | test_graceful_shutdown | python | huawei-noah/SMARTS | smarts/env/tests/test_shutdown.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/tests/test_shutdown.py | MIT |
def test_graceful_interrupt(monkeypatch):
"""SMARTS should only throw a KeyboardInterript exception."""
agent_spec = AgentSpec(
interface=AgentInterface.from_type(AgentType.Laner),
agent_builder=lambda: Agent.from_function(lambda _: "keep_lane"),
)
agent = agent_spec.build_agent()
env = build_env(agent_spec)
with pytest.raises(KeyboardInterrupt):
obs, _ = env.reset()
episode = 0
# To simulate a user interrupting the sim (e.g. ctrl-c). We just need to
# hook in to some function that SMARTS calls internally (like this one).
with mock.patch(
"smarts.core.sensor_manager.SensorManager.observe",
side_effect=KeyboardInterrupt,
):
for episode in range(10):
obs, _, _, _, _ = env.step({AGENT_ID: agent.act(obs)})
assert episode == 0, "SMARTS should have been interrupted, ending early"
with pytest.raises(SMARTSNotSetupError):
env.step({AGENT_ID: agent.act(obs)}) | SMARTS should only throw a KeyboardInterript exception. | test_graceful_interrupt | python | huawei-noah/SMARTS | smarts/env/tests/test_shutdown.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/tests/test_shutdown.py | MIT |
def platoon_env(
scenario: str,
agent_interface: AgentInterface,
seed: int = 42,
headless: bool = True,
sumo_headless: bool = True,
envision_record_data_replay_path: Optional[str] = None,
):
"""All ego agents should track and follow the leader (i.e., lead vehicle) in a
single-file fashion. The lead vehicle is marked as a vehicle of interest
and may be found by filtering the
:attr:`~smarts.core.observations.VehicleObservation.interest` attribute of
the neighborhood vehicles in the observation. The episode ends when the
leader reaches its destination. Ego agents do not have prior knowledge of the
leader's destination.
Observation space for each agent:
Formatted :class:`~smarts.core.observations.Observation` using
:attr:`~smarts.env.utils.observation_conversion.ObservationOptions.multi_agent`
option is returned as observation. See
:class:`~smarts.env.utils.observation_conversion.ObservationSpacesFormatter` for
a sample formatted observation data structure.
Action space for each agent:
Action space for an ego can be either :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.Continuous`
or :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`. User should choose
one of the action spaces and specify the chosen action space through the ego's agent interface.
Agent interface:
Using the input argument agent_interface, users may configure any field of
:class:`~smarts.core.agent_interface.AgentInterface`, except
+ :attr:`~smarts.core.agent_interface.AgentInterface.accelerometer`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.done_criteria`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.max_episode_steps`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.neighborhood_vehicle_states`, and
+ :attr:`~smarts.core.agent_interface.AgentInterface.waypoint_paths`.
Reward:
Default reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Lead vehicle reaches its pre-programmed destination.
2. Steps per episode exceed 1000.
3. Agent collides or drives off road.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
seed (int, optional): Random number generator seed. Defaults to 42.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`.
"""
# Check for supported action space
assert agent_interface.action in SUPPORTED_ACTION_TYPES, (
f"Got unsupported action type `{agent_interface.action}`, which is not "
f"in supported action types `{SUPPORTED_ACTION_TYPES}`."
)
# Build scenario
env_specs = get_scenario_specs(scenario)
build_scenario(scenario=env_specs["scenario"])
# Resolve agent interface
resolved_agent_interface = resolve_agent_interface(agent_interface)
agent_interfaces = {
f"Agent_{i}": resolved_agent_interface for i in range(env_specs["num_agent"])
}
visualization_client_builder = None
if not headless:
visualization_client_builder = partial(
Envision,
endpoint=None,
output_dir=envision_record_data_replay_path,
headless=headless,
data_formatter_args=EnvisionDataFormatterArgs(
"base", enable_reduction=False
),
)
env = HiWayEnvV1(
scenarios=[env_specs["scenario"]],
agent_interfaces=agent_interfaces,
sim_name="VehicleFollowing",
headless=headless,
seed=seed,
sumo_options=SumoOptions(headless=sumo_headless),
visualization_client_builder=visualization_client_builder,
observation_options=ObservationOptions.multi_agent,
)
if resolved_agent_interface.action == ActionSpaceType.RelativeTargetPose:
env = LimitRelativeTargetPose(env)
return env | All ego agents should track and follow the leader (i.e., lead vehicle) in a
single-file fashion. The lead vehicle is marked as a vehicle of interest
and may be found by filtering the
:attr:`~smarts.core.observations.VehicleObservation.interest` attribute of
the neighborhood vehicles in the observation. The episode ends when the
leader reaches its destination. Ego agents do not have prior knowledge of the
leader's destination.
Observation space for each agent:
Formatted :class:`~smarts.core.observations.Observation` using
:attr:`~smarts.env.utils.observation_conversion.ObservationOptions.multi_agent`
option is returned as observation. See
:class:`~smarts.env.utils.observation_conversion.ObservationSpacesFormatter` for
a sample formatted observation data structure.
Action space for each agent:
Action space for an ego can be either :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.Continuous`
or :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`. User should choose
one of the action spaces and specify the chosen action space through the ego's agent interface.
Agent interface:
Using the input argument agent_interface, users may configure any field of
:class:`~smarts.core.agent_interface.AgentInterface`, except
+ :attr:`~smarts.core.agent_interface.AgentInterface.accelerometer`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.done_criteria`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.max_episode_steps`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.neighborhood_vehicle_states`, and
+ :attr:`~smarts.core.agent_interface.AgentInterface.waypoint_paths`.
Reward:
Default reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Lead vehicle reaches its pre-programmed destination.
2. Steps per episode exceed 1000.
3. Agent collides or drives off road.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
seed (int, optional): Random number generator seed. Defaults to 42.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`. | platoon_env | python | huawei-noah/SMARTS | smarts/env/gymnasium/platoon_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/platoon_env.py | MIT |
def resolve_agent_interface(agent_interface: AgentInterface):
"""Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed.
"""
done_criteria = DoneCriteria(
collision=True,
off_road=True,
off_route=False,
on_shoulder=False,
wrong_way=False,
not_moving=False,
agents_alive=None,
interest=InterestDoneCriteria(
include_scenario_marked=True,
strict=True,
),
)
max_episode_steps = 1000
waypoints_lookahead = 80
neighborhood_radius = 80
return AgentInterface(
accelerometer=True,
action=agent_interface.action,
done_criteria=done_criteria,
drivable_area_grid_map=agent_interface.drivable_area_grid_map,
lane_positions=agent_interface.lane_positions,
lidar_point_cloud=agent_interface.lidar_point_cloud,
max_episode_steps=max_episode_steps,
neighborhood_vehicle_states=NeighborhoodVehicles(radius=neighborhood_radius),
occupancy_grid_map=agent_interface.occupancy_grid_map,
top_down_rgb=agent_interface.top_down_rgb,
road_waypoints=agent_interface.road_waypoints,
waypoint_paths=Waypoints(lookahead=waypoints_lookahead),
signals=agent_interface.signals,
) | Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed. | resolve_agent_interface | python | huawei-noah/SMARTS | smarts/env/gymnasium/platoon_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/platoon_env.py | MIT |
def reset(
self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None
) -> Tuple[ObsType, Dict[str, Any]]:
"""Resets the environment to an initial internal state, returning an initial observation and info.
This method generates a new starting state often with some randomness to ensure that the agent explores the
state space and learns a generalized policy about the environment. This randomness can be controlled
with the ``seed`` parameter otherwise if the environment already has a random number generator and
:meth:`reset` is called with ``seed=None``, the RNG is not reset.
Therefore, :meth:`reset` should (in the typical use case) be called with a seed right after initialization and then never again.
Args:
seed (int, optional): The seed that is used to initialize the environment's PRNG (`np_random`).
If the environment does not already have a PRNG and ``seed=None`` (the default option) is passed,
a seed will be chosen from some source of entropy (e.g. timestamp or `/dev/urandom`).
However, if the environment already has a PRNG and ``seed=None`` is passed, the PRNG will *not* be reset.
If you pass an integer, the PRNG will be reset even if it already exists.
Usually, you want to pass an integer *right after the environment has been initialized and then never again*.
options (dict, optional): Additional information to specify how the environment is reset (optional,
depending on the specific environment). Forwards to :meth:`~smarts.core.smarts.SMARTS.reset`.
- "scenario" (:class:`~smarts.sstudio.sstypes.scenario.Scenario`): An explicit scenario to reset to. The default is a scenario from the scenario iter.
- "start_time" (float): Forwards the start time of the current scenario. The default is 0.
Returns:
dict: observation. Observation of the initial state. This will be an element of :attr:`observation_space`
and is analogous to the observation returned by :meth:`step`.
dict: info. This dictionary contains auxiliary information complementing ``observation``. It should be analogous to
the ``info`` returned by :meth:`step`.
"""
super().reset(seed=seed, options=options)
options = options or {}
scenario = options.get("scenario")
if scenario is None:
scenario = next(self._scenarios_iterator)
self._dones_registered = 0
observations = self._smarts.reset(
scenario, start_time=options.get("start_time", 0)
)
info = {
agent_id: {
"score": 0,
"env_obs": agent_obs,
"done": False,
"reward": 0,
"map_source": self._smarts.scenario.road_map.source,
}
for agent_id, agent_obs in observations.items()
}
if self._env_renderer is not None:
self._env_renderer.reset(observations)
if seed is not None:
smarts_seed(seed)
return self._observations_formatter.format(observations), info | Resets the environment to an initial internal state, returning an initial observation and info.
This method generates a new starting state often with some randomness to ensure that the agent explores the
state space and learns a generalized policy about the environment. This randomness can be controlled
with the ``seed`` parameter otherwise if the environment already has a random number generator and
:meth:`reset` is called with ``seed=None``, the RNG is not reset.
Therefore, :meth:`reset` should (in the typical use case) be called with a seed right after initialization and then never again.
Args:
seed (int, optional): The seed that is used to initialize the environment's PRNG (`np_random`).
If the environment does not already have a PRNG and ``seed=None`` (the default option) is passed,
a seed will be chosen from some source of entropy (e.g. timestamp or `/dev/urandom`).
However, if the environment already has a PRNG and ``seed=None`` is passed, the PRNG will *not* be reset.
If you pass an integer, the PRNG will be reset even if it already exists.
Usually, you want to pass an integer *right after the environment has been initialized and then never again*.
options (dict, optional): Additional information to specify how the environment is reset (optional,
depending on the specific environment). Forwards to :meth:`~smarts.core.smarts.SMARTS.reset`.
- "scenario" (:class:`~smarts.sstudio.sstypes.scenario.Scenario`): An explicit scenario to reset to. The default is a scenario from the scenario iter.
- "start_time" (float): Forwards the start time of the current scenario. The default is 0.
Returns:
dict: observation. Observation of the initial state. This will be an element of :attr:`observation_space`
and is analogous to the observation returned by :meth:`step`.
dict: info. This dictionary contains auxiliary information complementing ``observation``. It should be analogous to
the ``info`` returned by :meth:`step`. | reset | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def render(
self,
) -> Optional[Union[gym.core.RenderFrame, List[gym.core.RenderFrame]]]:
"""Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment.
The environment's :attr:`metadata` render modes (`env.metadata["render_modes"]`) should contain the possible
ways to implement the render modes. In addition, list versions for most render modes is achieved through
`gymnasium.make` which automatically applies a wrapper to collect rendered frames.
Note:
As the :attr:`render_mode` is known during ``__init__``, the objects used to render the environment state
should be initialized in ``__init__``.
By convention, if the :attr:`render_mode` is:
- None (default): no render is computed.
- `human`: The environment is continuously rendered in the current display or terminal,
usually for human consumption. This rendering should occur during :meth:`step` and
:meth:`render` doesn't need to be called. Returns ``None``.
- `rgb_array`: Return a single frame representing the current state of the environment.
A frame is a ``np.ndarray`` with shape ``(x, y, 3)`` representing RGB values for
an x-by-y pixel image.
- `ansi`: Return a strings (``str``) or ``StringIO.StringIO`` containing a
terminal-style text representation for each time step. The text can include
newlines and ANSI escape sequences (e.g. for colors).
- `rgb_array_list` and `ansi_list`: List based version of render modes are possible
(except Human) through the wrapper, :py:class:`gymnasium.wrappers.RenderCollection`
that is automatically applied during ``gymnasium.make(..., render_mode="rgb_array_list")``.
The frames collected are popped after :meth:`render` is called or :meth:`reset`.
Note:
Make sure that your class's :attr:`metadata` ``"render_modes"`` key includes the list of supported modes.
"""
if self.render_mode == "rgb_array":
if self._env_renderer is None:
from smarts.env.utils.record import AgentCameraRGBRender
self._env_renderer = AgentCameraRGBRender(self)
return self._env_renderer.render(env=self) | Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment.
The environment's :attr:`metadata` render modes (`env.metadata["render_modes"]`) should contain the possible
ways to implement the render modes. In addition, list versions for most render modes is achieved through
`gymnasium.make` which automatically applies a wrapper to collect rendered frames.
Note:
As the :attr:`render_mode` is known during ``__init__``, the objects used to render the environment state
should be initialized in ``__init__``.
By convention, if the :attr:`render_mode` is:
- None (default): no render is computed.
- `human`: The environment is continuously rendered in the current display or terminal,
usually for human consumption. This rendering should occur during :meth:`step` and
:meth:`render` doesn't need to be called. Returns ``None``.
- `rgb_array`: Return a single frame representing the current state of the environment.
A frame is a ``np.ndarray`` with shape ``(x, y, 3)`` representing RGB values for
an x-by-y pixel image.
- `ansi`: Return a strings (``str``) or ``StringIO.StringIO`` containing a
terminal-style text representation for each time step. The text can include
newlines and ANSI escape sequences (e.g. for colors).
- `rgb_array_list` and `ansi_list`: List based version of render modes are possible
(except Human) through the wrapper, :py:class:`gymnasium.wrappers.RenderCollection`
that is automatically applied during ``gymnasium.make(..., render_mode="rgb_array_list")``.
The frames collected are popped after :meth:`render` is called or :meth:`reset`.
Note:
Make sure that your class's :attr:`metadata` ``"render_modes"`` key includes the list of supported modes. | render | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def close(self):
"""After the user has finished using the environment, close contains the code necessary to "clean up" the environment.
This is critical for closing rendering windows, database or HTTP connections.
"""
if self._smarts is not None:
self._smarts.destroy() | After the user has finished using the environment, close contains the code necessary to "clean up" the environment.
This is critical for closing rendering windows, database or HTTP connections. | close | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def unwrapped(self) -> gym.Env[ObsType, ActType]:
"""Returns the base non-wrapped environment.
Returns:
gym.Env: The base non-wrapped :class:`gymnasium.Env` instance
"""
return self | Returns the base non-wrapped environment.
Returns:
gym.Env: The base non-wrapped :class:`gymnasium.Env` instance | unwrapped | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def np_random(self) -> np.random.Generator:
"""Returns the environment's internal random number generator that if not set will initialize with a random seed.
Returns:
The internal instance of :class:`np.random.Generator`.
"""
return super().np_random | Returns the environment's internal random number generator that if not set will initialize with a random seed.
Returns:
The internal instance of :class:`np.random.Generator`. | np_random | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def __str__(self):
"""Returns a string of the environment with :attr:`spec` id's if :attr:`spec`.
Returns:
A string identifying the environment.
"""
return super().__str__() | Returns a string of the environment with :attr:`spec` id's if :attr:`spec`.
Returns:
A string identifying the environment. | __str__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def __enter__(self):
"""Support with-statement for the environment."""
return super().__enter__() | Support with-statement for the environment. | __enter__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def __exit__(self, *args: Any):
"""Support with-statement for the environment and closes the environment."""
self.close()
# propagate exception
return False | Support with-statement for the environment and closes the environment. | __exit__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def agent_ids(self) -> Set[str]:
"""Agent ids of all agents that potentially will be in the environment.
Returns:
(Set[str]): Agent ids.
"""
return set(self._agent_interfaces) | Agent ids of all agents that potentially will be in the environment.
Returns:
(Set[str]): Agent ids. | agent_ids | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def agent_interfaces(self) -> Dict[str, AgentInterface]:
"""Agent interfaces used for the environment.
Returns:
(Dict[str, AgentInterface]):
Agent interface defining the agents affect on the observation and action spaces
of this environment.
"""
return self._agent_interfaces | Agent interfaces used for the environment.
Returns:
(Dict[str, AgentInterface]):
Agent interface defining the agents affect on the observation and action spaces
of this environment. | agent_interfaces | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def scenario_log(self) -> Dict[str, Union[float, str]]:
"""Simulation steps log.
Returns:
(Dict[str, Union[float,str]]): A dictionary with the following keys.
`fixed_timestep_sec` - Simulation time-step.
`scenario_map` - Name of the current scenario.
`scenario_traffic` - Traffic spec(s) used.
`mission_hash` - Hash identifier for the current scenario.
"""
scenario = self._smarts.scenario
return {
"fixed_timestep_sec": self._smarts.fixed_timestep_sec,
"scenario_map": scenario.name,
"scenario_traffic": ",".join(map(os.path.basename, scenario.traffic_specs)),
"mission_hash": str(hash(frozenset(scenario.missions.items()))),
} | Simulation steps log.
Returns:
(Dict[str, Union[float,str]]): A dictionary with the following keys.
`fixed_timestep_sec` - Simulation time-step.
`scenario_map` - Name of the current scenario.
`scenario_traffic` - Traffic spec(s) used.
`mission_hash` - Hash identifier for the current scenario. | scenario_log | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def smarts(self):
"""Gives access to the underlying simulator. Use this carefully.
Returns:
smarts.core.smarts.SMARTS: The smarts simulator instance.
"""
return self._smarts | Gives access to the underlying simulator. Use this carefully.
Returns:
smarts.core.smarts.SMARTS: The smarts simulator instance. | smarts | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def seed(self):
"""Returns the environment seed.
Returns:
int: Environment seed.
"""
return current_seed() | Returns the environment seed.
Returns:
int: Environment seed. | seed | python | huawei-noah/SMARTS | smarts/env/gymnasium/hiway_env_v1.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/hiway_env_v1.py | MIT |
def driving_smarts_2023_env(
scenario: str,
agent_interface: AgentInterface,
seed: int = 42,
headless: bool = True,
sumo_headless: bool = True,
envision_record_data_replay_path: Optional[str] = None,
):
"""An environment with a mission to be completed by a single or multiple
ego agents. Episode ends when ego agents reach their respective destinations
specified by their mission goals.
Observation space for each agent:
Formatted :class:`~smarts.core.observations.Observation` using
:attr:`~smarts.env.utils.observation_conversion.ObservationOptions.multi_agent`
option is returned as observation. See
:class:`~smarts.env.utils.observation_conversion.ObservationSpacesFormatter` for
a sample formatted observation data structure.
Action space for each agent:
Action space for an ego can be either :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.Continuous`
or :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`. User should choose
one of the action spaces and specify the chosen action space through the ego's agent interface.
Agent interface:
Using the input argument agent_interface, users may configure any field of
:class:`~smarts.core.agent_interface.AgentInterface`, except
+ :attr:`~smarts.core.agent_interface.AgentInterface.accelerometer`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.done_criteria`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.max_episode_steps`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.neighborhood_vehicle_states`, and
+ :attr:`~smarts.core.agent_interface.AgentInterface.waypoint_paths`.
Reward:
Default reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Egos reach their respective destinations specified by their mission goals.
2. Steps per episode exceed 1000.
3. Agent collides or drives off road.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
seed (int, optional): Random number generator seed. Defaults to 42.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`.
"""
# Check for supported action space
assert agent_interface.action in SUPPORTED_ACTION_TYPES, (
f"Got unsupported action type `{agent_interface.action}`, which is not "
f"in supported action types `{SUPPORTED_ACTION_TYPES}`."
)
# Build scenario
env_specs = get_scenario_specs(scenario)
build_scenario(scenario=env_specs["scenario"])
# Resolve agent interface
resolved_agent_interface = resolve_agent_interface(agent_interface)
agent_interfaces = {
f"Agent_{i}": resolved_agent_interface for i in range(env_specs["num_agent"])
}
visualization_client_builder = None
if not headless:
visualization_client_builder = partial(
Envision,
endpoint=None,
output_dir=envision_record_data_replay_path,
headless=headless,
data_formatter_args=EnvisionDataFormatterArgs(
"base", enable_reduction=False
),
)
env = HiWayEnvV1(
scenarios=[env_specs["scenario"]],
agent_interfaces=agent_interfaces,
sim_name="Driving_Smarts_2023",
headless=headless,
seed=seed,
sumo_options=SumoOptions(headless=sumo_headless),
visualization_client_builder=visualization_client_builder,
observation_options=ObservationOptions.multi_agent,
)
if resolved_agent_interface.action == ActionSpaceType.RelativeTargetPose:
env = LimitRelativeTargetPose(env)
return env | An environment with a mission to be completed by a single or multiple
ego agents. Episode ends when ego agents reach their respective destinations
specified by their mission goals.
Observation space for each agent:
Formatted :class:`~smarts.core.observations.Observation` using
:attr:`~smarts.env.utils.observation_conversion.ObservationOptions.multi_agent`
option is returned as observation. See
:class:`~smarts.env.utils.observation_conversion.ObservationSpacesFormatter` for
a sample formatted observation data structure.
Action space for each agent:
Action space for an ego can be either :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.Continuous`
or :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`. User should choose
one of the action spaces and specify the chosen action space through the ego's agent interface.
Agent interface:
Using the input argument agent_interface, users may configure any field of
:class:`~smarts.core.agent_interface.AgentInterface`, except
+ :attr:`~smarts.core.agent_interface.AgentInterface.accelerometer`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.done_criteria`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.max_episode_steps`,
+ :attr:`~smarts.core.agent_interface.AgentInterface.neighborhood_vehicle_states`, and
+ :attr:`~smarts.core.agent_interface.AgentInterface.waypoint_paths`.
Reward:
Default reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Egos reach their respective destinations specified by their mission goals.
2. Steps per episode exceed 1000.
3. Agent collides or drives off road.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
seed (int, optional): Random number generator seed. Defaults to 42.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`. | driving_smarts_2023_env | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2023_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2023_env.py | MIT |
def resolve_agent_interface(agent_interface: AgentInterface):
"""Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed.
"""
done_criteria = DoneCriteria(
collision=True,
off_road=True,
off_route=False,
on_shoulder=False,
wrong_way=False,
not_moving=False,
agents_alive=None,
interest=None,
)
max_episode_steps = 1000
waypoints_lookahead = 80
neighborhood_radius = 80
return AgentInterface(
accelerometer=True,
action=agent_interface.action,
done_criteria=done_criteria,
drivable_area_grid_map=agent_interface.drivable_area_grid_map,
lane_positions=agent_interface.lane_positions,
lidar_point_cloud=agent_interface.lidar_point_cloud,
max_episode_steps=max_episode_steps,
neighborhood_vehicle_states=NeighborhoodVehicles(radius=neighborhood_radius),
occupancy_grid_map=agent_interface.occupancy_grid_map,
top_down_rgb=agent_interface.top_down_rgb,
road_waypoints=agent_interface.road_waypoints,
waypoint_paths=Waypoints(lookahead=waypoints_lookahead),
signals=agent_interface.signals,
) | Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed. | resolve_agent_interface | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2023_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2023_env.py | MIT |
def driving_smarts_2022_env(
scenario: str,
agent_interface: AgentInterface,
headless: bool = True,
seed: int = 42,
visdom: bool = False,
sumo_headless: bool = True,
envision_record_data_replay_path: Optional[str] = None,
):
"""An environment with a mission to be completed by a single or multiple ego agents.
Observation space for each agent:
An unformatted :class:`~smarts.core.observations.Observation` is returned as observation.
Action space for each agent:
Action space for each agent is configured through its `AgentInterface`.
The action space could be either of the following.
(i) :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`
+------------------------------------+-------------+-------+
| Action | Values | Units |
+====================================+=============+=======+
| Δx-coordinate | [-2.8, 2.8] | m |
+------------------------------------+-------------+-------+
| Δy-coordinate | [-2.8, 2.8] | m |
+------------------------------------+-------------+-------+
| Δheading | [-π, π] | rad |
+------------------------------------+-------------+-------+
(ii) :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.TargetPose`
+------------------------------------+---------------+-------+
| Action | Values | Units |
+====================================+===============+=======+
| Next x-coordinate | [-1e10, 1e10] | m |
+------------------------------------+---------------+-------+
| Next y-coordinate | [-1e10, 1e10] | m |
+------------------------------------+---------------+-------+
| Heading with respect to map's axes | [-π, π] | rad |
+------------------------------------+---------------+-------+
| ΔTime | 0.1 | s |
+------------------------------------+---------------+-------+
Reward:
Reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Steps per episode exceed 800.
2. Agent collides, drives off road, drives off route, or drives on wrong way.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
seed (int, optional): Random number generator seed. Defaults to 42.
visdom (bool, optional): If True, enables visualization of observed
RGB images in `visdom`. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`.
"""
env_specs = get_scenario_specs(scenario)
build_scenario(scenario=env_specs["scenario"])
resolved_agent_interface = resolve_agent_interface(agent_interface)
agent_interfaces = {
f"Agent_{i}": resolved_agent_interface for i in range(env_specs["num_agent"])
}
env_action_space = resolve_env_action_space(agent_interfaces)
visualization_client_builder = None
if not headless:
visualization_client_builder = partial(
Envision,
endpoint=None,
output_dir=envision_record_data_replay_path,
headless=headless,
data_formatter_args=EnvisionDataFormatterArgs(
"base", enable_reduction=False
),
)
env = HiWayEnvV1(
scenarios=[env_specs["scenario"]],
agent_interfaces=agent_interfaces,
sim_name="Driving_SMARTS_v0",
headless=headless,
visdom=visdom,
fixed_timestep_sec=0.1,
seed=seed,
sumo_options=SumoOptions(headless=sumo_headless),
visualization_client_builder=visualization_client_builder,
observation_options=ObservationOptions.unformatted,
)
env.action_space = env_action_space
if resolved_agent_interface.action == ActionSpaceType.TargetPose:
env = _LimitTargetPose(env)
return env | An environment with a mission to be completed by a single or multiple ego agents.
Observation space for each agent:
An unformatted :class:`~smarts.core.observations.Observation` is returned as observation.
Action space for each agent:
Action space for each agent is configured through its `AgentInterface`.
The action space could be either of the following.
(i) :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.RelativeTargetPose`
+------------------------------------+-------------+-------+
| Action | Values | Units |
+====================================+=============+=======+
| Δx-coordinate | [-2.8, 2.8] | m |
+------------------------------------+-------------+-------+
| Δy-coordinate | [-2.8, 2.8] | m |
+------------------------------------+-------------+-------+
| Δheading | [-π, π] | rad |
+------------------------------------+-------------+-------+
(ii) :attr:`~smarts.core.controllers.action_space_type.ActionSpaceType.TargetPose`
+------------------------------------+---------------+-------+
| Action | Values | Units |
+====================================+===============+=======+
| Next x-coordinate | [-1e10, 1e10] | m |
+------------------------------------+---------------+-------+
| Next y-coordinate | [-1e10, 1e10] | m |
+------------------------------------+---------------+-------+
| Heading with respect to map's axes | [-π, π] | rad |
+------------------------------------+---------------+-------+
| ΔTime | 0.1 | s |
+------------------------------------+---------------+-------+
Reward:
Reward is distance travelled (in meters) in each step, including the termination step.
Episode termination:
Episode is terminated if any of the following occurs.
1. Steps per episode exceed 800.
2. Agent collides, drives off road, drives off route, or drives on wrong way.
Args:
scenario (str): Scenario name or path to scenario folder.
agent_interface (AgentInterface): Agent interface specification.
headless (bool, optional): If True, disables visualization in
Envision. Defaults to False.
seed (int, optional): Random number generator seed. Defaults to 42.
visdom (bool, optional): If True, enables visualization of observed
RGB images in `visdom`. Defaults to False.
sumo_headless (bool, optional): If True, disables visualization in
SUMO GUI. Defaults to True.
envision_record_data_replay_path (Optional[str], optional):
Envision's data replay output directory. Defaults to None.
Returns:
An environment described by the input argument `scenario`. | driving_smarts_2022_env | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def resolve_agent_action_space(agent_interface: AgentInterface):
"""Get the competition action space for the given agent interface."""
assert (
agent_interface.action in SUPPORTED_ACTION_TYPES
), f"Unsupported action type `{agent_interface.action}` not in supported actions `{SUPPORTED_ACTION_TYPES}`"
if agent_interface.action == ActionSpaceType.RelativeTargetPose:
max_dist = MAXIMUM_SPEED_MPS * 0.1 # assumes 0.1 timestep
return gym.spaces.Box(
low=np.array([-max_dist, -max_dist, -np.pi]),
high=np.array([max_dist, max_dist, np.pi]),
dtype=np.float32,
)
if agent_interface.action == ActionSpaceType.TargetPose:
return gym.spaces.Box(
low=np.array([-1e10, -1e10, -np.pi, 0.1]),
high=np.array([1e10, 1e10, np.pi, 0.1]),
dtype=np.float32,
) | Get the competition action space for the given agent interface. | resolve_agent_action_space | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def resolve_env_action_space(agent_interfaces: Dict[str, AgentInterface]):
"""Get the environment action space for the given set of agent interfaces."""
return gym.spaces.Dict(
{
a_id: resolve_agent_action_space(a_inter)
for a_id, a_inter in agent_interfaces.items()
}
) | Get the environment action space for the given set of agent interfaces. | resolve_env_action_space | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def resolve_agent_interface(agent_interface: AgentInterface):
"""Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed.
"""
done_criteria = DoneCriteria(
collision=True,
off_road=True,
off_route=False,
on_shoulder=False,
wrong_way=False,
not_moving=False,
agents_alive=None,
)
max_episode_steps = 800
road_waypoint_horizon = 50
waypoints_lookahead = 50
return AgentInterface(
accelerometer=True,
action=agent_interface.action,
done_criteria=done_criteria,
drivable_area_grid_map=agent_interface.drivable_area_grid_map,
lidar_point_cloud=True,
max_episode_steps=max_episode_steps,
neighborhood_vehicle_states=True,
occupancy_grid_map=agent_interface.occupancy_grid_map,
top_down_rgb=agent_interface.top_down_rgb,
road_waypoints=RoadWaypoints(horizon=road_waypoint_horizon),
waypoint_paths=Waypoints(lookahead=waypoints_lookahead),
) | Resolve the agent interface for a given environment. Some interface
values can be configured by the user, but others are pre-determined and
fixed. | resolve_agent_interface | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def __init__(self, env: gym.Env):
"""
Args:
env (gym.Env): Environment to be wrapped.
"""
super().__init__(env)
self._prev_obs: Dict[str, Dict[str, Any]] | Args:
env (gym.Env): Environment to be wrapped. | __init__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def reset(self, **kwargs):
"""Resets the environment.
Returns:
observation (dict): Dictionary of initial-state observation for
each agent.
info (dict): This dictionary contains auxiliary information
complementing ``observation``. It is analogous to the ``info``
returned by :meth:`step`.
"""
obs, info = self.env.reset(**kwargs)
self._prev_obs = self._store(obs=obs)
return obs, info | Resets the environment.
Returns:
observation (dict): Dictionary of initial-state observation for
each agent.
info (dict): This dictionary contains auxiliary information
complementing ``observation``. It is analogous to the ``info``
returned by :meth:`step`. | reset | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def _limit(
self, name: str, action: np.ndarray, prev_coord: np.ndarray
) -> np.ndarray:
"""Set time delta and limit Euclidean distance travelled in TargetPose action space.
Args:
name (str): Agent's name.
action (np.ndarray): Agent's action.
prev_coord (np.ndarray): Agent's previous xy coordinate on the map.
Returns:
np.ndarray: Agent's TargetPose action which has fixed time-delta and constrained next xy coordinate.
"""
time_delta = 0.1
limited_action = np.array(
[action[0], action[1], action[2], time_delta], dtype=np.float32
)
speed_max = MAXIMUM_SPEED_MPS
dist_max = speed_max * time_delta
# Set time-delta
if not math.isclose(action[3], time_delta, abs_tol=1e-3):
logger.warning(
"%s: Expected time-delta=%s, but got time-delta=%s. "
"Action time-delta automatically changed to %s.",
name,
time_delta,
action[3],
time_delta,
)
# Limit Euclidean distance travelled
next_coord = action[:2]
vector = next_coord - prev_coord
dist = np.linalg.norm(vector)
if dist > dist_max:
unit_vector = vector / dist
limited_action[0], limited_action[1] = prev_coord + dist_max * unit_vector
logger.warning(
"Action out of bounds. `%s`: Allowed max speed=%sm/s, but got speed=%sm/s. "
"Action has be corrected from %s to %s.",
name,
speed_max,
dist / time_delta,
action,
limited_action,
)
return limited_action | Set time delta and limit Euclidean distance travelled in TargetPose action space.
Args:
name (str): Agent's name.
action (np.ndarray): Agent's action.
prev_coord (np.ndarray): Agent's previous xy coordinate on the map.
Returns:
np.ndarray: Agent's TargetPose action which has fixed time-delta and constrained next xy coordinate. | _limit | python | huawei-noah/SMARTS | smarts/env/gymnasium/driving_smarts_2022_env.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/driving_smarts_2022_env.py | MIT |
def __init__(self, env: gym.Env):
"""
Args:
env (gym.Env): Single-agent SMARTS environment to be wrapped.
"""
super(SingleAgent, self).__init__(env)
agent_ids = list(env.agent_interfaces.keys())
assert (
len(agent_ids) == 1
), f"Expected env to have a single agent, but got {len(agent_ids)} agents."
self._agent_id = agent_ids[0]
if self.observation_space:
self.observation_space = self.observation_space[self._agent_id]
if self.action_space:
self.action_space = self.action_space[self._agent_id] | Args:
env (gym.Env): Single-agent SMARTS environment to be wrapped. | __init__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/single_agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/single_agent.py | MIT |
def step(self, action: Any) -> Tuple[Any, float, bool, bool, Any]:
"""Steps a single-agent SMARTS environment.
Args:
action (Any): Agent's action
Returns:
Tuple[Any, float, bool, bool, Any]: Agent's observation, reward,
terminated, truncated, and info
"""
obs, reward, terminated, truncated, info = self.env.step(
{self._agent_id: action}
)
return (
obs[self._agent_id],
reward[self._agent_id],
terminated[self._agent_id],
truncated[self._agent_id],
info[self._agent_id],
) | Steps a single-agent SMARTS environment.
Args:
action (Any): Agent's action
Returns:
Tuple[Any, float, bool, bool, Any]: Agent's observation, reward,
terminated, truncated, and info | step | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/single_agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/single_agent.py | MIT |
def reset(self, *, seed=None, options=None) -> Tuple[Any, Any]:
"""Resets a single-agent SMARTS environment.
Returns:
Tuple[Any, Any]: Agent's observation and info
"""
obs, info = self.env.reset(seed=seed, options=options)
return obs[self._agent_id], info[self._agent_id] | Resets a single-agent SMARTS environment.
Returns:
Tuple[Any, Any]: Agent's observation and info | reset | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/single_agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/single_agent.py | MIT |
def step(self, action: Action):
"""Mark a step for logging."""
step_vals = super().step(action)
self._current_episode.record_step(*step_vals)
return step_vals | Mark a step for logging. | step | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/episode_logger.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/episode_logger.py | MIT |
def reset(self) -> Tuple[Any, Dict[str, Any]]:
"""Mark an episode reset for logging."""
out = super().reset()
self._current_episode: EpisodeLog = next(self._log_iter)
self._current_episode.record_scenario(self.scenario_log)
return out | Mark an episode reset for logging. | reset | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/episode_logger.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/episode_logger.py | MIT |
def close(self):
"""Cap off the episode logging."""
self._closed = True
try:
next(self._log_iter)
except:
pass
return super().close() | Cap off the episode logging. | close | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/episode_logger.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/episode_logger.py | MIT |
def __init__(self, env: gym.Env):
"""
Args:
env (gym.Env): Environment to be wrapped.
"""
super().__init__(env)
self._time_delta = 0.1
self._speed_max = 22.22 # Units: m/s. Equivalent to 80 km/h.
self._dist_max = self._speed_max * self._time_delta | Args:
env (gym.Env): Environment to be wrapped. | __init__ | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/limit_relative_target_pose.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/limit_relative_target_pose.py | MIT |
def _limit(
self,
name: str,
action: np.ndarray,
) -> np.ndarray:
"""Limit Euclidean distance travelled in RelativeTargetPose action space.
Args:
name (str): Agent's name.
action (np.ndarray): Agent's action.
Returns:
np.ndarray: Agent's RelativeTargetPose action with constrained delta-x and delta-y coordinates.
"""
limited_action = np.array([action[0], action[1], action[2]], dtype=np.float32)
vector = action[:2]
dist = np.linalg.norm(vector)
if dist > self._dist_max:
unit_vector = vector / dist
limited_action[0], limited_action[1] = self._dist_max * unit_vector
logger.warning(
"Action out of bounds. `%s`: Allowed max speed=%sm/s, but got speed=%sm/s. "
"Action changed from %s to %s.",
name,
self._speed_max,
dist / self._time_delta,
action,
limited_action,
)
return limited_action | Limit Euclidean distance travelled in RelativeTargetPose action space.
Args:
name (str): Agent's name.
action (np.ndarray): Agent's action.
Returns:
np.ndarray: Agent's RelativeTargetPose action with constrained delta-x and delta-y coordinates. | _limit | python | huawei-noah/SMARTS | smarts/env/gymnasium/wrappers/limit_relative_target_pose.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/limit_relative_target_pose.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.