Skip to content

[Feature] Composite.separates #2599

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions torchrl/data/tensor_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4339,6 +4339,33 @@ def pop(self, key: NestedKey, default: Any = NO_DEFAULT) -> Any:
return default
raise KeyError(f"{key} not found in composite spec.")

def separates(self, *keys: NestedKey, default: Any = None) -> Composite:
"""Splits the composite spec by extracting specified keys and their associated values into a new composite spec.

This method iterates over the provided keys, removes them from the current composite spec, and adds them to a new
composite spec. If a key is not found, the specified default value is used. The new composite spec is returned.

Args:
*keys (NestedKey):
One or more keys to be extracted from the composite spec. Each key can be a single key or a nested key.
default (Any, optional):
The value to use if a specified key is not found in the composite spec. Defaults to `None`.

Returns:
Composite: A new composite spec containing the extracted keys and their associated values.

Note:
If none of the specified keys are found, the method returns `None`.
"""
out = None
for key in keys:
result = self.pop(key, default=default)
if result is not None:
if out is None:
out = Composite(batch_size=self.batch_size, device=self.device)
out[key] = result
return out

def set(self, name, spec):
if self.locked:
raise RuntimeError("Cannot modify a locked Composite.")
Expand Down
Loading