code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def finish_path(
self,
last_value_r: torch.Tensor | None = None,
last_value_c: torch.Tensor | None = None,
idx: int = 0,
) -> None:
"""Get the data in the buffer.
In vector-on-policy buffer, we get the data from each buffer and then concatenate them.
"""
... | Get the data in the buffer.
In vector-on-policy buffer, we get the data from each buffer and then concatenate them.
| finish_path | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_onpolicy_buffer.py | Apache-2.0 |
def get(self) -> dict[str, torch.Tensor]:
"""Get the data in the buffer.
We provide a trick to standardize the advantages of state-action pairs. We calculate the
mean and standard deviation of the advantages of state-action pairs and then standardize
the advantages of state-action pairs... | Get the data in the buffer.
We provide a trick to standardize the advantages of state-action pairs. We calculate the
mean and standard deviation of the advantages of state-action pairs and then standardize
the advantages of state-action pairs. You can turn on this trick by setting the
`... | get | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_onpolicy_buffer.py | Apache-2.0 |
def forward(self, states, actions):
"""Forward pass of the ensemble model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
Returns:
torch.Tensor: The next states.
"""
n = len(states)
perm = np.random.per... | Forward pass of the ensemble model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
Returns:
torch.Tensor: The next states.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def get_nlls(self, states, actions, next_states):
"""Get the negative log likelihoods.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
next_states (torch.Tensor): The next states.
Returns:
List[float]: The negative l... | Get the negative log likelihoods.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
next_states (torch.Tensor): The next states.
Returns:
List[float]: The negative log likelihoods.
| get_nlls | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def training_step(self, batch):
"""Training step of the ensemble model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
"""
total_loss = 0
for i, model in enumerate(self.models):
loss = model.get_loss(batch, gp=False)
total_loss = total... | Training step of the ensemble model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
| training_step | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def validation_step(self, batch):
"""Validation step of the ensemble model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
"""
for i, model in enumerate(self.models):
loss = model.get_loss(batch)
self.log(f'model/{i}/val_loss', loss.item(), on... | Validation step of the ensemble model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
| validation_step | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, *inputs):
"""Forward pass of the MLP.
Args:
*inputs: The input tensors.
"""
inputs = inputs[0] if len(inputs) == 1 else torch.cat(inputs, dim=-1)
outputs = inputs
for layer in self:
outputs = layer(outputs)
if self._aut... | Forward pass of the MLP.
Args:
*inputs: The input tensors.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def init_cfgs(self, cfgs):
"""Initialize the configuration.
Args:
cfgs: The configurations.
"""
self.batch_size = cfgs.batch_size
self.weight_decay = cfgs.weight_decay
self.lr = cfgs.lr
self.mul_std = cfgs.mul_std | Initialize the configuration.
Args:
cfgs: The configurations.
| init_cfgs | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, states, actions, det=True):
"""Forward pass of the transition model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
det (bool, optional): Whether to use deterministic output. Defaults to True.
"""
outpu... | Forward pass of the transition model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
det (bool, optional): Whether to use deterministic output. Defaults to True.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def get_loss(self, batch, gp=False):
"""Get the loss of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
gp (bool, optional): Whether to use gradient penalty. Defaults to False.
"""
batch['obs'].requires_grad_()
predictions: to... | Get the loss of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
gp (bool, optional): Whether to use gradient penalty. Defaults to False.
| get_loss | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def configure_optimizers(self):
"""Configure the optimizers for the transition model.
Returns:
torch.optim.Optimizer: The optimizer.
"""
return torch.optim.Adam(
self.parameters(),
lr=self.lr,
weight_decay=self.weight_decay,
) | Configure the optimizers for the transition model.
Returns:
torch.optim.Optimizer: The optimizer.
| configure_optimizers | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def training_step(self, batch):
"""Training step of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
Returns:
dict[str, float]: The training loss.
"""
loss = self.get_loss(batch, gp=True)
self.log(f'{self.name}/trainin... | Training step of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
Returns:
dict[str, float]: The training loss.
| training_step | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def validation_step(self, batch):
"""Validation step of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
Returns:
dict[str, float]: The validation loss.
"""
loss = self.get_loss(batch)
self.log(f'{self.name}/val_loss',... | Validation step of the transition model.
Args:
batch (dict[str, torch.Tensor]): The batch data.
Returns:
dict[str, float]: The validation loss.
| validation_step | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def u(self, states, actions=None):
"""Compute the value of the barrier function.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor, optional): The actions. Defaults to None.
"""
if actions is None:
actions = self.policy(states)
n... | Compute the value of the barrier function.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor, optional): The actions. Defaults to None.
| u | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def obj_eval(self, s):
"""Short cut for barrier function.
Args:
s: The states.
Returns:
dict: The results of the barrier function.
"""
h = self.h(s)
u = self.u(s)
eps = self.eps
obj = u + eps
mask = (h < 0) & (u + eps > 0... | Short cut for barrier function.
Args:
s: The states.
Returns:
dict: The results of the barrier function.
| obj_eval | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, states, actions, det=True):
"""Forward pass of the gated transition model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
det (bool, optional): Whether to use deterministic output. Defaults to True.
"""
... | Forward pass of the gated transition model.
Args:
states (torch.Tensor): The states.
actions (torch.Tensor): The actions.
det (bool, optional): Whether to use deterministic output. Defaults to True.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def get_actions(self, states):
"""Sample the actions.
Args:
states (torch.Tensor): The states.
""" | Sample the actions.
Args:
states (torch.Tensor): The states.
| get_actions | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, states: torch.Tensor):
"""Safe exploration policy.
Certify the safety of the action by the barrier function.
Args:
states (torch.Tensor): The states.
"""
device = states.device
assert len(states) == 1
dist = self.policy(states)
... | Safe exploration policy.
Certify the safety of the action by the barrier function.
Args:
states (torch.Tensor): The states.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def __init__(self, policy: NetPolicy, mean, std) -> None:
"""Initialize the policy with Gaussian noise."""
super().__init__()
self.policy = policy
self.mean = mean
self.std = std | Initialize the policy with Gaussian noise. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, states):
"""Forward pass of the policy.
Args:
states (torch.Tensor): The states.
Returns:
torch.Tensor: The actions.
"""
actions = self.policy(states)
if isinstance(actions, TanhNormal):
return TanhNormal(actions.mea... | Forward pass of the policy.
Args:
states (torch.Tensor): The states.
Returns:
torch.Tensor: The actions.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/models.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/models.py | Apache-2.0 |
def forward(self, states: torch.Tensor) -> torch.Tensor:
"""Forward pass of the barrier function.
Args:
states (torch.Tensor): States to evaluate the barrier function.
Returns:
torch.Tensor: Barrier function values.
"""
return (
self.ell(self... | Forward pass of the barrier function.
Args:
states (torch.Tensor): States to evaluate the barrier function.
Returns:
torch.Tensor: Barrier function values.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def find_box(self, h):
"""Find the state box.
Args:
h: Barrier function.
"""
s = torch.empty(10_000, *self.shape, device=self.device)
count = 0
for _i in range(1000):
self.fill_(s)
inside = torch.where(h(s) < 0.0)[0]
if len... | Find the state box.
Args:
h: Barrier function.
| find_box | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def update(self, data, logging=True):
"""Update the state box.
Args:
data (torch.Tensor): Data to update the state box.
logging (bool, optional): Whether to log the state box. Defaults to True.
"""
self._max = self._max.maximum(data.max(dim=0).values)
sel... | Update the state box.
Args:
data (torch.Tensor): Data to update the state box.
logging (bool, optional): Whether to log the state box. Defaults to True.
| update | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def init_cfgs(self, cfgs):
"""Initialize the configuration.
Args:
cfgs: Configuration for the optimization.
"""
self.temperature = cfgs.temperature
self.filter = cfgs.filter
self.n_steps = cfgs.n_steps
self.method = cfgs.method
self.lr = cfg... | Initialize the configuration.
Args:
cfgs: Configuration for the optimization.
| init_cfgs | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def set_temperature(self, p):
"""Set the temperature for the optimizer.
Args:
p (float): Temperature parameter.
"""
max = self.temperature.max
min = self.temperature.min
self.temperature = np.exp(np.log(max) * (1 - p) + np.log(min) * p) | Set the temperature for the optimizer.
Args:
p (float): Temperature parameter.
| set_temperature | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def pdf(self, z):
"""Probability density function for the optimizer.
Args:
z (torch.Tensor): State tensor.
Returns:
Tuple[torch.Tensor, dict]: Probability density function and the result.
"""
s = self.state_box.decode(z)
result = self.core.obj_ev... | Probability density function for the optimizer.
Args:
z (torch.Tensor): State tensor.
Returns:
Tuple[torch.Tensor, dict]: Probability density function and the result.
| pdf | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def project_back(self):
"""Use gradient descent to project s back to the set C_h."""
for _ in range(self.n_proj_iters):
with torch.enable_grad():
h = self.core.h(self.s)
loss = relu(h - 0.03)
if (h > 0.03).sum() < 1000:
brea... | Use gradient descent to project s back to the set C_h. | project_back | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def resample(self, f: torch.Tensor, idx):
"""Resample the states.
Args:
f (torch.Tensor): Probability density function.
idx: Index of the states to resample.
"""
if len(idx) == 0:
return
new_idx = f.softmax(0).multinomial(len(idx), replacement... | Resample the states.
Args:
f (torch.Tensor): Probability density function.
idx: Index of the states to resample.
| resample | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def step(self):
"""One step of the optimizer.
Returns:
torch.Tensor: Loss.
"""
result = self.obj_eval(self.s)
obj = result['hard_obj']
loss = (-obj).mean()
self.opt.zero_grad()
loss.mean().backward()
self.opt.step()
return los... | One step of the optimizer.
Returns:
torch.Tensor: Loss.
| step | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def constrained_optimize(fx, gx, x, opt, reg=0.0): # \grad_y [max_{x: g_y(x) <= 0} f(x)]
"""Constrained optimization.
Args:
fx (torch.Tensor): Function to optimize.
gx (torch.Tensor): Constraint function.
x (torch.Tensor): State tensor.
opt: Optimizer.
reg (float, optio... | Constrained optimization.
Args:
fx (torch.Tensor): Function to optimize.
gx (torch.Tensor): Constraint function.
x (torch.Tensor): State tensor.
opt: Optimizer.
reg (float, optional): Regularization term. Defaults to 0.0.
| constrained_optimize | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def init_cfgs(self, cfgs):
"""Initialize the configuration.
Args:
cfgs: Configuration for the optimizer.
"""
self.weight_decay = cfgs.weight_decay
self.lr = cfgs.lr
self.lambda_2 = cfgs.lambda_2
self.locals = cfgs.locals
self.n_iters = cfgs.n_... | Initialize the configuration.
Args:
cfgs: Configuration for the optimizer.
| init_cfgs | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def train(self) -> Tuple[bool, float]:
"""Train the barrier certificate.
Returns:
Tuple[bool, float]: Whether the training is successful and how to change policy adversarial training frequency.
"""
for _ in track(range(2000), description='Optimizing s...'):
self.... | Train the barrier certificate.
Returns:
Tuple[bool, float]: Whether the training is successful and how to change policy adversarial training frequency.
| train | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def check_by_grad(self):
"""Check if the barrier function is correct by gradient."""
self.s_opt_grad.reinit()
for i in range(10001):
if i % 1000 == 0:
self.s_opt_grad.debug(step=0)
self.s_opt_grad.step() | Check if the barrier function is correct by gradient. | check_by_grad | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/optimizers.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/optimizers.py | Apache-2.0 |
def forward(self, x, inverse=False):
"""Normalize input data.
Args:
x (torch.Tensor): Input data.
inverse (bool): If True, unnormalize the data.
Returns:
torch.Tensor: Normalized data.
"""
if inverse:
return x * self.std + self.me... | Normalize input data.
Args:
x (torch.Tensor): Input data.
inverse (bool): If True, unnormalize the data.
Returns:
torch.Tensor: Normalized data.
| forward | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def update(self, data):
"""Update the normalizer with new data.
Args:
data (torch.Tensor): New data.
"""
data = data - self.mean
m = data.shape[0]
delta = data.mean(dim=0)
new_n = self.n + m
new_mean = self.mean + delta * m / new_n
ne... | Update the normalizer with new data.
Args:
data (torch.Tensor): New data.
| update | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def fit(self, data):
"""Fit the normalizer with new data.
Args:
data (torch.Tensor): New data.
"""
n = data.shape[0]
self.n.set_(torch.tensor(n, device=self.n.device))
self.mean.set_(data.mean(dim=0))
self.std.set_(data.std(dim=0)) | Fit the normalizer with new data.
Args:
data (torch.Tensor): New data.
| fit | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def download_model(url, destination):
"""Download model from the cloud.
Args:
url (str): URL of the model.
destination (str): Path to save the model.
"""
response = requests.get(url)
os.makedirs(os.path.dirname(destination), exist_ok=True)
with open(destination, 'wb') as f:
... | Download model from the cloud.
Args:
url (str): URL of the model.
destination (str): Path to save the model.
| download_model | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def get_pretrained_model(model_path, model_url, device):
"""Get pretrained model.
If the model is not found locally, download it from the cloud.
Args:
model_path (str): Path to save the model.
model_url (str): URL of the model.
device (torch.device): Device to load the model.
... | Get pretrained model.
If the model is not found locally, download it from the cloud.
Args:
model_path (str): Path to save the model.
model_url (str): URL of the model.
device (torch.device): Device to load the model.
Returns:
torch.nn.Module: Pretrained model.
| get_pretrained_model | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def create_model_and_trainer(cfgs, dim_state, dim_action, normalizer, device):
"""Create world model and trainer.
Args:
cfgs: Configs.
dim_state: Dimension of the state.
dim_action: Dimension of the action.
normalizer: Observation normalizer.
device: Device to load the m... | Create world model and trainer.
Args:
cfgs: Configs.
dim_state: Dimension of the state.
dim_action: Dimension of the action.
normalizer: Observation normalizer.
device: Device to load the model.
Returns:
Tuple[nn.Module, pl.Trainer]: World model and trainer.
... | create_model_and_trainer | python | PKU-Alignment/omnisafe | omnisafe/common/control_barrier_function/crabs/utils.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/control_barrier_function/crabs/utils.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-branches
self,
dataset_name: str,
batch_size: int = 256,
gpu_threshold: int = 1024,
device: torch.device = DEVICE_CPU,
) -> None:
"""Initialize the dataset.
Args:
dataset_name: The name of the dataset. cou... | Initialize the dataset.
Args:
dataset_name: The name of the dataset. could be one of the following:
- ``SafetyPointCircle1-v0_mixed_0.5``
- some local .npz file
batch_size: The batch size of the dataset.
gpu_threshold: The threshold of size(M... | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/offline/dataset.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/dataset.py | Apache-2.0 |
def __getitem__(
self,
idx: int,
) -> tuple[torch.Tensor, ...]:
"""Get a single sample from the dataset.
Args:
idx: The index of the sample.
Returns:
A tuple of tensors containing the sample.
"""
if self._pre_transfer:
ret... | Get a single sample from the dataset.
Args:
idx: The index of the sample.
Returns:
A tuple of tensors containing the sample.
| __getitem__ | python | PKU-Alignment/omnisafe | omnisafe/common/offline/dataset.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/dataset.py | Apache-2.0 |
def sample(
self,
) -> tuple[torch.Tensor, ...]:
"""Sample a batch of data from the dataset."""
indices = torch.randint(low=0, high=len(self), size=(self._batch_size,), dtype=torch.int64)
batch_obs = self.obs[indices]
batch_action = self.action[indices]
batch_reward =... | Sample a batch of data from the dataset. | sample | python | PKU-Alignment/omnisafe | omnisafe/common/offline/dataset.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/dataset.py | Apache-2.0 |
def __init__(self, size: int, env_name: str) -> None:
"""Initialize the data collector.
Args:
size (int): The total number of data to collect.
env_name (str): The name of the environment.
"""
self._size = size
self._env_name = env_name
# make a e... | Initialize the data collector.
Args:
size (int): The total number of data to collect.
env_name (str): The name of the environment.
| __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/offline/data_collector.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/data_collector.py | Apache-2.0 |
def register_agent(self, save_dir: str, model_name: str, size: int) -> None:
"""Register an agent to the data collector.
Args:
save_dir (str): The directory of the agent.
model_name (str): The name of the model.
size (int): The number of data to collect from this age... | Register an agent to the data collector.
Args:
save_dir (str): The directory of the agent.
model_name (str): The name of the model.
size (int): The number of data to collect from this agent.
| register_agent | python | PKU-Alignment/omnisafe | omnisafe/common/offline/data_collector.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/data_collector.py | Apache-2.0 |
def collect(self, save_dir: str) -> None:
"""Collect data from the registered agents.
Args:
save_dir (str): The directory to save the collected data.
"""
# check each agent's size
total_size = 0
for agent in self.agents:
assert agent.size <= self.... | Collect data from the registered agents.
Args:
save_dir (str): The directory to save the collected data.
| collect | python | PKU-Alignment/omnisafe | omnisafe/common/offline/data_collector.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/offline/data_collector.py | Apache-2.0 |
def __init__(self, env_id: str, **kwargs: Any) -> None:
"""Initialize an instance of :class:`CMDP`."""
assert (
env_id in self.support_envs()
), f'env_id {env_id} is not supported by {self.__class__.__name__}' | Initialize an instance of :class:`CMDP`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def set_seed(self, seed: int) -> None:
"""Set the seed for this env's random number generator(s).
Args:
seed (int): The seed to use.
""" | Set the seed for this env's random number generator(s).
Args:
seed (int): The seed to use.
| set_seed | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def render(self) -> Any:
"""Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment.
Returns:
The render frames: we recommend to use `np.ndarray`
which could construct video by moviepy.
""" | Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment.
Returns:
The render frames: we recommend to use `np.ndarray`
which could construct video by moviepy.
| render | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device = DEVICE_CPU) -> None:
"""Initialize an instance of :class:`Wrapper`."""
self._env: CMDP = env
self._device: torch.device = device
self.need_evaluation = self._env.need_evaluation | Initialize an instance of :class:`Wrapper`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def __getattr__(self, name: str) -> Any:
"""Get the attribute of the environment.
Args:
name (str): The attribute name.
Returns:
The attribute.
"""
if name.startswith('_'):
raise AttributeError(f'attempted to get missing private attribute {na... | Get the attribute of the environment.
Args:
name (str): The attribute name.
Returns:
The attribute.
| __getattr__ | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment and returns an initial observation.
Args:
seed (int, optional): The random seed. Defaults to None.
opti... | Reset the environment and returns an initial observation.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
observation: The initial observation of the spac... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def __init__(self) -> None:
"""Initialize an instance of :class:`EnvRegister`."""
self._class: dict[str, type[CMDP]]
self._support_envs: dict[str, list[str]]
self._class = {}
self._support_envs = {} | Initialize an instance of :class:`EnvRegister`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def _register(self, env_class: type[CMDP]) -> None:
"""Register the environment class.
Args:
env_class (type[CMDP]): The environment class.
"""
if not inspect.isclass(env_class):
raise TypeError(f'{env_class} must be a class')
class_name = env_class.__nam... | Register the environment class.
Args:
env_class (type[CMDP]): The environment class.
| _register | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def unregister(self, env_class: type[CMDP]) -> type[CMDP]:
"""Remove the environment from the register.
Args:
env_class (type[CMDP]): The environment class.
"""
class_name = env_class.__name__
if class_name not in self._class:
print(f'{class_name} has not... | Remove the environment from the register.
Args:
env_class (type[CMDP]): The environment class.
| unregister | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def get_class(self, env_id: str, class_name: str | None) -> type[CMDP]:
"""Get the environment class.
Args:
env_id (str): The environment id.
class_name (str or None): The environment class name.
Returns:
The environment class.
"""
if class_n... | Get the environment class.
Args:
env_id (str): The environment id.
class_name (str or None): The environment class name.
Returns:
The environment class.
| get_class | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def make(env_id: str, class_name: str | None = None, **kwargs: Any) -> CMDP:
"""Create an environment.
Args:
env_id (str): The environment id.
class_name (str or None): The environment class name.
Keyword Args:
render_mode (str, optional): The render mode ranges from 'human' to 'rg... | Create an environment.
Args:
env_id (str): The environment id.
class_name (str or None): The environment class name.
Keyword Args:
render_mode (str, optional): The render mode ranges from 'human' to 'rgb_array' and 'rgb_array_list'.
Defaults to 'rgb_array'.
camera_n... | make | python | PKU-Alignment/omnisafe | omnisafe/envs/core.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/core.py | Apache-2.0 |
def __init__(
self,
env_id: str,
num_envs: int = 1,
device: str = 'cpu',
**kwargs: Any,
) -> None:
"""Initialize the environment.
Args:
env_id (str): Environment id.
num_envs (int, optional): Number of environments. Defaults to 1.
... | Initialize the environment.
Args:
env_id (str): Environment id.
num_envs (int, optional): Number of environments. Defaults to 1.
device (torch.device, optional): Device to store the data. Defaults to 'cpu'.
Keyword Args:
render_mode (str, optional): The ... | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/crabs_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/crabs_env.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict]:
"""Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options f... | Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
observation: Agent's observation of the current environment.
info: Auxil... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/crabs_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/crabs_env.py | Apache-2.0 |
def sample_action(self) -> torch.Tensor:
"""Sample a random action.
Returns:
A random action.
"""
return torch.as_tensor(
self._env.action_space.sample(),
dtype=torch.float32,
device=self._device,
) | Sample a random action.
Returns:
A random action.
| sample_action | python | PKU-Alignment/omnisafe | omnisafe/envs/crabs_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/crabs_env.py | Apache-2.0 |
def __init__(
self,
env_id: str,
**kwargs: Any, # pylint: disable=unused-argument
) -> None:
"""Initialize CustomEnv with the given environment ID and optional keyword arguments.
.. note::
Optionally, you can specify some environment-specific information that ne... | Initialize CustomEnv with the given environment ID and optional keyword arguments.
.. note::
Optionally, you can specify some environment-specific information that needs to be
logged. You need to complete this operation in two steps:
1. Define the environment information in... | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/custom_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/custom_env.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict]:
"""Reset the environment.
Args:
seed (int, optional): The random seed to use for the environment. Defaults to None.
options (dict[str, Any... | Reset the environment.
Args:
seed (int, optional): The random seed to use for the environment. Defaults to None.
options (dict[str, Any], optional): Additional options. Defaults to None.
Returns:
tuple[torch.Tensor, dict]: A tuple containing:
- obs (... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/custom_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/custom_env.py | Apache-2.0 |
def spec_log(self, logger: Logger) -> None:
"""Log specific environment into logger.
.. note::
This function will be called after each episode.
Args:
logger (Logger): The logger to use for logging.
""" | Log specific environment into logger.
.. note::
This function will be called after each episode.
Args:
logger (Logger): The logger to use for logging.
| spec_log | python | PKU-Alignment/omnisafe | omnisafe/envs/custom_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/custom_env.py | Apache-2.0 |
def __init__(
self,
env_id: str,
num_envs: int = 1,
device: torch.device = DEVICE_CPU,
**kwargs: Any, # pylint: disable=unused-argument
) -> None:
"""Initialize an instance of :class:`SafetyMetaDriveEnv`."""
super().__init__(env_id)
self._num_envs = n... | Initialize an instance of :class:`SafetyMetaDriveEnv`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/meta_drive_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/meta_drive_env.py | Apache-2.0 |
def spec_log(self, logger: Logger) -> None:
"""Log the success rate into the logger."""
logger.store({'Env/Success_rate': np.mean(self.env_spec_log['Env/Success_rate'])})
self.env_spec_log['Env/Success_rate'] = [] | Log the success rate into the logger. | spec_log | python | PKU-Alignment/omnisafe | omnisafe/envs/meta_drive_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/meta_drive_env.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment.
Args:
seed (int or None, optional): Seed to reset the environment.
Defaults to None.
Retu... | Reset the environment.
Args:
seed (int or None, optional): Seed to reset the environment.
Defaults to None.
Returns:
observation: Agent's observation of the current environment.
info: Some information logged by the environment.
| reset | python | PKU-Alignment/omnisafe | omnisafe/envs/meta_drive_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/meta_drive_env.py | Apache-2.0 |
def __init__(
self,
env_id: str,
num_envs: int = 1,
device: torch.device = DEVICE_CPU,
**kwargs: Any,
) -> None:
"""Initialize an instance of :class:`SafetyGymnasiumEnv`."""
super().__init__(env_id)
self._num_envs = num_envs
self._device = torc... | Initialize an instance of :class:`SafetyGymnasiumEnv`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_env.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The... | Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
observation: Agent's observation of the current environment.
info: Some ... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_env.py | Apache-2.0 |
def __init__(
self,
env_id: str,
num_envs: int = 1,
device: str = 'cpu',
use_lidar: bool = False,
**kwargs: Any,
) -> None:
"""Initialize the environment.
Args:
env_id (str): Environment id.
num_envs (int, optional): Number of ... | Initialize the environment.
Args:
env_id (str): Environment id.
num_envs (int, optional): Number of environments. Defaults to 1.
device (torch.device, optional): Device to store the data. Defaults to 'cpu'.
use_lidar (bool, optional): Whether to use lidar observa... | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def get_cost_from_obs_tensor(self, obs: torch.Tensor, is_binary: bool = True) -> torch.Tensor:
"""Get batch cost from batch observation.
Args:
obs (torch.Tensor): Batch observation.
is_binary (bool, optional): Whether to use binary cost. Defaults to True.
Returns:
... | Get batch cost from batch observation.
Args:
obs (torch.Tensor): Batch observation.
is_binary (bool, optional): Whether to use binary cost. Defaults to True.
Returns:
cost: Batch cost.
| get_cost_from_obs_tensor | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def get_lidar_from_coordinate(self, obs: np.ndarray) -> torch.Tensor:
"""Get lidar observation.
Args:
obs (np.ndarray): The observation.
Returns:
lidar_obs: The lidar observation.
"""
robot_matrix_x_y = obs[self.key_to_slice['robot_m']]
robot_mat... | Get lidar observation.
Args:
obs (np.ndarray): The observation.
Returns:
lidar_obs: The lidar observation.
| get_lidar_from_coordinate | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def _ego_xy(
self,
robot_matrix: list[list[float]],
robot_pos: np.ndarray,
pos: np.ndarray,
) -> np.ndarray:
"""Return the egocentric XY vector to a position from the robot.
Args:
robot_matrix (list[list[float]]): 3x3 rotation matrix.
robot_po... | Return the egocentric XY vector to a position from the robot.
Args:
robot_matrix (list[list[float]]): 3x3 rotation matrix.
robot_pos (np.ndarray): 2D robot position.
pos (np.ndarray): 2D position.
Returns:
2D_egocentric_vector: The 2D egocentric vector.
... | _ego_xy | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def _obs_lidar_pseudo(
self,
robot_matrix: list[list[float]],
robot_pos: np.ndarray,
positions: list[np.ndarray],
) -> np.ndarray: # pylint: disable=too-many-locals
"""Return a robot-centric lidar observation of a list of positions.
Lidar is a set of bins around the... | Return a robot-centric lidar observation of a list of positions.
Lidar is a set of bins around the robot (divided evenly in a circle).
The detection directions are exclusive and exhaustive for a full 360 view.
Each bin reads 0 if there are no objects in that direction.
If there are mult... | _obs_lidar_pseudo | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def _get_flat_coordinate(self, coordinate_obs: dict[str, Any]) -> np.ndarray:
"""Get the flattened obs.
Args:
coordinate_obs (dict[str, Any]): The dict of coordinate and sensor observations.
Returns:
flat_obs: The flattened observation.
"""
assert (
... | Get the flattened obs.
Args:
coordinate_obs (dict[str, Any]): The dict of coordinate and sensor observations.
Returns:
flat_obs: The flattened observation.
| _get_flat_coordinate | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def _get_coordinate_sensor(self) -> dict[str, Any]:
"""Return the coordinate observation and sensor observation.
We will ignore the z-axis coordinates in every poses.
The returned obs coordinates are all in the robot coordinates.
Returns:
coordinate_obs: The coordinate obse... | Return the coordinate observation and sensor observation.
We will ignore the z-axis coordinates in every poses.
The returned obs coordinates are all in the robot coordinates.
Returns:
coordinate_obs: The coordinate observation.
| _get_coordinate_sensor | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def _dist_xy(
self,
pos1: np.ndarray | list[np.ndarray],
pos2: np.ndarray | list[np.ndarray],
) -> float:
"""Return the distance from the robot to an XY position.
Args:
pos1 (np.ndarray | list[np.ndarray]): The first position.
pos2 (np.ndarray | list[... | Return the distance from the robot to an XY position.
Args:
pos1 (np.ndarray | list[np.ndarray]): The first position.
pos2 (np.ndarray | list[np.ndarray]): The second position.
Returns:
distance: The distance between the two positions.
| _dist_xy | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The... | Reset the environment.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
observation: The initial observation of the space.
info: Some informati... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_gymnasium_modelbased.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_gymnasium_modelbased.py | Apache-2.0 |
def __init__(
self,
env_id: str,
num_envs: int = 1,
device: torch.device = DEVICE_CPU,
**kwargs: Any,
) -> None:
"""Initialize an instance of :class:`SafetyIsaacGymEnv`."""
super().__init__(env_id)
self._num_envs = num_envs
self._device = torch... | Initialize an instance of :class:`SafetyIsaacGymEnv`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/safety_isaac_gym_env.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/safety_isaac_gym_env.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment.
.. note::
Additionally, the time step will be reset to 0.
Args:
seed (int, optional): The ran... | Reset the environment.
.. note::
Additionally, the time step will be reset to 0.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environment. Defaults to None.
Returns:
obser... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device) -> None:
"""Initialize an instance of :class:`AutoReset`."""
super().__init__(env=env, device=device)
assert self.num_envs == 1, 'AutoReset only supports single environment' | Initialize an instance of :class:`AutoReset`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device, norm: Normalizer | None = None) -> None:
"""Initialize an instance of :class:`ObsNormalize`."""
super().__init__(env=env, device=device)
assert isinstance(self.observation_space, spaces.Box), 'Observation space must be Box'
self._obs_no... | Initialize an instance of :class:`ObsNormalize`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def save(self) -> dict[str, torch.nn.Module]:
"""Save the observation normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
... | Save the observation normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
reward_normalize, and cost_normalize. When evaluating the... | save | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device, norm: Normalizer | None = None) -> None:
"""Initialize an instance of :class:`RewardNormalize`."""
super().__init__(env=env, device=device)
self._reward_normalizer: Normalizer
if norm is not None:
self._reward_normalizer = ... | Initialize an instance of :class:`RewardNormalize`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def save(self) -> dict[str, torch.nn.Module]:
"""Save the reward normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
rewar... | Save the reward normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
reward_normalize, and cost_normalize.
Returns:
... | save | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device, norm: Normalizer | None = None) -> None:
"""Initialize an instance of :class:`CostNormalize`."""
super().__init__(env=env, device=device)
self._cost_normalizer: Normalizer
if norm is not None:
self._cost_normalizer = norm.t... | Initialize an instance of :class:`CostNormalize`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def save(self) -> dict[str, torch.nn.Module]:
"""Save the cost normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
reward_... | Save the cost normalizer.
.. note::
The saved components will be stored in the wrapped environment. If the environment is
not wrapped, the saved components will be empty dict. common wrappers are obs_normalize,
reward_normalize, and cost_normalize.
Returns:
... | save | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(
self,
env: CMDP,
device: torch.device,
low: float,
high: float,
) -> None:
"""Initialize an instance of :class:`ActionScale`."""
super().__init__(env=env, device=device)
assert isinstance(self.action_space, spaces.Box), 'Action space must... | Initialize an instance of :class:`ActionScale`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(
self,
env: CMDP,
times: int,
device: torch.device,
) -> None:
"""Initialize the wrapper.
Args:
env: The environment to wrap.
times: The number of times to repeat the action.
device: The device to use.
"""
... | Initialize the wrapper.
Args:
env: The environment to wrap.
times: The number of times to repeat the action.
device: The device to use.
| __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def __init__(self, env: CMDP, device: torch.device) -> None:
"""Initialize an instance of :class:`Unsqueeze`."""
super().__init__(env=env, device=device)
assert self.num_envs == 1, 'Unsqueeze only works with single environment'
assert isinstance(self.observation_space, spaces.Box), 'Obse... | Initialize an instance of :class:`Unsqueeze`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def reset(
self,
seed: int | None = None,
options: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""Reset the environment and returns a new observation.
.. note::
The vector information will be unsqueezed to (1, dim) for agent training.
... | Reset the environment and returns a new observation.
.. note::
The vector information will be unsqueezed to (1, dim) for agent training.
Args:
seed (int, optional): The random seed. Defaults to None.
options (dict[str, Any], optional): The options for the environmen... | reset | python | PKU-Alignment/omnisafe | omnisafe/envs/wrapper.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/wrapper.py | Apache-2.0 |
def is_state_safe(self, states):
"""Check if the state is safe."""
# return states[..., 1].abs() <= self.threshold
return self.barrier_fn(states) <= 1.0 | Check if the state is safe. | is_state_safe | python | PKU-Alignment/omnisafe | omnisafe/envs/classic_control/envs_from_crabs.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/envs/classic_control/envs_from_crabs.py | Apache-2.0 |
def __init__(
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
hidden_sizes: list[int],
activation: Activation = 'relu',
weight_initialization_mode: InitFunction = 'kaiming_uniform',
) -> None:
"""Initialize an instance of :class:`Actor`."""
n... | Initialize an instance of :class:`Actor`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def _distribution(self, obs: torch.Tensor) -> Distribution:
r"""Return the distribution of action.
An actor generates a distribution, which is used to sample actions during training. When
training, the mean and the variance of the distribution are used to calculate the loss. When
testin... | Return the distribution of action.
An actor generates a distribution, which is used to sample actions during training. When
training, the mean and the variance of the distribution are used to calculate the loss. When
testing, the mean of the distribution is used directly as actions.
Fo... | _distribution | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def forward(self, obs: torch.Tensor) -> Distribution:
"""Return the distribution of action.
Args:
obs (torch.Tensor): Observation from environments.
""" | Return the distribution of action.
Args:
obs (torch.Tensor): Observation from environments.
| forward | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def predict(
self,
obs: torch.Tensor,
deterministic: bool = False,
) -> torch.Tensor:
r"""Predict deterministic or stochastic action based on observation.
- ``deterministic`` = ``True`` or ``False``
When training the actor, one important trick to avoid local minimum... | Predict deterministic or stochastic action based on observation.
- ``deterministic`` = ``True`` or ``False``
When training the actor, one important trick to avoid local minimum is to use stochastic
actions, which can simply be achieved by sampling actions from the distribution (set
``d... | predict | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def log_prob(self, act: torch.Tensor) -> torch.Tensor:
"""Return the log probability of action under the distribution.
:meth:`log_prob` only can be called after calling :meth:`predict` or :meth:`forward`.
Args:
act (torch.Tensor): The action.
Returns:
The log p... | Return the log probability of action under the distribution.
:meth:`log_prob` only can be called after calling :meth:`predict` or :meth:`forward`.
Args:
act (torch.Tensor): The action.
Returns:
The log probability of action under the distribution.
| log_prob | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def __init__(
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
hidden_sizes: list[int],
activation: Activation = 'relu',
weight_initialization_mode: InitFunction = 'kaiming_uniform',
num_critics: int = 1,
use_obs_encoder: bool = False,
) -> No... | Initialize an instance of :class:`Critic`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/models/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/base.py | Apache-2.0 |
def __init__(
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
hidden_sizes: list[int],
activation: Activation = 'relu',
weight_initialization_mode: InitFunction = 'kaiming_uniform',
) -> None:
"""Initialize an instance of :class:`ActorBuilder`."""
... | Initialize an instance of :class:`ActorBuilder`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/models/actor/actor_builder.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/actor_builder.py | Apache-2.0 |
def build_actor(
self,
actor_type: ActorType,
) -> Actor:
"""Build actor network.
Currently, we support the following actor types:
- ``gaussian_learning``: Gaussian actor with learnable standard deviation parameters.
- ``gaussian_sac``: Gaussian actor with le... | Build actor network.
Currently, we support the following actor types:
- ``gaussian_learning``: Gaussian actor with learnable standard deviation parameters.
- ``gaussian_sac``: Gaussian actor with learnable standard deviation network.
- ``mlp``: Multi-layer perceptron actor, ... | build_actor | python | PKU-Alignment/omnisafe | omnisafe/models/actor/actor_builder.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/actor_builder.py | Apache-2.0 |
def __init__(
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
hidden_sizes: list[int],
activation: Activation = 'relu',
weight_initialization_mode: InitFunction = 'kaiming_uniform',
) -> None:
"""Initialize an instance of :class:`GaussianLearningActo... | Initialize an instance of :class:`GaussianLearningActor`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/models/actor/gaussian_learning_actor.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_learning_actor.py | Apache-2.0 |
def _distribution(self, obs: torch.Tensor) -> Normal:
"""Get the distribution of the actor.
.. warning::
This method is not supposed to be called by users. You should call :meth:`forward`
instead.
Args:
obs (torch.Tensor): Observation from environments.
... | Get the distribution of the actor.
.. warning::
This method is not supposed to be called by users. You should call :meth:`forward`
instead.
Args:
obs (torch.Tensor): Observation from environments.
Returns:
The normal distribution of the mean and... | _distribution | python | PKU-Alignment/omnisafe | omnisafe/models/actor/gaussian_learning_actor.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_learning_actor.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.