python_utils
A set of utility functions for general python usage
CachedFunctions
Thin object which owns a dictionary in which each entry should be a function -- when a key is queried via get() and it exists, it will call the function exactly once, and cache the value so that subsequent calls will refer to the cached value.
This allows the dictionary to be created with potentially expensive operations, but only queried up to exaclty once as needed.
Source code in omnigibson/utils/python_utils.py
add_fcn(name, fcn)
Adds a function to the internal registry.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the function. This is the name that should be queried with self.get() |
required |
fcn
|
function
|
Function to add. Can be an arbitrary signature |
required |
Source code in omnigibson/utils/python_utils.py
get(name, *args, **kwargs)
Computes the function referenced by @name with the corresponding @args and @kwargs. Note that for a unique set of arguments, this value will be internally cached
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the function to call |
required |
*args
|
tuple
|
Positional arguments to pass into the function call |
()
|
**kwargs
|
tuple
|
Keyword arguments to pass into the function call |
{}
|
Returns:
Type | Description |
---|---|
any
|
Output of the function referenced by @name |
Source code in omnigibson/utils/python_utils.py
get_fcn(name)
Gets the raw stored function referenced by @name
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the function to grab |
required |
Returns:
Type | Description |
---|---|
function
|
The stored function |
get_fcn_names()
Get all stored function names
Returns:
Type | Description |
---|---|
tuple of str
|
Names of stored functions |
Recreatable
Simple class that provides an abstract interface automatically saving init args of the classes inheriting it.
Source code in omnigibson/utils/python_utils.py
get_init_info()
Grabs relevant initialization information for this class instance. Useful for directly reloading an object from this information, using @create_object_from_init_info.
Returns:
Type | Description |
---|---|
dict
|
Nested dictionary that contains this object's initialization information |
Source code in omnigibson/utils/python_utils.py
RecreatableAbcMeta
Bases: RecreatableMeta
, ABCMeta
A composite metaclass of both RecreatableMeta and ABCMeta.
Adding in ABCMeta to resolve metadata conflicts.
Source code in omnigibson/utils/python_utils.py
RecreatableMeta
Bases: type
Simple metaclass that automatically saves init args of the instances it creates.
Source code in omnigibson/utils/python_utils.py
Registerable
Simple class template that provides an abstract interface for registering classes.
Source code in omnigibson/utils/python_utils.py
__init_subclass__(**kwargs)
Registers all subclasses as part of this registry. This is useful to decouple internal codebase from external user additions. This way, users can add their custom subclasses by simply extending this class, and it will automatically be registered internally. This allows users to then specify their classes directly in string-form in e.g., their config files, without having to manually set the str-to-class mapping in our code.
Source code in omnigibson/utils/python_utils.py
Serializable
Simple class that provides an abstract interface to dump / load states, optionally with serialized functionality as well.
Source code in omnigibson/utils/python_utils.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
|
deserialize(state)
De-serializes flattened 1D numpy array @state into nested dictionary state. Should be implemented by subclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
n - array
|
encoded + serialized, 1D numerical th.tensor capturing this object's state |
required |
Returns:
Type | Description |
---|---|
2 - tuple
|
|
Source code in omnigibson/utils/python_utils.py
dump_state(serialized=False)
Dumps the state of this object in either dictionary of flattened numerical form.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
serialized
|
bool
|
If True, will return the state of this object as a 1D numpy array. Otherewise, will return a (potentially nested) dictionary of states for this object |
False
|
Returns:
Type | Description |
---|---|
dict or n - array
|
Either: - Keyword-mapped states of this object, or - encoded + serialized, 1D numerical th.tensor capturing this object's state |
Source code in omnigibson/utils/python_utils.py
load_state(state, serialized=False)
Deserializes and loads this object's state based on @state
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
dict or n - array
|
Either: - Keyword-mapped states of this object, or - encoded + serialized, 1D numerical th.tensor capturing this object's state. |
required |
serialized
|
bool
|
If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is a (potentially nested) dictionary of states for this object |
False
|
Source code in omnigibson/utils/python_utils.py
serialize(state)
Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency. Should be implemented by subclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
dict
|
Keyword-mapped states of this object to encode. Should match structure of output from self._dump_state() |
required |
Returns:
Type | Description |
---|---|
n - array
|
encoded + serialized, 1D numerical th.tensor capturing this object's state |
Source code in omnigibson/utils/python_utils.py
SerializableNonInstance
Identical to Serializable, but intended for non-instanceable classes
Source code in omnigibson/utils/python_utils.py
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
deserialize(state)
classmethod
De-serializes flattened 1D numpy array @state into nested dictionary state. Should be implemented by subclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
n - array
|
encoded + serialized, 1D numerical th.tensor capturing this object's state |
required |
Returns:
Type | Description |
---|---|
2 - tuple
|
|
Source code in omnigibson/utils/python_utils.py
dump_state(serialized=False)
classmethod
Dumps the state of this object in either dictionary of flattened numerical form.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
serialized
|
bool
|
If True, will return the state of this object as a 1D numpy array. Otherewise, will return a (potentially nested) dictionary of states for this object |
False
|
Returns:
Type | Description |
---|---|
dict or n - array
|
Either: - Keyword-mapped states of this object, or - encoded + serialized, 1D numerical th.tensor capturing this object's state. |
Source code in omnigibson/utils/python_utils.py
load_state(state, serialized=False)
classmethod
Deserializes and loads this object's state based on @state
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
dict or n - array
|
Either: - Keyword-mapped states of this object, or - encoded + serialized, 1D numerical th.tensor capturing this object's state. |
required |
serialized
|
bool
|
If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is a (potentially nested) dictionary of states for this object |
False
|
Source code in omnigibson/utils/python_utils.py
serialize(state)
classmethod
Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency. Should be implemented by subclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
dict
|
Keyword-mapped states of this object to encode. Should match structure of output from self._dump_state() |
required |
Returns:
Type | Description |
---|---|
n - array
|
encoded + serialized, 1D numerical th.tensor capturing this object's state |
Source code in omnigibson/utils/python_utils.py
Wrapper
Base class for all wrappers in OmniGibson
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
any
|
Arbitrary python object instance to wrap |
required |
Source code in omnigibson/utils/python_utils.py
unwrapped
property
Grabs unwrapped object
Returns:
Type | Description |
---|---|
any
|
The unwrapped object instance |
assert_valid_key(key, valid_keys, name=None)
Helper function that asserts that @key is in dictionary @valid_keys keys. If not, it will raise an error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
any
|
key to check for in dictionary @dic's keys |
required |
valid_keys
|
Iterable
|
contains keys should be checked with @key |
required |
name
|
str or None
|
if specified, is the name associated with the key that will be printed out if the key is not found. If None, default is "value" |
None
|
Source code in omnigibson/utils/python_utils.py
clear()
create_class_from_registry_and_config(cls_name, cls_registry, cfg, cls_type_descriptor)
Helper function to create a class with str type @cls_name, which should be a valid entry in @cls_registry, using kwargs in dictionary form @cfg to pass to the constructor, with @cls_type_name specified for debugging
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls_name
|
str
|
Name of the class to create. This should correspond to the actual class type, in string form |
required |
cls_registry
|
dict
|
Class registry. This should map string names of valid classes to create to the actual class type itself |
required |
cfg
|
dict
|
Any keyword arguments to pass to the class constructor |
required |
cls_type_descriptor
|
str
|
Description of the class type being created. This can be any string and is used solely for debugging purposes |
required |
Returns:
Type | Description |
---|---|
any
|
Created class instance |
Source code in omnigibson/utils/python_utils.py
create_object_from_init_info(init_info)
Create a new object based on given init info.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_info
|
dict
|
Nested dictionary that contains an object's init information. |
required |
Returns:
Type | Description |
---|---|
any
|
Newly created object. |
Source code in omnigibson/utils/python_utils.py
extract_class_init_kwargs_from_dict(cls, dic, copy=False)
Helper function to return a dictionary of key-values that specifically correspond to @cls class's init constructor method, from @dic which may or may not contain additional, irrelevant kwargs. Note that @dic may possibly be missing certain kwargs as specified by cls.init. No error will be raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
object
|
Class from which to grab init kwargs that will be be used as filtering keys for @dic |
required |
dic
|
dict
|
Dictionary containing multiple key-values |
required |
copy
|
bool
|
If True, will deepcopy all values corresponding to the specified @keys |
False
|
Returns:
Type | Description |
---|---|
dict
|
Extracted subset dictionary possibly containing only the specified keys from cls.init and their corresponding values |
Source code in omnigibson/utils/python_utils.py
extract_subset_dict(dic, keys, copy=False)
Helper function to extract a subset of dictionary key-values from a current dictionary. Optionally (deep)copies the values extracted from the original @dic if @copy is True.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dic
|
dict
|
Dictionary containing multiple key-values |
required |
keys
|
Iterable
|
Specific keys to extract from @dic. If the key doesn't exist in @dic, then the key is skipped |
required |
copy
|
bool
|
If True, will deepcopy all values corresponding to the specified @keys |
False
|
Returns:
Type | Description |
---|---|
dict
|
Extracted subset dictionary containing only the specified @keys and their corresponding values |
Source code in omnigibson/utils/python_utils.py
get_class_init_kwargs(cls)
Helper function to return a list of all valid keyword arguments (excluding "self") for the given @cls class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
object
|
Class from which to grab init kwargs |
required |
Returns:
Type | Description |
---|---|
list
|
All keyword arguments (excluding "self") specified by @cls init constructor method |
Source code in omnigibson/utils/python_utils.py
get_uuid(name, n_digits=8, deterministic=True)
Helper function to create a unique @n_digits uuid given a unique @name
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the object or class |
required |
n_digits
|
int
|
Number of digits of the uuid, default is 8 |
8
|
deterministic
|
bool
|
Whether the outputted UUID should be deterministic or not |
True
|
Returns:
Type | Description |
---|---|
int
|
uuid |
Source code in omnigibson/utils/python_utils.py
meets_minimum_version(test_version, minimum_version)
Verify that @test_version meets the @minimum_version
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test_version
|
str
|
Python package version. Should be, e.g., 0.26.1 |
required |
minimum_version
|
str
|
Python package version to test against. Should be, e.g., 0.27.2 |
required |
Returns:
Type | Description |
---|---|
bool
|
Whether @test_version meets @minimum_version |
Source code in omnigibson/utils/python_utils.py
merge_nested_dicts(base_dict, extra_dict, inplace=False, verbose=False)
Iteratively updates @base_dict with values from @extra_dict. Note: This generates a new dictionary!
Parameters:
Name | Type | Description | Default |
---|---|---|---|
base_dict
|
dict
|
Nested base dictionary, which should be updated with all values from @extra_dict |
required |
extra_dict
|
dict
|
Nested extra dictionary, whose values will overwrite corresponding ones in @base_dict |
required |
inplace
|
bool
|
Whether to modify @base_dict in place or not |
False
|
verbose
|
bool
|
If True, will print when keys are mismatched |
False
|
Returns:
Type | Description |
---|---|
dict
|
Updated dictionary |
Source code in omnigibson/utils/python_utils.py
multi_dim_linspace(start, stop, num)
Generate a tensor with evenly spaced values along multiple dimensions. This function creates a tensor where each slice along the first dimension contains values linearly interpolated between the corresponding elements of 'start' and 'stop'. It's similar to numpy.linspace but works with multi-dimensional inputs in PyTorch. Args: start (th.Tensor): Starting values for each dimension. stop (th.Tensor): Ending values for each dimension. num (int): Number of samples to generate along the interpolated dimension. Returns: th.Tensor: A tensor of shape (num, *start.shape) containing the interpolated values. Example: >>> start = th.tensor([0, 10, 100]) >>> stop = th.tensor([1, 20, 200]) >>> result = multi_dim_linspace(start, stop, num=5) >>> print(result.shape) torch.Size([5, 3]) >>> print(result) tensor([[ 0.0000, 10.0000, 100.0000], [ 0.2500, 12.5000, 125.0000], [ 0.5000, 15.0000, 150.0000], [ 0.7500, 17.5000, 175.0000], [ 1.0000, 20.0000, 200.0000]])
Source code in omnigibson/utils/python_utils.py
nums2array(nums, dim, dtype=th.float32)
Converts input @nums into numpy array of length @dim. If @nums is a single number, broadcasts input to corresponding dimension size @dim before converting into numpy array
Parameters:
Name | Type | Description | Default |
---|---|---|---|
nums
|
float or array
|
Numbers to map to numpy array |
required |
dim
|
int
|
Size of array to broadcast input to |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Mapped input numbers |
Source code in omnigibson/utils/python_utils.py
save_init_info(func)
Decorator to save the init info of an object to object._init_info.
_init_info contains class name and class constructor's input args.
Source code in omnigibson/utils/python_utils.py
subclass_factory(name, base_classes, __init__=None, **kwargs)
Programmatically generates a new class type with name @name, subclassing from base classes @base_classes, with corresponding init call @init.
NOTE: If init is None (default), the init call from @base_classes will be used instead.
cf. https://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Generated class name |
required |
base_classes
|
type, or list of type
|
Base class(es) to use for generating the subclass |
required |
__init__
|
None or function
|
Init call to use for the base class when it is instantiated. If None if specified, the newly generated class will automatically inherit the init call from @base_classes |
None
|
**kwargs
|
any
|
keyword-mapped parameters to override / set in the child class, where the keys represent the class / instance attribute to modify and the values represent the functions / value to set |
{}
|
Source code in omnigibson/utils/python_utils.py
torch_delete(tensor, indices, dim=None)
Delete elements from a tensor along a specified dimension.
Parameters: tensor (torch.Tensor): Input tensor. indices (int or torch.Tensor): Indices of elements to remove. dim (int, optional): The dimension along which to delete the elements. If None, the tensor is flattened before deletion.
Returns: torch.Tensor: Tensor with specified elements removed.