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 partition_by(f, seq):
"""Lazily partition seq into continuous chunks with constant value of f."""
f = make_func(f)
for _, items in groupby(seq, f):
yield items | Lazily partition seq into continuous chunks with constant value of f. | partition_by | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def lpartition_by(f, seq):
"""Partition seq into continuous chunks with constant value of f."""
return _lmap(list, partition_by(f, seq)) | Partition seq into continuous chunks with constant value of f. | lpartition_by | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def with_prev(seq, fill=None):
"""Yields each item paired with its preceding: (item, prev)."""
a, b = tee(seq)
return zip(a, chain([fill], b)) | Yields each item paired with its preceding: (item, prev). | with_prev | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def with_next(seq, fill=None):
"""Yields each item paired with its following: (item, next)."""
a, b = tee(seq)
next(b, None)
return zip(a, chain(b, [fill])) | Yields each item paired with its following: (item, next). | with_next | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def pairwise(seq):
"""Yields all pairs of neighboring items in seq."""
a, b = tee(seq)
next(b, None)
return zip(a, b) | Yields all pairs of neighboring items in seq. | pairwise | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def lzip(*seqs, strict=False):
"""List zip() version."""
return list(zip(*seqs, strict=strict)) | List zip() version. | lzip | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def lzip(*seqs, strict=False):
"""List zip() version."""
if strict and len(seqs) > 1:
return list(_zip_strict(*seqs))
return list(zip(*seqs)) | List zip() version. | lzip | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def reductions(f, seq, acc=EMPTY):
"""Yields intermediate reductions of seq by f."""
if acc is EMPTY:
return accumulate(seq) if f is operator.add else accumulate(seq, f)
return _reductions(f, seq, acc) | Yields intermediate reductions of seq by f. | reductions | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def lreductions(f, seq, acc=EMPTY):
"""Lists intermediate reductions of seq by f."""
return list(reductions(f, seq, acc)) | Lists intermediate reductions of seq by f. | lreductions | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def sums(seq, acc=EMPTY):
"""Yields partial sums of seq."""
return reductions(operator.add, seq, acc) | Yields partial sums of seq. | sums | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def lsums(seq, acc=EMPTY):
"""Lists partial sums of seq."""
return lreductions(operator.add, seq, acc) | Lists partial sums of seq. | lsums | python | Suor/funcy | funcy/seqs.py | https://github.com/Suor/funcy/blob/master/funcy/seqs.py | BSD-3-Clause |
def empty(coll):
"""Creates an empty collection of the same type."""
if isinstance(coll, Iterator):
return iter([])
return _factory(coll)() | Creates an empty collection of the same type. | empty | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def join(colls):
"""Joins several collections of same type into one."""
colls, colls_copy = tee(colls)
it = iter(colls_copy)
try:
dest = next(it)
except StopIteration:
return None
cls = dest.__class__
if isinstance(dest, (bytes, str)):
return ''.join(colls)
elif isinstance(dest, Mapping):
result = dest.copy()
for d in it:
result.update(d)
return result
elif isinstance(dest, Set):
return dest.union(*it)
elif isinstance(dest, (Iterator, range)):
return chain.from_iterable(colls)
elif isinstance(dest, Iterable):
# NOTE: this could be reduce(concat, ...),
# more effective for low count
return cls(chain.from_iterable(colls))
else:
raise TypeError("Don't know how to join %s" % cls.__name__) | Joins several collections of same type into one. | join | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def merge(*colls):
"""Merges several collections of same type into one.
Works with dicts, sets, lists, tuples, iterators and strings.
For dicts later values take precedence."""
return join(colls) | Merges several collections of same type into one.
Works with dicts, sets, lists, tuples, iterators and strings.
For dicts later values take precedence. | merge | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def join_with(f, dicts, strict=False):
"""Joins several dicts, combining values with given function."""
dicts = list(dicts)
if not dicts:
return {}
elif not strict and len(dicts) == 1:
return dicts[0]
lists = {}
for c in dicts:
for k, v in iteritems(c):
if k in lists:
lists[k].append(v)
else:
lists[k] = [v]
if f is not list:
# kind of walk_values() inplace
for k, v in iteritems(lists):
lists[k] = f(v)
return lists | Joins several dicts, combining values with given function. | join_with | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def merge_with(f, *dicts):
"""Merges several dicts, combining values with given function."""
return join_with(f, dicts) | Merges several dicts, combining values with given function. | merge_with | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def walk(f, coll):
"""Walks the collection transforming its elements with f.
Same as map, but preserves coll type."""
return _factory(coll)(xmap(f, iteritems(coll))) | Walks the collection transforming its elements with f.
Same as map, but preserves coll type. | walk | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def walk_keys(f, coll):
"""Walks keys of the collection, mapping them with f."""
f = make_func(f)
# NOTE: we use this awkward construct instead of lambda to be Python 3 compatible
def pair_f(pair):
k, v = pair
return f(k), v
return walk(pair_f, coll) | Walks keys of the collection, mapping them with f. | walk_keys | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def walk_values(f, coll):
"""Walks values of the collection, mapping them with f."""
f = make_func(f)
# NOTE: we use this awkward construct instead of lambda to be Python 3 compatible
def pair_f(pair):
k, v = pair
return k, f(v)
return _factory(coll, mapper=f)(xmap(pair_f, iteritems(coll))) | Walks values of the collection, mapping them with f. | walk_values | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def select(pred, coll):
"""Same as filter but preserves coll type."""
return _factory(coll)(xfilter(pred, iteritems(coll))) | Same as filter but preserves coll type. | select | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def select_keys(pred, coll):
"""Select part of the collection with keys passing pred."""
pred = make_pred(pred)
return select(lambda pair: pred(pair[0]), coll) | Select part of the collection with keys passing pred. | select_keys | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def select_values(pred, coll):
"""Select part of the collection with values passing pred."""
pred = make_pred(pred)
return select(lambda pair: pred(pair[1]), coll) | Select part of the collection with values passing pred. | select_values | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def compact(coll):
"""Removes falsy values from the collection."""
if isinstance(coll, Mapping):
return select_values(bool, coll)
else:
return select(bool, coll) | Removes falsy values from the collection. | compact | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def is_distinct(coll, key=EMPTY):
"""Checks if all elements in the collection are different."""
if key is EMPTY:
return len(coll) == len(set(coll))
else:
return len(coll) == len(set(xmap(key, coll))) | Checks if all elements in the collection are different. | is_distinct | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def all(pred, seq=EMPTY):
"""Checks if all items in seq pass pred (or are truthy)."""
if seq is EMPTY:
return _all(pred)
return _all(xmap(pred, seq)) | Checks if all items in seq pass pred (or are truthy). | all | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def any(pred, seq=EMPTY):
"""Checks if any item in seq passes pred (or is truthy)."""
if seq is EMPTY:
return _any(pred)
return _any(xmap(pred, seq)) | Checks if any item in seq passes pred (or is truthy). | any | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def none(pred, seq=EMPTY):
""""Checks if none of the items in seq pass pred (or are truthy)."""
return not any(pred, seq) | Checks if none of the items in seq pass pred (or are truthy). | none | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def one(pred, seq=EMPTY):
"""Checks whether exactly one item in seq passes pred (or is truthy)."""
if seq is EMPTY:
return one(bool, pred)
return len(take(2, xfilter(pred, seq))) == 1 | Checks whether exactly one item in seq passes pred (or is truthy). | one | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def some(pred, seq=EMPTY):
"""Finds first item in seq passing pred or first that is truthy."""
if seq is EMPTY:
return some(bool, pred)
return next(xfilter(pred, seq), None) | Finds first item in seq passing pred or first that is truthy. | some | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def zipdict(keys, vals):
"""Creates a dict with keys mapped to the corresponding vals."""
return dict(zip(keys, vals)) | Creates a dict with keys mapped to the corresponding vals. | zipdict | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def flip(mapping):
"""Flip passed dict or collection of pairs swapping its keys and values."""
def flip_pair(pair):
k, v = pair
return v, k
return walk(flip_pair, mapping) | Flip passed dict or collection of pairs swapping its keys and values. | flip | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def project(mapping, keys):
"""Leaves only given keys in mapping."""
return _factory(mapping)((k, mapping[k]) for k in keys if k in mapping) | Leaves only given keys in mapping. | project | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def omit(mapping, keys):
"""Removes given keys from mapping."""
return _factory(mapping)((k, v) for k, v in iteritems(mapping) if k not in keys) | Removes given keys from mapping. | omit | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def zip_values(*dicts):
"""Yields tuples of corresponding values of several dicts."""
if len(dicts) < 1:
raise TypeError('zip_values expects at least one argument')
keys = set.intersection(*map(set, dicts))
for key in keys:
yield tuple(d[key] for d in dicts) | Yields tuples of corresponding values of several dicts. | zip_values | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def zip_dicts(*dicts):
"""Yields tuples like (key, (val1, val2, ...))
for each common key in all given dicts."""
if len(dicts) < 1:
raise TypeError('zip_dicts expects at least one argument')
keys = set.intersection(*map(set, dicts))
for key in keys:
yield key, tuple(d[key] for d in dicts) | Yields tuples like (key, (val1, val2, ...))
for each common key in all given dicts. | zip_dicts | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def get_in(coll, path, default=None):
"""Returns a value at path in the given nested collection."""
for key in path:
try:
coll = coll[key]
except (KeyError, IndexError):
return default
return coll | Returns a value at path in the given nested collection. | get_in | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def get_lax(coll, path, default=None):
"""Returns a value at path in the given nested collection.
Does not raise on a wrong collection type along the way, but removes default.
"""
for key in path:
try:
coll = coll[key]
except (KeyError, IndexError, TypeError):
return default
return coll | Returns a value at path in the given nested collection.
Does not raise on a wrong collection type along the way, but removes default. | get_lax | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def set_in(coll, path, value):
"""Creates a copy of coll with the value set at path."""
return update_in(coll, path, lambda _: value) | Creates a copy of coll with the value set at path. | set_in | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def update_in(coll, path, update, default=None):
"""Creates a copy of coll with a value updated at path."""
if not path:
return update(coll)
elif isinstance(coll, list):
copy = coll[:]
# NOTE: there is no auto-vivication for lists
copy[path[0]] = update_in(copy[path[0]], path[1:], update, default)
return copy
else:
copy = coll.copy()
current_default = {} if len(path) > 1 else default
copy[path[0]] = update_in(copy.get(path[0], current_default), path[1:], update, default)
return copy | Creates a copy of coll with a value updated at path. | update_in | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def del_in(coll, path):
"""Creates a copy of coll with a nested key or index deleted."""
if not path:
return coll
try:
next_coll = coll[path[0]]
except (KeyError, IndexError):
return coll
coll_copy = copy(coll)
if len(path) == 1:
del coll_copy[path[0]]
else:
coll_copy[path[0]] = del_in(next_coll, path[1:])
return coll_copy | Creates a copy of coll with a nested key or index deleted. | del_in | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def has_path(coll, path):
"""Checks if path exists in the given nested collection."""
for p in path:
try:
coll = coll[p]
except (KeyError, IndexError):
return False
return True | Checks if path exists in the given nested collection. | has_path | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def lwhere(mappings, **cond):
"""Selects mappings containing all pairs in cond."""
return list(where(mappings, **cond)) | Selects mappings containing all pairs in cond. | lwhere | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def lpluck(key, mappings):
"""Lists values for key in each mapping."""
return list(pluck(key, mappings)) | Lists values for key in each mapping. | lpluck | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def lpluck_attr(attr, objects):
"""Lists values of given attribute of each object."""
return list(pluck_attr(attr, objects)) | Lists values of given attribute of each object. | lpluck_attr | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def linvoke(objects, name, *args, **kwargs):
"""Makes a list of results of the obj.name(*args, **kwargs)
for each object in objects."""
return list(invoke(objects, name, *args, **kwargs)) | Makes a list of results of the obj.name(*args, **kwargs)
for each object in objects. | linvoke | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def where(mappings, **cond):
"""Iterates over mappings containing all pairs in cond."""
items = cond.items()
match = lambda m: all(k in m and m[k] == v for k, v in items)
return filter(match, mappings) | Iterates over mappings containing all pairs in cond. | where | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def pluck(key, mappings):
"""Iterates over values for key in mappings."""
return map(itemgetter(key), mappings) | Iterates over values for key in mappings. | pluck | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def pluck_attr(attr, objects):
"""Iterates over values of given attribute of given objects."""
return map(attrgetter(attr), objects) | Iterates over values of given attribute of given objects. | pluck_attr | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def invoke(objects, name, *args, **kwargs):
"""Yields results of the obj.name(*args, **kwargs)
for each object in objects."""
return map(methodcaller(name, *args, **kwargs), objects) | Yields results of the obj.name(*args, **kwargs)
for each object in objects. | invoke | python | Suor/funcy | funcy/colls.py | https://github.com/Suor/funcy/blob/master/funcy/colls.py | BSD-3-Clause |
def get_ray_worker_actors(self, count: int):
"""Get the current "ray" worker actors.
Args:
count (int): The number of workers to get.
Returns:
Any: The "ray" remote worker handles.
"""
if len(self._current_workers) != count:
# we need to cache because using options(name) is extremely slow
self._current_workers = [
RayProcessWorker.options(
name=f"sensor_worker_{i}", get_if_exists=True
).remote()
for i in range(count)
]
return self._current_workers | Get the current "ray" worker actors.
Args:
count (int): The number of workers to get.
Returns:
Any: The "ray" remote worker handles. | get_ray_worker_actors | python | huawei-noah/SMARTS | smarts/ray/sensors/ray_sensor_resolver.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/ray/sensors/ray_sensor_resolver.py | MIT |
def step(self, sim_frame: SimulationFrame, sensor_states: Iterable[SensorState]):
"""Step the sensor state."""
for sensor_state in sensor_states:
sensor_state.step() | Step the sensor state. | step | python | huawei-noah/SMARTS | smarts/ray/sensors/ray_sensor_resolver.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/ray/sensors/ray_sensor_resolver.py | MIT |
def update_local_constants(self, sim_local_constants: SimulationLocalConstants):
"""Updates the process worker.
Args:
sim_local_constants (SimulationLocalConstants | None): The current simulation reset state.
"""
self._simulation_local_constants = loads(sim_local_constants) | Updates the process worker.
Args:
sim_local_constants (SimulationLocalConstants | None): The current simulation reset state. | update_local_constants | python | huawei-noah/SMARTS | smarts/ray/sensors/ray_sensor_resolver.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/ray/sensors/ray_sensor_resolver.py | MIT |
def do_work(self, remote_sim_frame: SimulationFrame, agent_ids: Set[str]):
"""Run the sensors against the current simulation state.
Args:
remote_sim_frame (SimulationFrame): The current simulation state.
agent_ids (set[str]): The agent ids to operate on.
Returns:
tuple[dict, dict, dict]: The updated sensor states: (observations, dones, updated_sensors)
"""
sim_frame = loads(remote_sim_frame)
return Sensors.observe_serializable_sensor_batch(
sim_frame, self._simulation_local_constants, agent_ids
) | Run the sensors against the current simulation state.
Args:
remote_sim_frame (SimulationFrame): The current simulation state.
agent_ids (set[str]): The agent ids to operate on.
Returns:
tuple[dict, dict, dict]: The updated sensor states: (observations, dones, updated_sensors) | do_work | python | huawei-noah/SMARTS | smarts/ray/sensors/ray_sensor_resolver.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/ray/sensors/ray_sensor_resolver.py | MIT |
def step(self, sim: SMARTS):
"""Step the manager. Assume modification of existence and control of the simulation actors.
Args:
sim (smarts.core.smarts.SMARTS): The smarts simulation instance.
"""
raise NotImplementedError() | Step the manager. Assume modification of existence and control of the simulation actors.
Args:
sim (smarts.core.smarts.SMARTS): The smarts simulation instance. | step | python | huawei-noah/SMARTS | smarts/core/actor_capture_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor_capture_manager.py | MIT |
def reset(self, scenario: smarts.core.scenario.Scenario, sim: SMARTS):
"""Reset this manager.
:param scenario: The scenario to initialize from.
:type scenario: smarts.core.scenario.Scenario
:param sim: The simulation this is associated to.
:type scenario: smarts.core.smarts.SMARTS
"""
raise NotImplementedError() | Reset this manager.
:param scenario: The scenario to initialize from.
:type scenario: smarts.core.scenario.Scenario
:param sim: The simulation this is associated to.
:type scenario: smarts.core.smarts.SMARTS | reset | python | huawei-noah/SMARTS | smarts/core/actor_capture_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor_capture_manager.py | MIT |
def teardown(self):
"""Clean up any unmanaged resources this manager uses (e.g. file handles.)"""
raise NotImplementedError() | Clean up any unmanaged resources this manager uses (e.g. file handles.) | teardown | python | huawei-noah/SMARTS | smarts/core/actor_capture_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor_capture_manager.py | MIT |
def id(self):
"""The id of this vehicle."""
return self._id | The id of this vehicle. | id | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def length(self) -> float:
"""The length of this vehicle."""
self._assert_initialized()
return self._chassis.dimensions.length | The length of this vehicle. | length | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def max_steering_wheel(self) -> Optional[float]:
"""The max steering value the chassis steering wheel can turn to.
Some chassis types do not support this.
"""
self._assert_initialized()
return getattr(self._chassis, "max_steering_wheel", None) | The max steering value the chassis steering wheel can turn to.
Some chassis types do not support this. | max_steering_wheel | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def width(self) -> float:
"""The width of this vehicle."""
self._assert_initialized()
return self._chassis.dimensions.width | The width of this vehicle. | width | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def height(self) -> float:
"""The height of this vehicle."""
self._assert_initialized()
return self._chassis.dimensions.height | The height of this vehicle. | height | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def speed(self) -> float:
"""The current speed of this vehicle."""
self._assert_initialized()
return self._chassis.speed | The current speed of this vehicle. | speed | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def sensors(self) -> Dict[str, Sensor]:
"""The sensors attached to this vehicle."""
self._assert_initialized()
return self._sensors | The sensors attached to this vehicle. | sensors | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def vehicle_color(self) -> Union[SceneColors, None]:
"""The color of this vehicle (generally used for rendering purposes.)"""
self._assert_initialized()
return self._color | The color of this vehicle (generally used for rendering purposes.) | vehicle_color | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def state(self) -> VehicleState:
"""The current state of this vehicle."""
self._assert_initialized()
return VehicleState(
actor_id=self.id,
actor_type=self.vehicle_type,
source="SMARTS", # this is the "ground truth" state
vehicle_config_type=self._vehicle_config_type,
pose=self.pose,
dimensions=self._chassis.dimensions,
speed=self.speed,
# pytype: disable=attribute-error
steering=self._chassis.steering,
# pytype: enable=attribute-error
yaw_rate=self._chassis.yaw_rate,
linear_velocity=self._chassis.velocity_vectors[0],
angular_velocity=self._chassis.velocity_vectors[1],
) | The current state of this vehicle. | state | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def action_space(self):
"""The action space this vehicle uses."""
self._assert_initialized()
return self._action_space | The action space this vehicle uses. | action_space | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def pose(self) -> Pose:
"""The pose of this vehicle. Pose is defined as position and orientation."""
self._assert_initialized()
return self._chassis.pose | The pose of this vehicle. Pose is defined as position and orientation. | pose | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def chassis(self) -> Chassis:
"""The underlying chassis of this vehicle."""
self._assert_initialized()
return self._chassis | The underlying chassis of this vehicle. | chassis | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def heading(self) -> Heading:
"""The heading of this vehicle.
Note: Heading rotates counterclockwise with north as 0.
"""
self._assert_initialized()
return self._chassis.pose.heading | The heading of this vehicle.
Note: Heading rotates counterclockwise with north as 0. | heading | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def position(self) -> np.ndarray:
"""The position of this vehicle."""
self._assert_initialized()
return self._chassis.pose.position | The position of this vehicle. | position | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def bounding_box(self) -> List[np.ndarray]:
"""The minimum fitting heading aligned bounding box. Four 2D points representing the minimum fitting box."""
# XXX: this doesn't return a smarts.core.coordinates.BoundingBox!
self._assert_initialized()
# Assuming the position is the center,
# calculate the corner coordinates of the bounding_box
origin = self.position[:2]
dimensions = np.array([self.width, self.length])
corners = np.array([(-1, 1), (1, 1), (1, -1), (-1, -1)]) / 2
heading = self.heading
return [
rotate_cw_around_point(
point=origin + corner * dimensions,
radians=Heading.flip_clockwise(heading),
origin=origin,
)
for corner in corners
] | The minimum fitting heading aligned bounding box. Four 2D points representing the minimum fitting box. | bounding_box | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def vehicle_type(self) -> str:
"""Get the vehicle type name as recognized by SMARTS. (e.g. 'car')"""
return VEHICLE_CONFIGS[self._vehicle_config_type].vehicle_type | Get the vehicle type name as recognized by SMARTS. (e.g. 'car') | vehicle_type | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def vehicle_config_type(self) -> str:
"""Get the vehicle type identifier. (e.g. 'sedan')"""
return self._vehicle_config_type | Get the vehicle type identifier. (e.g. 'sedan') | vehicle_config_type | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def vehicle_class(self) -> str:
"""Get the custom class of vehicle this is. (e.g. 'ford_f150')"""
return self._vehicle_class | Get the custom class of vehicle this is. (e.g. 'ford_f150') | vehicle_class | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def valid(self) -> bool:
"""Check if the vehicle still `exists` and is still operable."""
return self._initialized | Check if the vehicle still `exists` and is still operable. | valid | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def sensor_names(self) -> Tuple[str]:
"""The names of the sensors that are potentially available to this vehicle."""
return self._sensor_names | The names of the sensors that are potentially available to this vehicle. | sensor_names | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def agent_vehicle_dims(
mission: "plan.NavigationMission", default: Optional[str] = None
) -> Dimensions:
"""Get the vehicle dimensions from the mission requirements.
Args:
A mission for the agent.
Returns:
The mission vehicle spec dimensions XOR the default "passenger" vehicle dimensions.
"""
if not default:
default = config().get_setting("assets", "default_agent_vehicle")
if default == "sedan":
default = "passenger"
default_type = default
if mission.vehicle_spec:
# mission.vehicle_spec.veh_config_type will always be "passenger" for now,
# but we use that value here in case we ever expand our history functionality.
vehicle_config_type = mission.vehicle_spec.veh_config_type
return Dimensions.copy_with_defaults(
mission.vehicle_spec.dimensions,
VEHICLE_CONFIGS[vehicle_config_type or default_type].dimensions,
)
return VEHICLE_CONFIGS[default_type].dimensions | Get the vehicle dimensions from the mission requirements.
Args:
A mission for the agent.
Returns:
The mission vehicle spec dimensions XOR the default "passenger" vehicle dimensions. | agent_vehicle_dims | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def attach_sensors_to_vehicle(
cls,
sensor_manager: SensorManager,
sim: SMARTS,
vehicle: Vehicle,
agent_interface: AgentInterface,
replace=True,
reset_sensors=False,
):
"""Attach sensors as required to satisfy the agent interface's requirements"""
# The distance travelled sensor is not optional b/c it is used for the score
# and reward calculation
vehicle_state = vehicle.state
has_no_sensors = len(vehicle.sensors) == 0
added_sensors: List[Tuple[str, Sensor]] = []
if reset_sensors:
sensor_manager.remove_actor_sensors_by_actor_id(vehicle.id)
# pytype: disable=attribute-error
Vehicle.detach_all_sensors_from_vehicle(vehicle)
# pytype: enable=attribute-error
def add_sensor_if_needed(
sensor_type,
sensor_name: str,
condition: bool = True,
**kwargs,
):
assert (
sensor_name in cls._sensor_names
), f"{sensor_name}:{cls._sensor_names}"
if (
replace
or has_no_sensors
or (condition and not vehicle.subscribed_to(sensor_name))
):
sensor = sensor_type(**kwargs)
vehicle.attach_sensor(sensor, sensor_name)
added_sensors.append((sensor_name, sensor))
# pytype: disable=attribute-error
add_sensor_if_needed(TripMeterSensor, sensor_name="trip_meter_sensor")
add_sensor_if_needed(DrivenPathSensor, sensor_name="driven_path_sensor")
if agent_interface.neighborhood_vehicle_states:
add_sensor_if_needed(
NeighborhoodVehiclesSensor,
sensor_name="neighborhood_vehicle_states_sensor",
radius=agent_interface.neighborhood_vehicle_states.radius,
)
add_sensor_if_needed(
AccelerometerSensor,
sensor_name="accelerometer_sensor",
condition=agent_interface.accelerometer,
)
add_sensor_if_needed(
WaypointsSensor,
sensor_name="waypoints_sensor",
condition=agent_interface.waypoint_paths,
)
if agent_interface.road_waypoints:
add_sensor_if_needed(
RoadWaypointsSensor,
"road_waypoints_sensor",
horizon=agent_interface.road_waypoints.horizon,
)
add_sensor_if_needed(
LanePositionSensor,
"lane_position_sensor",
condition=agent_interface.lane_positions,
)
# DrivableAreaGridMapSensor
if agent_interface.drivable_area_grid_map:
if not sim.renderer_ref:
raise RendererException.required_to("add a drivable_area_grid_map")
add_sensor_if_needed(
DrivableAreaGridMapSensor,
"drivable_area_grid_map_sensor",
True, # Always add this sensor
vehicle_state=vehicle_state,
width=agent_interface.drivable_area_grid_map.width,
height=agent_interface.drivable_area_grid_map.height,
resolution=agent_interface.drivable_area_grid_map.resolution,
renderer=sim.renderer_ref,
)
# OGMSensor
if agent_interface.occupancy_grid_map:
if not sim.renderer_ref:
raise RendererException.required_to("add an OGM")
add_sensor_if_needed(
OGMSensor,
"ogm_sensor",
True, # Always add this sensor
vehicle_state=vehicle_state,
width=agent_interface.occupancy_grid_map.width,
height=agent_interface.occupancy_grid_map.height,
resolution=agent_interface.occupancy_grid_map.resolution,
renderer=sim.renderer_ref,
)
if agent_interface.occlusion_map:
if not vehicle.subscribed_to("ogm_sensor"):
warnings.warn(
"Occupancy grid map sensor must be attached to use occlusion sensor.",
category=UserWarning,
)
else:
add_sensor_if_needed(
OcclusionMapSensor,
"occlusion_map_sensor",
vehicle_state=vehicle_state,
width=agent_interface.occlusion_map.width,
height=agent_interface.occlusion_map.height,
resolution=agent_interface.occlusion_map.resolution,
renderer=sim.renderer_ref,
ogm_sensor=vehicle.sensor_property("ogm_sensor"),
add_surface_noise=agent_interface.occlusion_map.surface_noise,
)
# RGBSensor
if agent_interface.top_down_rgb:
if not sim.renderer_ref:
raise RendererException.required_to("add an RGB camera")
add_sensor_if_needed(
RGBSensor,
"rgb_sensor",
True, # Always add this sensor
vehicle_state=vehicle_state,
width=agent_interface.top_down_rgb.width,
height=agent_interface.top_down_rgb.height,
resolution=agent_interface.top_down_rgb.resolution,
renderer=sim.renderer_ref,
)
if len(agent_interface.custom_renders):
if not sim.renderer_ref:
raise RendererException.required_to("add a fragment program.")
for i, program in enumerate(agent_interface.custom_renders):
add_sensor_if_needed(
CustomRenderSensor,
f"custom_render{i}_sensor",
vehicle_state=vehicle_state,
width=program.width,
height=program.height,
resolution=program.resolution,
renderer=sim.renderer_ref,
fragment_shader_path=program.fragment_shader_path,
render_dependencies=program.dependencies,
ogm_sensor=vehicle.sensor_property("ogm_sensor", None),
top_down_rgb_sensor=vehicle.sensor_property("rgb_sensor", None),
drivable_area_grid_map_sensor=vehicle.sensor_property(
"drivable_area_grid_map_sensor", default=None
),
occlusion_map_sensor=vehicle.sensor_property(
"occlusion_map_sensor", default=None
),
name=program.name,
)
if agent_interface.lidar_point_cloud:
add_sensor_if_needed(
LidarSensor,
"lidar_sensor",
vehicle_state=vehicle_state,
sensor_params=agent_interface.lidar_point_cloud.sensor_params,
)
add_sensor_if_needed(
ViaSensor, "via_sensor", True, lane_acquisition_range=80, speed_accuracy=1.5
)
if agent_interface.signals:
add_sensor_if_needed(
SignalsSensor,
"signals_sensor",
lookahead=agent_interface.signals.lookahead,
)
# pytype: enable=attribute-error
for sensor_name, sensor in added_sensors:
if not sensor:
continue
sensor_manager.add_sensor_for_actor(vehicle.id, sensor_name, sensor) | Attach sensors as required to satisfy the agent interface's requirements | attach_sensors_to_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def step(self, current_simulation_time: float):
"""Update internal state."""
self._has_stepped = True
self._chassis.step(current_simulation_time) | Update internal state. | step | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def control(self, *args, **kwargs):
"""Apply control values to this vehicle.
Forwards control to the chassis.
"""
self._chassis.control(*args, **kwargs) | Apply control values to this vehicle.
Forwards control to the chassis. | control | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def update_state(self, state: VehicleState, dt: float):
"""Update the vehicle's state"""
state.updated = True
if state.role != ActorRole.External:
assert isinstance(self._chassis, BoxChassis)
self.control(pose=state.pose, speed=state.speed, dt=dt)
return
# External actors are "privileged", which means they work directly (bypass force application).
# Conceptually, this is playing 'god' with physics and should only be used
# to defer to a co-simulator's states.
linear_velocity, angular_velocity = None, None
if not np.allclose(
self._chassis.velocity_vectors[0], state.linear_velocity
) or not np.allclose(self._chassis.velocity_vectors[1], state.angular_velocity):
linear_velocity = state.linear_velocity
angular_velocity = state.angular_velocity
if not state.dimensions.equal_if_defined(self.length, self.width, self.height):
self._log.warning(
"Unable to change a vehicle's dimensions via external_state_update()."
)
# XXX: any way to update acceleration in pybullet?
self._chassis.state_override(dt, state.pose, linear_velocity, angular_velocity) | Update the vehicle's state | update_state | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def create_renderer_node(self, renderer: RendererBase):
"""Create the vehicle's rendering node in the renderer."""
return renderer.create_vehicle_node(
self._visual_model_path, self._id, self.vehicle_color, self.pose
) | Create the vehicle's rendering node in the renderer. | create_renderer_node | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def set_pose(self, pose: Pose):
"""Use with caution. This will directly set the pose of the chassis.
This may disrupt physics simulation of the chassis physics body for a few steps after use.
"""
self._warn_AckermannChassis_set_pose()
self._chassis.set_pose(pose) | Use with caution. This will directly set the pose of the chassis.
This may disrupt physics simulation of the chassis physics body for a few steps after use. | set_pose | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def swap_chassis(self, chassis: Chassis):
"""Swap the current chassis with the given chassis. Apply the GCD of the previous chassis
to the new chassis ("greatest common denominator state" from front-end to back-end)
"""
chassis.inherit_physical_values(self._chassis)
self._chassis.teardown()
self._chassis = chassis | Swap the current chassis with the given chassis. Apply the GCD of the previous chassis
to the new chassis ("greatest common denominator state" from front-end to back-end) | swap_chassis | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def teardown(self, renderer: RendererBase, exclude_chassis: bool = False):
"""Clean up internal resources"""
if not exclude_chassis:
self._chassis.teardown()
if renderer:
renderer.remove_vehicle_node(self._id)
self._initialized = False | Clean up internal resources | teardown | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def attach_sensor(self, sensor: Sensor, sensor_name: str):
"""replace previously-attached sensor with this one
(to allow updating its parameters).
Sensors might have been attached to a non-agent vehicle
(for example, for observation collection from history vehicles),
but if that vehicle gets hijacked, we want to use the sensors
specified by the hijacking agent's interface."""
detach = getattr(self, f"detach_{sensor_name}")
if detach:
self.detach_sensor(sensor_name)
self._log.debug("Replaced existing %s on vehicle %s", sensor_name, self.id)
setattr(self, f"_{sensor_name}", sensor)
self._sensors[sensor_name] = sensor | replace previously-attached sensor with this one
(to allow updating its parameters).
Sensors might have been attached to a non-agent vehicle
(for example, for observation collection from history vehicles),
but if that vehicle gets hijacked, we want to use the sensors
specified by the hijacking agent's interface. | attach_sensor | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def detach_sensor(self, sensor_name: str):
"""Detach a sensor by name."""
self._log.debug("Removed existing %s on vehicle %s", sensor_name, self.id)
sensor = getattr(self, f"_{sensor_name}", None)
if sensor is not None:
setattr(self, f"_{sensor_name}", None)
del self._sensors[sensor_name]
return sensor | Detach a sensor by name. | detach_sensor | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def subscribed_to(self, sensor_name: str):
"""Confirm if the sensor is subscribed."""
sensor = getattr(self, f"_{sensor_name}", None)
return sensor is not None | Confirm if the sensor is subscribed. | subscribed_to | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def sensor_property(
self,
sensor_name: str,
default: Optional[Union[Sensor, Ellipsis.__class__]] = ...,
):
"""Call a sensor by name."""
sensor = getattr(self, f"_{sensor_name}", None if default is ... else default)
assert (
sensor is not None or default is not ...
), f"'{sensor_name}' is not attached to '{self.id}'"
return sensor | Call a sensor by name. | sensor_property | python | huawei-noah/SMARTS | smarts/core/vehicle.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle.py | MIT |
def actor_ids(self) -> Iterable[str]:
"""A set of actors that this provider manages.
Returns:
Iterable[str]: The actors this provider manages.
"""
return set(vs.actor_id for vs in self._my_signals.values()) | A set of actors that this provider manages.
Returns:
Iterable[str]: The actors this provider manages. | actor_ids | python | huawei-noah/SMARTS | smarts/core/signal_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/signal_provider.py | MIT |
def get_pose(self) -> Optional[Pose]:
"""Get the pose of this actor. Some actors do not have a physical location."""
return None | Get the pose of this actor. Some actors do not have a physical location. | get_pose | python | huawei-noah/SMARTS | smarts/core/actor.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor.py | MIT |
def get_dimensions(self) -> Optional[Dimensions]:
"""Get the dimensions of this actor. Some actors do not have physical dimensions."""
return None | Get the dimensions of this actor. Some actors do not have physical dimensions. | get_dimensions | python | huawei-noah/SMARTS | smarts/core/actor.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor.py | MIT |
def __lt__(self, other) -> bool:
"""Allows ordering ActorStates for use in sorted data-structures."""
assert isinstance(other, ActorState)
return self.actor_id < other.actor_id or (
self.actor_id == other.actor_id and id(self) < id(other)
) | Allows ordering ActorStates for use in sorted data-structures. | __lt__ | python | huawei-noah/SMARTS | smarts/core/actor.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/actor.py | MIT |
def trajectory(self, current_pose, target_pose_at_t, n, dt):
"""Generate a bezier trajectory to a target pose."""
return self.trajectory_batched(
np.array([current_pose]), np.array([target_pose_at_t]), n, dt
)[0] | Generate a bezier trajectory to a target pose. | trajectory | python | huawei-noah/SMARTS | smarts/core/bezier_motion_planner.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bezier_motion_planner.py | MIT |
def trajectory_batched(self, current_poses, target_poses_at_t, n, dt) -> np.ndarray:
"""Generate a batch of trajectories
Args:
current_poses: ``np.array([[x, y, heading]])``
target_poses_at_t: ``np.array([[x, y, heading, seconds_into_future]]``
pose we would like to have this many seconds into the future
n: number of trajectory points to return
dt: time delta between trajectory points
Returns:
A stacked ``np.array`` of the form
``np.array([[x], [y], [heading], [desired_speed]])``
"""
assert len(current_poses) == len(target_poses_at_t)
# vectorized cubic bezier computation
target_headings = target_poses_at_t[:, 2] + np.pi * 0.5
target_dir_vecs = np.array(
[np.cos(target_headings), np.sin(target_headings)]
).T.reshape(-1, 2)
current_headings = current_poses[:, 2] + np.pi * 0.5
current_dir_vecs = np.array(
[np.cos(current_headings), np.sin(current_headings)]
).T.reshape(-1, 2)
extension = (
np.linalg.norm(
target_poses_at_t[:, :2] - current_poses[:, :2], axis=1
).reshape(-1, 1)
* self._extend
)
# FIXME: speed control still needed for values of t != dt !!!
# Reason being that the tangents (therefore speed) along a bezier curve will vary.
real_times = target_poses_at_t[:, 3:4].repeat(n, axis=0).clip(dt, None)
p0s = current_poses[:, :2].repeat(n, axis=0)
p1s = (
current_poses[:, :2] + current_dir_vecs * extension * self._extend_bias
).repeat(n, axis=0)
p2s = (
target_poses_at_t[:, :2]
- target_dir_vecs * extension * (1 - self._extend_bias)
).repeat(n, axis=0)
p3s = target_poses_at_t[:, :2].repeat(n, axis=0)
dts = (np.array(range(1, n + 1)) * dt).reshape(-1, 1).repeat(
len(current_poses), axis=1
).T.reshape(-1, 1) / real_times
def linear_bezier(t, p0, p1):
return (1 - t) * p0 + t * p1
def quadratic_bezier(t, p0, p1, p2):
return linear_bezier(t, linear_bezier(t, p0, p1), linear_bezier(t, p1, p2))
def cubic_bezier(t, p0, p1, p2, p3):
return linear_bezier(
t, quadratic_bezier(t, p0, p1, p2), quadratic_bezier(t, p1, p2, p3)
)
def curve_lengths(subsections, t, p0, p1, p2, p3):
# TAI: subsections could be scaled by time, magnitude between p0 and p3,
# and directional difference between p1 and p2
lengths = []
inverse_subsection = 1 / subsections
for (ti, p0i, p1i, p2i, p3i) in zip(t, p0, p1, p2, p3):
# get s subsection points in [p(0):p(t)]
tss = [ts * inverse_subsection * ti for ts in range(subsections + 1)]
points = [cubic_bezier(ts, p0i, p1i, p2i, p3i) for ts in tss]
subsection_length_total = 0
# accumulate position deltas [s[t+1] - s[t]]
for (ps, ps1) in zip(points[:-1], points[1:]):
# convert deltas to magnitudes
delta_dist = np.subtract(ps1, ps)
# add magnitudes
subsection_length = np.linalg.norm(delta_dist)
# add to lengths
subsection_length_total += subsection_length
lengths.append(subsection_length_total)
return np.array(lengths)
def length_to_speed(t, length):
speeds = [l / t if t > 0 else -1 for (t, l) in zip(t, length)]
return np.array(speeds)
positions = cubic_bezier(dts, p0s, p1s, p2s, p3s)
# TODO: this could be optimized to use the positions already generated
lengths = curve_lengths(
self._speed_calculation_resolution, dts, p0s, p1s, p2s, p3s
)
speeds = length_to_speed(real_times.reshape(n), lengths)
# angle interp. equations come from:
# https://stackoverflow.com/questions/2708476/rotation-interpolation#14498790
heading_correction = ((target_headings - current_headings) + np.pi) % (
2 * np.pi
) - np.pi
headings = (
current_headings
+ (
(dts.reshape(-1) * heading_correction + np.pi) % (2 * np.pi) - np.pi
).reshape(-1)
- np.pi * 0.5
)
trajectories = np.array(
[positions[:, 0], positions[:, 1], headings, speeds]
).T.reshape(-1, 4, n)
return trajectories | Generate a batch of trajectories
Args:
current_poses: ``np.array([[x, y, heading]])``
target_poses_at_t: ``np.array([[x, y, heading, seconds_into_future]]``
pose we would like to have this many seconds into the future
n: number of trajectory points to return
dt: time delta between trajectory points
Returns:
A stacked ``np.array`` of the form
``np.array([[x], [y], [heading], [desired_speed]])`` | trajectory_batched | python | huawei-noah/SMARTS | smarts/core/bezier_motion_planner.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bezier_motion_planner.py | MIT |
def teardown(self):
"""Clean up resources."""
self._log.debug("Tearing down AgentManager")
self.teardown_ego_agents()
self.teardown_social_agents()
self._pending_agent_ids = set() | Clean up resources. | teardown | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def destroy(self):
"""Clean up remaining resources for deletion."""
if self._agent_buffer:
self._agent_buffer.destroy()
self._agent_buffer = None | Clean up remaining resources for deletion. | destroy | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def agent_ids(self) -> Set[str]:
"""A list of all agents in the simulation."""
return self._ego_agent_ids | self._social_agent_ids | A list of all agents in the simulation. | agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def ego_agent_ids(self) -> Set[str]:
"""A list of only the active ego agents in the simulation."""
return self._ego_agent_ids | A list of only the active ego agents in the simulation. | ego_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def social_agent_ids(self) -> Set[str]:
"""A list of only the active social agents in the simulation."""
return self._social_agent_ids | A list of only the active social agents in the simulation. | social_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.