index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
47,721
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/_deeplab.py
159,160
135,168
forward
ASPP
160,168
160,168
class ASPP(nn.Module): def __init__(self, in_channels, atrous_rates): super(ASPP, self).__init__() out_channels = 256 modules = [] modules.append(nn.Sequential( nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.R...
class ASPP(nn.Module): def __init__(self, in_channels, atrous_rates): super(ASPP, self).__init__() out_channels = 256 modules = [] modules.append(nn.Sequential( nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.R...
res = [] for conv in self.convs: res.append(conv(x)) res = torch.cat(res, dim=1) return self.project(res)
res = [] for conv in self.convs: res.append(conv(x)) res = torch.cat(res, dim=1) return self.project(res)
14
356
60
416
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
47,722
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/_deeplab.py
130,131
122,135
forward
ASPPPooling
131,135
131,135
class ASPPPooling(nn.Sequential): def __init__(self, in_channels, out_channels): super(ASPPPooling, self).__init__( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)) def forw...
class ASPPPooling(nn.Sequential): def __init__(self, in_channels, out_channels): super(ASPPPooling, self).__init__( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)) def forw...
size = x.shape[-2:] x = super(ASPPPooling, self).forward(x) return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
size = x.shape[-2:] x = super(ASPPPooling, self).forward(x) return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
12
137
62
199
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
47,723
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/_deeplab.py
105,106
87,113
_init_weight
AtrousSeparableConvolution
106,113
106,113
class AtrousSeparableConvolution(nn.Module): """ Atrous Separable Convolution """ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=True): super(AtrousSeparableConvolution, self).__init__() self.body = nn.Sequential( ...
class AtrousSeparableConvolution(nn.Module): """ Atrous Separable Convolution """ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=True): super(AtrousSeparableConvolution, self).__init__() self.body = nn.Sequential( ...
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
16
263
106
369
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
47,724
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/_deeplab.py
79,80
63,87
_init_weight
DeepLabHead
80,87
80,87
class DeepLabHead(nn.Module): def __init__(self, in_channels, num_classes, aspp_dilate=[12, 24, 36]): super(DeepLabHead, self).__init__() self.classifier = nn.Sequential( ASPP(in_channels, aspp_dilate), nn.Conv2d(256, 256, 3, padding=1, bias=False), nn.BatchNorm2...
class DeepLabHead(nn.Module): def __init__(self, in_channels, num_classes, aspp_dilate=[12, 24, 36]): super(DeepLabHead, self).__init__() self.classifier = nn.Sequential( ASPP(in_channels, aspp_dilate), nn.Conv2d(256, 256, 3, padding=1, bias=False), nn.BatchNorm2...
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
16
228
106
334
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
47,725
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/_deeplab.py
49,50
30,63
forward
DeepLabHeadV3Plus
50,55
50,55
class DeepLabHeadV3Plus(nn.Module): def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36]): super(DeepLabHeadV3Plus, self).__init__() self.project = nn.Sequential( nn.Conv2d(low_level_channels, 48, 1, bias=False), nn.BatchNorm2d(48), ...
class DeepLabHeadV3Plus(nn.Module): def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36]): super(DeepLabHeadV3Plus, self).__init__() self.project = nn.Sequential( nn.Conv2d(low_level_channels, 48, 1, bias=False), nn.BatchNorm2d(48), ...
low_level_feature = self.project( feature['low_level'] ) output_feature = self.aspp(feature['out']) output_feature = F.interpolate(output_feature, size=low_level_feature.shape[2:], mode='bilinear', align_corners=False) return self.classifier( torch.cat( [ low_level_feature, output_featur...
low_level_feature = self.project( feature['low_level'] ) output_feature = self.aspp(feature['out']) output_feature = F.interpolate(output_feature, size=low_level_feature.shape[2:], mode='bilinear', align_corners=False) return self.classifier( torch.cat( [ low_level_feature, output_featur...
24
404
114
518
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel __all__ = ["DeepLabV3"] class DeepLabV3(_SimpleSegmentationModel): """ Implements DeepLabV3 model from `"Rethinking Atrous Convolu...
47,727
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/s2m_resnet.py
48,49
28,71
forward
Bottleneck
49,71
49,71
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = in...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = in...
identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = se...
identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = se...
43
314
165
479
import torch import torch.nn as nn try: from torchvision.models.utils import load_state_dict_from_url except ModuleNotFoundError: from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet...
import torch import torch.nn as nn try: from torchvision.models.utils import load_state_dict_from_url except ModuleNotFoundError: from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet...
47,728
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/s2m_resnet.py
122,123
71,164
_make_layer
ResNet
123,146
123,146
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = ...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = ...
norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(sel...
norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(sel...
68
1,032
288
1,320
import torch import torch.nn as nn try: from torchvision.models.utils import load_state_dict_from_url except ModuleNotFoundError: from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet...
import torch import torch.nn as nn try: from torchvision.models.utils import load_state_dict_from_url except ModuleNotFoundError: from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet...
47,729
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/utils.py
71,72
23,79
forward
IntermediateLayerGetter
72,79
72,79
class IntermediateLayerGetter(nn.ModuleDict): """ Module wrapper that returns intermediate layers from a model It has a strong assumption that the modules have been registered into the model in the same order as they are used. This means that one should **not** reuse the same nn.Module twice in...
class IntermediateLayerGetter(nn.ModuleDict): """ Module wrapper that returns intermediate layers from a model It has a strong assumption that the modules have been registered into the model in the same order as they are used. This means that one should **not** reuse the same nn.Module twice in...
out = OrderedDict() for name, module in self.named_children(): x = module(x) if name in self.return_layers: out_name = self.return_layers[name] out[out_name] = x return out
out = OrderedDict() for name, module in self.named_children(): x = module(x) if name in self.return_layers: out_name = self.return_layers[name] out[out_name] = x return out
23
640
76
716
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from collections import OrderedDict class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__in...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from collections import OrderedDict class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__in...
47,730
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m/utils.py
15,16
9,23
forward
_SimpleSegmentationModel
16,23
16,23
class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__init__() self.backbone = backbone self.classifier = classifier def forward(self, x): FILL_FUNC_BODY
class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__init__() self.backbone = backbone self.classifier = classifier def forward(self, x): FILL_FUNC_BODY
input_shape = x.shape[-2:] features = self.backbone(x) x = self.classifier(features) x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False) return x
input_shape = x.shape[-2:] features = self.backbone(x) x = self.classifier(features) x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False) return x
17
80
80
160
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from collections import OrderedDict class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__in...
# Credit: https://github.com/VainF/DeepLabV3Plus-Pytorch import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from collections import OrderedDict class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier): super(_SimpleSegmentationModel, self).__in...
47,731
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/s2m_controller.py
21,22
8,41
interact
S2MController
22,41
22,41
class S2MController: """ A controller for Scribble-to-Mask (for user interaction, not for DAVIS) Takes the image, previous mask, and scribbles to produce a new mask ignore_class is usually 255 0 is NOT the ignore class -- it is the label for the background """ def __init__(self, s2m_net:S2M...
class S2MController: """ A controller for Scribble-to-Mask (for user interaction, not for DAVIS) Takes the image, previous mask, and scribbles to produce a new mask ignore_class is usually 255 0 is NOT the ignore class -- it is the label for the background """ def __init__(self, s2m_net:S2M...
print(self.device) image = image.to(self.device, non_blocking=True) prev_mask = prev_mask.unsqueeze(0) h, w = image.shape[-2:] unaggre_mask = torch.zeros((self.num_objects, h, w), dtype=torch.float32, device=image.device) for ki in range(1, self.num_objects+1): ...
print(self.device) image = image.to(self.device, non_blocking=True) prev_mask = prev_mask.unsqueeze(0) h, w = image.shape[-2:] unaggre_mask = torch.zeros((self.num_objects, h, w), dtype=torch.float32, device=image.device) for ki in range(1, self.num_objects+1): ...
54
190
337
527
import torch import numpy as np from ..interact.s2m.s2m_network import deeplabv3plus_resnet50 as S2M from util.tensor_util import pad_divide_by, unpad class S2MController: """ A controller for Scribble-to-Mask (for user interaction, not for DAVIS) Takes the image, previous mask, and scribbles to produce ...
import torch import numpy as np from ..interact.s2m.s2m_network import deeplabv3plus_resnet50 as S2M from util.tensor_util import pad_divide_by, unpad class S2MController: """ A controller for Scribble-to-Mask (for user interaction, not for DAVIS) Takes the image, previous mask, and scribbles to produce ...
47,732
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/inference/interact/timer.py
19,20
3,34
count
Timer
20,27
20,27
class Timer: def __init__(self): self._acc_time = 0 self._paused = True def start(self): if self._paused: self.last_time = time.time() self._paused = False return self def pause(self): self.count() self._paused = True return s...
class Timer: def __init__(self): self._acc_time = 0 self._paused = True def start(self): if self._paused: self.last_time = time.time() self._paused = False return self def pause(self): self.count() self._paused = True return s...
if self._paused: return self._acc_time t = time.time() self._acc_time += t - self.last_time self.last_time = t return self._acc_time
if self._paused: return self._acc_time t = time.time() self._acc_time += t - self.last_time self.last_time = t return self._acc_time
17
212
64
276
import time class Timer: def __init__(self): self._acc_time = 0 self._paused = True def start(self): if self._paused: self.last_time = time.time() self._paused = False return self def pause(self): self.count() self._paused = True ...
import time class Timer: def __init__(self): self._acc_time = 0 self._paused = True def start(self): if self._paused: self.last_time = time.time() self._paused = False return self def pause(self): self.count() self._paused = True ...
47,735
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/aggregate.py
6,7
1,18
aggregate
7,18
7,18
import torch import torch.nn.functional as F # Soft aggregation from STM def aggregate(prob, dim, return_logits=False): FILL_FUNC_BODY
import torch import torch.nn.functional as F # Soft aggregation from STM def aggregate(prob, dim, return_logits=False): FILL_FUNC_BODY
new_prob = torch.cat([ torch.prod(1-prob, dim=dim, keepdim=True), prob ], dim).clamp(1e-7, 1-1e-7) logits = torch.log((new_prob /(1-new_prob))) prob = F.softmax(logits, dim=dim) if return_logits: return logits, prob else: return prob
new_prob = torch.cat([ torch.prod(1-prob, dim=dim, keepdim=True), prob ], dim).clamp(1e-7, 1-1e-7) logits = torch.log((new_prob /(1-new_prob))) prob = F.softmax(logits, dim=dim) if return_logits: return logits, prob else: return prob
26
50
126
176
import torch import torch.nn.functional as F # Soft aggregation from STM def aggregate(prob, dim, return_logits=False): FILL_FUNC_BODY
import torch import torch.nn.functional as F # Soft aggregation from STM def aggregate(prob, dim, return_logits=False): FILL_FUNC_BODY
47,736
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/group_modules.py
15,16
1,83
interpolate_groups
16,22
16,22
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
batch_size, num_objects = g.shape[:2] g = F.interpolate(g.flatten(start_dim=0, end_dim=1), scale_factor=ratio, mode=mode, align_corners=align_corners) g = g.view(batch_size, num_objects, *g.shape[1:]) return g
batch_size, num_objects = g.shape[:2] g = F.interpolate(g.flatten(start_dim=0, end_dim=1), scale_factor=ratio, mode=mode, align_corners=align_corners) g = g.view(batch_size, num_objects, *g.shape[1:]) return g
18
827
101
928
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
47,737
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/group_modules.py
30,31
29,36
forward
GConv2D
31,36
31,36
class GConv2D(nn.Conv2d): def forward(self, g): FILL_FUNC_BODY
class GConv2D(nn.Conv2d): def forward(self, g): FILL_FUNC_BODY
batch_size, num_objects = g.shape[:2] g = super().forward(g.flatten(start_dim=0, end_dim=1)) return g.view(batch_size, num_objects, *g.shape[1:])
batch_size, num_objects = g.shape[:2] g = super().forward(g.flatten(start_dim=0, end_dim=1)) return g.view(batch_size, num_objects, *g.shape[1:])
12
34
71
105
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
47,738
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/group_modules.py
48,49
36,58
forward
GroupResBlock
49,58
49,58
class GroupResBlock(nn.Module): def __init__(self, in_dim, out_dim): super().__init__() if in_dim == out_dim: self.downsample = None else: self.downsample = GConv2D(in_dim, out_dim, kernel_size=3, padding=1) self.conv1 = GConv2D(in_dim, out_dim, kernel_size=...
class GroupResBlock(nn.Module): def __init__(self, in_dim, out_dim): super().__init__() if in_dim == out_dim: self.downsample = None else: self.downsample = GConv2D(in_dim, out_dim, kernel_size=3, padding=1) self.conv1 = GConv2D(in_dim, out_dim, kernel_size=...
out_g = self.conv1(F.relu(g)) out_g = self.conv2(F.relu(out_g)) if self.downsample is not None: g = self.downsample(g) return out_g + g
out_g = self.conv1(F.relu(g)) out_g = self.conv2(F.relu(out_g)) if self.downsample is not None: g = self.downsample(g) return out_g + g
18
173
82
255
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
47,739
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/group_modules.py
66,67
58,83
forward
MainToGroupDistributor
67,83
67,83
class MainToGroupDistributor(nn.Module): def __init__(self, x_transform=None, method='cat', reverse_order=False): super().__init__() self.x_transform = x_transform self.method = method self.reverse_order = reverse_order def forward(self, x, g): FILL_FUNC_BODY
class MainToGroupDistributor(nn.Module): def __init__(self, x_transform=None, method='cat', reverse_order=False): super().__init__() self.x_transform = x_transform self.method = method self.reverse_order = reverse_order def forward(self, x, g): FILL_FUNC_BODY
num_objects = g.shape[1] if self.x_transform is not None: x = self.x_transform(x) if self.method == 'cat': if self.reverse_order: g = torch.cat([g, x.unsqueeze(1).expand(-1,num_objects,-1,-1,-1)], 2) else: g = torch.cat([x.uns...
num_objects = g.shape[1] if self.x_transform is not None: x = self.x_transform(x) if self.method == 'cat': if self.reverse_order: g = torch.cat([g, x.unsqueeze(1).expand(-1,num_objects,-1,-1,-1)], 2) else: g = torch.cat([x.uns...
42
99
209
308
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
""" Group-specific modules They handle features that also depends on the mask. Features are typically of shape batch_size * num_objects * num_channels * H * W All of them are permutation equivariant w.r.t. to the num_objects dimension """ import torch import torch.nn as nn import torch.nn.functional as F def i...
47,740
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/losses.py
8,9
1,69
dice_loss
9,23
9,23
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): FILL_FUNC_BODYclass BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm s...
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): FILL_FUNC_BODYclass BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm s...
num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we add one to cls_gt gt = (cls_gt==(i+1)).float().flatten(start_dim=1) numerator = 2 * (mask * gt).sum(-1) denominator =...
num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we add one to cls_gt gt = (cls_gt==(i+1)).float().flatten(start_dim=1) numerator = 2 * (mask * gt).sum(-1) denominator =...
55
656
230
886
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): FILL_FUNC_BODYclass BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm s...
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): FILL_FUNC_BODYclass BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm s...
47,741
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/losses.py
31,32
23,46
forward
BootstrappedCE
32,46
32,46
class BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm self.end_warm = end_warm self.top_p = top_p def forward(self, input, target, it): FILL_FUNC_BODY
class BootstrappedCE(nn.Module): def __init__(self, start_warm, end_warm, top_p=0.15): super().__init__() self.start_warm = start_warm self.end_warm = end_warm self.top_p = top_p def forward(self, input, target, it): FILL_FUNC_BODY
if it < self.start_warm: return F.cross_entropy(input, target), 1.0 raw_loss = F.cross_entropy(input, target, reduction='none').view(-1) num_pixels = raw_loss.numel() if it > self.end_warm: this_p = self.top_p else: this_p = self.top_p + (1-s...
if it < self.start_warm: return F.cross_entropy(input, target), 1.0 raw_loss = F.cross_entropy(input, target, reduction='none').view(-1) num_pixels = raw_loss.numel() if it > self.end_warm: this_p = self.top_p else: this_p = self.top_p + (1-s...
40
108
204
312
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we ...
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we ...
47,742
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/losses.py
52,53
46,69
compute
LossComputer
53,69
53,69
class LossComputer: def __init__(self, config): super().__init__() self.config = config self.bce = BootstrappedCE(config['start_warm'], config['end_warm']) def compute(self, data, num_objects, it): FILL_FUNC_BODY
class LossComputer: def __init__(self, config): super().__init__() self.config = config self.bce = BootstrappedCE(config['start_warm'], config['end_warm']) def compute(self, data, num_objects, it): FILL_FUNC_BODY
losses = defaultdict(int) b, t = data['rgb'].shape[:2] losses['total_loss'] = 0 for ti in range(1, t): for bi in range(b): loss, p = self.bce(data[f'logits_{ti}'][bi:bi+1, :num_objects[bi]+1], data['cls_gt'][bi:bi+1,ti,0], it) losses['p'] += ...
losses = defaultdict(int) b, t = data['rgb'].shape[:2] losses['total_loss'] = 0 for ti in range(1, t): for bi in range(b): loss, p = self.bce(data[f'logits_{ti}'][bi:bi+1, :num_objects[bi]+1], data['cls_gt'][bi:bi+1,ti,0], it) losses['p'] += ...
50
84
252
336
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we ...
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we ...
47,743
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/memory_util.py
7,8
1,81
get_similarity
8,41
8,41
import math import numpy as np import torch from typing import Optional def get_similarity(mk, ms, qk, qe): FILL_FUNC_BODYdef do_softmax(similarity, top_k: Optional[int]=None, inplace=False, return_usage=False): # normalize similarity with top-k softmax # similarity: B x N x [HW/P] # use inplace with care...
import math import numpy as np import torch from typing import Optional def get_similarity(mk, ms, qk, qe): FILL_FUNC_BODYdef do_softmax(similarity, top_k: Optional[int]=None, inplace=False, return_usage=False): # normalize similarity with top-k softmax # similarity: B x N x [HW/P] # use inplace with care...
# used for training/inference and memory reading/memory potentiation # mk: B x CK x [N] - Memory keys # ms: B x 1 x [N] - Memory shrinkage # qk: B x CK x [HW/P] - Query keys # qe: B x CK x [HW/P] - Query selection # Dimensions in [] are flattened CK = mk.shape[1] mk = mk.flatten(s...
# used for training/inference and memory reading/memory potentiation # mk: B x CK x [N] - Memory keys # ms: B x 1 x [N] - Memory shrinkage # qk: B x CK x [HW/P] - Query keys # qe: B x CK x [HW/P] - Query selection # Dimensions in [] are flattened CK = mk.shape[1] mk = mk.flatten(s...
179
535
505
1,040
import math import numpy as np import torch from typing import Optional def get_similarity(mk, ms, qk, qe): FILL_FUNC_BODYdef do_softmax(similarity, top_k: Optional[int]=None, inplace=False, return_usage=False): # normalize similarity with top-k softmax # similarity: B x N x [HW/P] # use inplace with care...
import math import numpy as np import torch from typing import Optional def get_similarity(mk, ms, qk, qe): FILL_FUNC_BODYdef do_softmax(similarity, top_k: Optional[int]=None, inplace=False, return_usage=False): # normalize similarity with top-k softmax # similarity: B x N x [HW/P] # use inplace with care...
47,744
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
229,230
214,251
forward
Decoder
230,251
230,251
class Decoder(nn.Module): def __init__(self, val_dim, hidden_dim): super().__init__() self.fuser = FeatureFusionBlock(1024, val_dim+hidden_dim, 512, 512) if hidden_dim > 0: self.hidden_update = HiddenUpdater([512, 256, 256+1], 256, hidden_dim) else: self.hidd...
class Decoder(nn.Module): def __init__(self, val_dim, hidden_dim): super().__init__() self.fuser = FeatureFusionBlock(1024, val_dim+hidden_dim, 512, 512) if hidden_dim > 0: self.hidden_update = HiddenUpdater([512, 256, 256+1], 256, hidden_dim) else: self.hidd...
batch_size, num_objects = memory_readout.shape[:2] if self.hidden_update is not None: g16 = self.fuser(f16, torch.cat([memory_readout, hidden_state], 2)) else: g16 = self.fuser(f16, memory_readout) g8 = self.up_16_8(f8, g16) g4 = self.up_8_4(f4, g8) ...
batch_size, num_objects = memory_readout.shape[:2] if self.hidden_update is not None: g16 = self.fuser(f16, torch.cat([memory_readout, hidden_state], 2)) else: g16 = self.fuser(f16, memory_readout) g8 = self.up_16_8(f8, g16) g4 = self.up_8_4(f4, g8) ...
71
292
352
644
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,745
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
31,32
22,44
forward
FeatureFusionBlock
32,44
32,44
class FeatureFusionBlock(nn.Module): def __init__(self, x_in_dim, g_in_dim, g_mid_dim, g_out_dim): super().__init__() self.distributor = MainToGroupDistributor() self.block1 = GroupResBlock(x_in_dim+g_in_dim, g_mid_dim) self.attention = CBAM(g_mid_dim) self.block2 = GroupRes...
class FeatureFusionBlock(nn.Module): def __init__(self, x_in_dim, g_in_dim, g_mid_dim, g_out_dim): super().__init__() self.distributor = MainToGroupDistributor() self.block1 = GroupResBlock(x_in_dim+g_in_dim, g_mid_dim) self.attention = CBAM(g_mid_dim) self.block2 = GroupRes...
batch_size, num_objects = g.shape[:2] g = self.distributor(x, g) g = self.block1(g) r = self.attention(g.flatten(start_dim=0, end_dim=1)) r = r.view(batch_size, num_objects, *r.shape[1:]) g = self.block2(g+r) return g
batch_size, num_objects = g.shape[:2] g = self.distributor(x, g) g = self.block1(g) r = self.attention(g.flatten(start_dim=0, end_dim=1)) r = r.view(batch_size, num_objects, *r.shape[1:]) g = self.block2(g+r) return g
25
157
124
281
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,746
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
86,87
77,102
forward
HiddenReinforcer
87,102
87,102
class HiddenReinforcer(nn.Module): # Used in the value encoder, a single GRU def __init__(self, g_dim, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.transform = GConv2D(g_dim+hidden_dim, hidden_dim*3, kernel_size=3, padding=1) nn.init.xavier_normal_(self.tran...
class HiddenReinforcer(nn.Module): # Used in the value encoder, a single GRU def __init__(self, g_dim, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.transform = GConv2D(g_dim+hidden_dim, hidden_dim*3, kernel_size=3, padding=1) nn.init.xavier_normal_(self.tran...
g = torch.cat([g, h], 2) # defined slightly differently than standard GRU, # namely the new value is generated before the forget gate. # might provide better gradient but frankly it was initially just an # implementation error that I never bothered fixing values = self...
g = torch.cat([g, h], 2) # defined slightly differently than standard GRU, # namely the new value is generated before the forget gate. # might provide better gradient but frankly it was initially just an # implementation error that I never bothered fixing values = self...
62
138
213
351
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,747
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
58,59
44,77
forward
HiddenUpdater
59,77
59,77
class HiddenUpdater(nn.Module): # Used in the decoder, multi-scale feature + GRU def __init__(self, g_dims, mid_dim, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.g16_conv = GConv2D(g_dims[0], mid_dim, kernel_size=1) self.g8_conv = GConv2D(g_dims[1], mid_dim,...
class HiddenUpdater(nn.Module): # Used in the decoder, multi-scale feature + GRU def __init__(self, g_dims, mid_dim, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.g16_conv = GConv2D(g_dims[0], mid_dim, kernel_size=1) self.g8_conv = GConv2D(g_dims[1], mid_dim,...
g = self.g16_conv(g[0]) + self.g8_conv(downsample_groups(g[1], ratio=1/2)) + \ self.g4_conv(downsample_groups(g[2], ratio=1/4)) g = torch.cat([g, h], 2) # defined slightly differently than standard GRU, # namely the new value is generated before the forget gate. # ...
g = self.g16_conv(g[0]) + self.g8_conv(downsample_groups(g[1], ratio=1/2)) + \ self.g4_conv(downsample_groups(g[2], ratio=1/4)) g = torch.cat([g, h], 2) # defined slightly differently than standard GRU, # namely the new value is generated before the forget gate. # ...
72
244
282
526
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,748
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
166,167
153,178
forward
KeyEncoder
167,178
167,178
class KeyEncoder(nn.Module): def __init__(self): super().__init__() network = resnet.resnet50(pretrained=True) self.conv1 = network.conv1 self.bn1 = network.bn1 self.relu = network.relu # 1/2, 64 self.maxpool = network.maxpool self.res2 = network.layer1 # 1/...
class KeyEncoder(nn.Module): def __init__(self): super().__init__() network = resnet.resnet50(pretrained=True) self.conv1 = network.conv1 self.bn1 = network.bn1 self.relu = network.relu # 1/2, 64 self.maxpool = network.maxpool self.res2 = network.layer1 # 1/...
x = self.conv1(f) x = self.bn1(x) x = self.relu(x) # 1/2, 64 x = self.maxpool(x) # 1/4, 64 f4 = self.res2(x) # 1/4, 256 f8 = self.layer2(f4) # 1/8, 512 f16 = self.layer3(f8) # 1/16, 1024 return f16, f8, f4
x = self.conv1(f) x = self.bn1(x) x = self.relu(x) # 1/2, 64 x = self.maxpool(x) # 1/4, 64 f4 = self.res2(x) # 1/4, 256 f8 = self.layer2(f4) # 1/8, 512 f16 = self.layer3(f8) # 1/16, 1024 return f16, f8, f4
40
183
163
346
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,749
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
207,208
194,214
forward
KeyProjection
208,214
208,214
class KeyProjection(nn.Module): def __init__(self, in_dim, keydim): super().__init__() self.key_proj = nn.Conv2d(in_dim, keydim, kernel_size=3, padding=1) # shrinkage self.d_proj = nn.Conv2d(in_dim, 1, kernel_size=3, padding=1) # selection self.e_proj = nn.Conv2d(in_...
class KeyProjection(nn.Module): def __init__(self, in_dim, keydim): super().__init__() self.key_proj = nn.Conv2d(in_dim, keydim, kernel_size=3, padding=1) # shrinkage self.d_proj = nn.Conv2d(in_dim, 1, kernel_size=3, padding=1) # selection self.e_proj = nn.Conv2d(in_...
shrinkage = self.d_proj(x)**2 + 1 if (need_s) else None selection = torch.sigmoid(self.e_proj(x)) if (need_e) else None return self.key_proj(x), shrinkage, selection
shrinkage = self.d_proj(x)**2 + 1 if (need_s) else None selection = torch.sigmoid(self.e_proj(x)) if (need_e) else None return self.key_proj(x), shrinkage, selection
20
213
76
289
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,750
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
186,187
178,194
forward
UpsampleBlock
187,194
187,194
class UpsampleBlock(nn.Module): def __init__(self, skip_dim, g_up_dim, g_out_dim, scale_factor=2): super().__init__() self.skip_conv = nn.Conv2d(skip_dim, g_up_dim, kernel_size=3, padding=1) self.distributor = MainToGroupDistributor(method='add') self.out_conv = GroupResBlock(g_up_di...
class UpsampleBlock(nn.Module): def __init__(self, skip_dim, g_up_dim, g_out_dim, scale_factor=2): super().__init__() self.skip_conv = nn.Conv2d(skip_dim, g_up_dim, kernel_size=3, padding=1) self.distributor = MainToGroupDistributor(method='add') self.out_conv = GroupResBlock(g_up_di...
skip_f = self.skip_conv(skip_f) g = upsample_groups(up_g, ratio=self.scale_factor) g = self.distributor(skip_f, g) g = self.out_conv(g) return g
skip_f = self.skip_conv(skip_f) g = upsample_groups(up_g, ratio=self.scale_factor) g = self.distributor(skip_f, g) g = self.out_conv(g) return g
16
166
78
244
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,751
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/modules.py
124,125
102,153
forward
ValueEncoder
125,153
125,153
class ValueEncoder(nn.Module): def __init__(self, value_dim, hidden_dim, single_object=False): super().__init__() self.single_object = single_object network = resnet.resnet18(pretrained=True, extra_dim=1 if single_object else 2) self.conv1 = network.conv1 self.bn1 = ...
class ValueEncoder(nn.Module): def __init__(self, value_dim, hidden_dim, single_object=False): super().__init__() self.single_object = single_object network = resnet.resnet18(pretrained=True, extra_dim=1 if single_object else 2) self.conv1 = network.conv1 self.bn1 = ...
# image_feat_f16 is the feature from the key encoder if not self.single_object: g = torch.stack([masks, others], 2) else: g = masks.unsqueeze(2) g = self.distributor(image, g) batch_size, num_objects = g.shape[:2] g = g.flatten(start_dim=0, end_di...
# image_feat_f16 is the feature from the key encoder if not self.single_object: g = torch.stack([masks, others], 2) else: g = masks.unsqueeze(2) g = self.distributor(image, g) batch_size, num_objects = g.shape[:2] g = g.flatten(start_dim=0, end_di...
89
340
350
690
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
""" modules.py - This file stores the rather boring network blocks. x - usually means features that only depends on the image g - usually means features that also depends on the mask. They might have an extra "group" or "num_objects" dimension, hence batch_size * num_objects * num_channels * H * W The traili...
47,752
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/resnet.py
14,15
1,166
load_weights_add_extra_dim
15,35
15,35
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): FILL_FUNC_BODYmod...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): FILL_FUNC_BODYmod...
new_dict = OrderedDict() for k1, v1 in target.state_dict().items(): if not 'num_batches_tracked' in k1: if k1 in source_state: tar_v = source_state[k1] if v1.shape != tar_v.shape: # Init the new segmentation channel with zeros ...
new_dict = OrderedDict() for k1, v1 in target.state_dict().items(): if not 'num_batches_tracked' in k1: if k1 in source_state: tar_v = source_state[k1] if v1.shape != tar_v.shape: # Init the new segmentation channel with zeros ...
55
1,800
237
2,037
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): FILL_FUNC_BODYmod...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): FILL_FUNC_BODYmod...
47,753
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/resnet.py
59,60
46,78
forward
BasicBlock
60,78
60,78
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.Re...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.Re...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return o...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return o...
34
208
127
335
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
47,754
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/resnet.py
94,95
78,117
forward
Bottleneck
95,117
95,117
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = se...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = se...
43
290
165
455
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
47,755
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/model/resnet.py
138,139
117,154
_make_layer
ResNet
139,154
139,154
class ResNet(nn.Module): def __init__(self, block, layers=(3, 4, 23, 3), extra_dim=0): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3+extra_dim, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(i...
class ResNet(nn.Module): def __init__(self, block, layers=(3, 4, 23, 3), extra_dim=0): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3+extra_dim, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(i...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.exp...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.exp...
48
436
201
637
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
47,758
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/util/load_subset.py
13,14
1,17
load_sub_yv
14,17
14,17
""" load_subset.py - Presents a subset of data DAVIS - only the training set YouTubeVOS - I manually filtered some erroneous ones out but I haven't checked all """ def load_sub_davis(path='util/davis_subset.txt'): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def l...
""" load_subset.py - Presents a subset of data DAVIS - only the training set YouTubeVOS - I manually filtered some erroneous ones out but I haven't checked all """ def load_sub_davis(path='util/davis_subset.txt'): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def l...
with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset
with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset
10
139
35
174
""" load_subset.py - Presents a subset of data DAVIS - only the training set YouTubeVOS - I manually filtered some erroneous ones out but I haven't checked all """ def load_sub_davis(path='util/davis_subset.txt'): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def l...
""" load_subset.py - Presents a subset of data DAVIS - only the training set YouTubeVOS - I manually filtered some erroneous ones out but I haven't checked all """ def load_sub_davis(path='util/davis_subset.txt'): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def l...
47,759
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/util/log_integrator.py
56,57
10,81
finalize
Integrator
57,81
57,81
class Integrator: def __init__(self, logger, distributed=True, local_rank=0, world_size=1): self.values = {} self.counts = {} self.hooks = [] # List is used here to maintain insertion order self.logger = logger self.distributed = distributed self.local_rank = local...
class Integrator: def __init__(self, logger, distributed=True, local_rank=0, world_size=1): self.values = {} self.counts = {} self.hooks = [] # List is used here to maintain insertion order self.logger = logger self.distributed = distributed self.local_rank = local...
for hook in self.hooks: k, v = hook(self.values) self.add_tensor(k, v) for k, v in self.values.items(): if k[:4] == 'hide': continue avg = v / self.counts[k] if self.distributed: # Inplace operation ...
for hook in self.hooks: k, v = hook(self.values) self.add_tensor(k, v) for k, v in self.values.items(): if k[:4] == 'hide': continue avg = v / self.counts[k] if self.distributed: # Inplace operation ...
57
452
239
691
""" Integrate numerical values for some iterations Typically used for loss computation / logging to tensorboard Call finalize and create a new Integrator when you want to display/log """ import torch class Integrator: def __init__(self, logger, distributed=True, local_rank=0, world_size=1): self.values =...
""" Integrate numerical values for some iterations Typically used for loss computation / logging to tensorboard Call finalize and create a new Integrator when you want to display/log """ import torch class Integrator: def __init__(self, logger, distributed=True, local_rank=0, world_size=1): self.values =...
47,760
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/util/logger.py
16,17
1,102
detach_to_cpu
17,19
17,19
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): FILL_FUNC_BODYdef fix_wi...
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): FILL_FUNC_BODYdef fix_wi...
return x.detach().cpu()
return x.detach().cpu()
2
1,067
13
1,080
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): FILL_FUNC_BODYdef fix_wi...
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): FILL_FUNC_BODYdef fix_wi...
47,761
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/util/logger.py
78,79
22,102
log_seg
TensorboardLogger
79,87
79,87
class TensorboardLogger: def __init__(self, short_id, id, git_info): self.short_id = short_id if self.short_id == 'NULL': self.short_id = 'DEBUG' if id is None: self.no_log = True warnings.warn('Logging has been disbaled.') else: self....
class TensorboardLogger: def __init__(self, short_id, id, git_info): self.short_id = short_id if self.short_id == 'NULL': self.short_id = 'DEBUG' if id is None: self.no_log = True warnings.warn('Logging has been disbaled.') else: self....
if self.no_log: warnings.warn('Logging has been disabled.') return x = detach_to_cpu(x) x = self.inv_seg_trans(x) x = tensor_to_numpy(x) self.logger.add_image(tag, x, step)
if self.no_log: warnings.warn('Logging has been disabled.') return x = detach_to_cpu(x) x = self.inv_seg_trans(x) x = tensor_to_numpy(x) self.logger.add_image(tag, x, step)
19
847
91
938
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): return x.detach().cp...
""" Dumps things to tensorboard and console """ import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): return x.detach().cp...
47,762
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem
/home/hieuvd/dung_repo/raw/stars_03/hkchengrex_XMem/XMem/util/tensor_util.py
34,35
1,48
unpad
35,48
35,48
import torch.nn.functional as F def compute_tensor_iu(seg, gt): intersection = (seg & gt).float().sum() union = (seg | gt).float().sum() return intersection, union def compute_tensor_iou(seg, gt): intersection, union = compute_tensor_iu(seg, gt) iou = (intersection + 1e-6) / (union + 1e-6) ...
import torch.nn.functional as F def compute_tensor_iu(seg, gt): intersection = (seg & gt).float().sum() union = (seg | gt).float().sum() return intersection, union def compute_tensor_iou(seg, gt): intersection, union = compute_tensor_iu(seg, gt) iou = (intersection + 1e-6) / (union + 1e-6) ...
if len(img.shape) == 4: if pad[2]+pad[3] > 0: img = img[:,:,pad[2]:-pad[3],:] if pad[0]+pad[1] > 0: img = img[:,:,:,pad[0]:-pad[1]] elif len(img.shape) == 3: if pad[2]+pad[3] > 0: img = img[:,pad[2]:-pad[3],:] if pad[0]+pad[1] > 0: ...
if len(img.shape) == 4: if pad[2]+pad[3] > 0: img = img[:,:,pad[2]:-pad[3],:] if pad[0]+pad[1] > 0: img = img[:,:,:,pad[0]:-pad[1]] elif len(img.shape) == 3: if pad[2]+pad[3] > 0: img = img[:,pad[2]:-pad[3],:] if pad[0]+pad[1] > 0: ...
41
377
186
563
import torch.nn.functional as F def compute_tensor_iu(seg, gt): intersection = (seg & gt).float().sum() union = (seg | gt).float().sum() return intersection, union def compute_tensor_iou(seg, gt): intersection, union = compute_tensor_iu(seg, gt) iou = (intersection + 1e-6) / (union + 1e-6) ...
import torch.nn.functional as F def compute_tensor_iu(seg, gt): intersection = (seg & gt).float().sum() union = (seg | gt).float().sum() return intersection, union def compute_tensor_iou(seg, gt): intersection, union = compute_tensor_iu(seg, gt) iou = (intersection + 1e-6) / (union + 1e-6) ...
47,763
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/cli/benchmark.py
83,91
1,117
list_benchmarks
92,115
91,115
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from smarts.benchmark import BENCHMARK_LISTING_FILE from smarts.benchmark import list_benchmarks as _list_benchmarks benchmarks = _list_benchmarks( Path(benchmark_listing) if benchmark_listing is not None else BENCHMARK_LISTING_FILE, )["benchmarks"] print("BENCHMARK_NAME".l...
"""Lists available benchmarks that can be used for `scl benchmark run`.""" from smarts.benchmark import BENCHMARK_LISTING_FILE from smarts.benchmark import list_benchmarks as _list_benchmarks benchmarks = _list_benchmarks( Path(benchmark_listing) if benchmark_listing is not None ...
49
998
259
1,257
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,764
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/cli/diagnostic.py
32,35
1,41
run
35,40
35,40
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from smarts.diagnostic import run as _run _run.main(scenarios)
from smarts.diagnostic import run as _run _run.main(scenarios)
7
476
33
509
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,765
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/cli/envision.py
31,44
1,50
start_server
44,49
44,49
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from envision.server import run run(max_capacity_mb=max_capacity, port=port)
from envision.server import run run(max_capacity_mb=max_capacity, port=port)
6
581
37
618
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,766
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/cli/studio.py
91,96
1,116
replay
96,112
96,112
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from envision.client import Client as Envision for path in directory: jsonl_paths = list(Path(path).glob("*.jsonl")) click.echo( f"Replaying {len(jsonl_paths)} record(s) at path={path} with " f"timestep={timestep}s" ) with ThreadPool(len(jsonl_paths)) as...
from envision.client import Client as Envision for path in directory: jsonl_paths = list(Path(path).glob("*.jsonl")) click.echo( f"Replaying {len(jsonl_paths)} record(s) at path={path} with " f"timestep={timestep}s" ) with ThreadPool(len(jsonl_paths)) as...
37
1,168
169
1,337
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,767
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/cli/waymo.py
34,41
1,115
overview
41,57
41,57
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from smarts.waymo import waymo_utils scenarios = waymo_utils.get_tfrecord_info(tfrecord_file) rows = [ [k, v["timestamps"], v["vehicles"], v["pedestrians"]] for k, v in scenarios.items() ] headers = [ "Scenario ID", "Timestamps", "Vehicles", "Pedestri...
from smarts.waymo import waymo_utils scenarios = waymo_utils.get_tfrecord_info(tfrecord_file) rows = [ [k, v["timestamps"], v["vehicles"], v["pedestrians"]] for k, v in scenarios.items() ] headers = [ "Scenario ID", "Timestamps", "Vehicles", "Pedestri...
31
1,134
147
1,281
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,768
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/client_config.py
39,40
1,57
_default_override
40,43
40,43
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
return SingleAttributeOverride(True, None)
return SingleAttributeOverride(True, None)
3
599
16
615
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,769
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/client_config.py
52,54
43,57
default
EnvisionStateFilter
55,57
54,57
@dataclass(frozen=True) class EnvisionStateFilter: """A state filtering tool.""" actor_data_filter: Dict[str, SingleAttributeOverride] """Actor filtering.""" simulation_data_filter: Dict[str, SingleAttributeOverride] """Simulation filtering.""" @classmethod def default(cls): FILL_FUNC_BODY
@dataclass(frozen=True) class EnvisionStateFilter: """A state filtering tool.""" actor_data_filter: Dict[str, SingleAttributeOverride] """Actor filtering.""" simulation_data_filter: Dict[str, SingleAttributeOverride] """Simulation filtering.""" @classmethod def default(cls): """Giv...
return cls(defaultdict(_default_override), defaultdict(_default_override))
"""Give a new default filter.""" return cls(defaultdict(_default_override), defaultdict(_default_override))
3
108
25
133
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,771
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/data_formatter.py
220,221
206,259
empty_gen
DataFormatterLayer
221,224
221,224
class DataFormatterLayer(ContextManager, Iterator): """A formatting layer that maps into the above layer of the current data formatter.""" def __init__( self, data_formatter: "EnvisionDataFormatter", iterable: Optional[Iterable], op: Operation, ...
class DataFormatterLayer(ContextManager, Iterator): """A formatting layer that maps into the above layer of the current data formatter.""" def __init__( self, data_formatter: "EnvisionDataFormatter", iterable: Optional[Iterable], op: Operation, ...
return yield
return yield
2
478
10
488
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,772
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/data_formatter.py
185,190
139,273
add
EnvisionDataFormatter
191,206
190,206
class EnvisionDataFormatter: """A formatter to put envision state into a reduced format.""" def __init__( self, formatter_params: EnvisionDataFormatterArgs, ): # self.seen_objects = context.seen_objects if context else set() self.id: Any = id self._data: List[Any] = ...
class EnvisionDataFormatter: """A formatter to put envision state into a reduced format.""" def __init__( self, formatter_params: EnvisionDataFormatterArgs, ): # self.seen_objects = context.seen_objects if context else set() self.id: Any = id self._data: List[Any] = ...
outval = value f = _sequence_formatter_map.get(type(value)) if op & Operation.REDUCE: outval = self._reduction_context.resolve_value(outval) if op & Operation.FLATTEN: outval = unpack(outval) if not isinstance(outval, (Sequence, np.ndarray)): ...
"""Format the given object to the current layer. Specified operations are performed.""" outval = value f = _sequence_formatter_map.get(type(value)) if op & Operation.REDUCE: outval = self._reduction_context.resolve_value(outval) if op & Operation.FLATTEN: ...
45
1,162
177
1,339
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,773
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/data_formatter.py
107,109
82,129
has_ids
ReductionContext
110,112
109,112
class ReductionContext: """Mappings between an object and its reduction to an ID.""" def __init__( self, mapping: Optional[Dict[Hashable, int]] = None, removed: Optional[List[int]] = None, enabled: bool = True, ) -> None: self._current_id = 0 self._mapping = ...
class ReductionContext: """Mappings between an object and its reduction to an ID.""" def __init__( self, mapping: Optional[Dict[Hashable, int]] = None, removed: Optional[List[int]] = None, enabled: bool = True, ) -> None: self._current_id = 0 self._mapping = ...
return len(self._mapping) > 0
"""If this reducing tool has currently reduced objects.""" return len(self._mapping) > 0
4
386
14
400
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,774
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/etypes.py
105,106
1,118
format_actor_id
115,118
106,118
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
if is_multi: return f"{actor_id}-{{{vehicle_id[:4]}}}" return actor_id
"""A conversion utility to ensure that an actor id conforms to envision's actor id standard. Args: actor_id: The base id of the actor. vehicle_id: The vehicle id of the vehicle the actor associates with. is_multi: If an actor associates with multiple vehicles. Returns: An en...
6
1,165
38
1,203
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,775
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/utils/multiprocessing_queue.py
89,90
57,93
clear
Queue
91,93
90,93
class Queue(multiprocessing.queues.Queue): """A portable implementation of multiprocessing.Queue. Because of multithreading / multiprocessing semantics, Queue.qsize() may raise the NotImplementedError exception on Unix platforms like Mac OS X where sem_getvalue() is not implemented. This subclass addres...
class Queue(multiprocessing.queues.Queue): """A portable implementation of multiprocessing.Queue. Because of multithreading / multiprocessing semantics, Queue.qsize() may raise the NotImplementedError exception on Unix platforms like Mac OS X where sem_getvalue() is not implemented. This subclass addres...
while not self.empty(): self.get()
"""Remove all elements from the Queue.""" while not self.empty(): self.get()
4
387
16
403
## MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
## MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
47,776
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/envision/utils/multiprocessing_queue.py
46,47
31,57
increment
SharedCounter
48,51
47,51
class SharedCounter(object): """A synchronized shared counter. The locking done by multiprocessing.Value ensures that only a single process or thread may read or write the in-memory ctypes object. However, in order to do n += 1, Python performs a read followed by a write, so a second process may rea...
class SharedCounter(object): """A synchronized shared counter. The locking done by multiprocessing.Value ensures that only a single process or thread may read or write the in-memory ctypes object. However, in order to do n += 1, Python performs a read followed by a write, so a second process may rea...
with self.count.get_lock(): self.count.value += n
"""Increment the counter by n (default = 1)""" with self.count.get_lock(): self.count.value += n
5
279
24
303
## MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
## MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
47,777
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/e12_rllib/configs.py
6,7
1,70
gen_parser
7,70
7,70
import argparse import multiprocessing from pathlib import Path def gen_parser(prog: str, default_result_dir: str) -> argparse.ArgumentParser: FILL_FUNC_BODY
import argparse import multiprocessing from pathlib import Path def gen_parser(prog: str, default_result_dir: str) -> argparse.ArgumentParser: FILL_FUNC_BODY
parser = argparse.ArgumentParser(prog) parser.add_argument( "scenarios", help="A list of scenarios. Each element can be either the scenario to" "run or a directory of scenarios to sample from. See `scenarios/`" "folder for some samples you can use.", type=str, nar...
parser = argparse.ArgumentParser(prog) parser.add_argument( "scenarios", help="A list of scenarios. Each element can be either the scenario to" "run or a directory of scenarios to sample from. See `scenarios/`" "folder for some samples you can use.", type=str, nar...
189
55
681
736
import argparse import multiprocessing from pathlib import Path def gen_parser(prog: str, default_result_dir: str) -> argparse.ArgumentParser: FILL_FUNC_BODY
import argparse import multiprocessing from pathlib import Path def gen_parser(prog: str, default_result_dir: str) -> argparse.ArgumentParser: FILL_FUNC_BODY
47,778
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/e5_agent_zoo.py
33,34
1,77
main
34,72
34,72
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
name = "random_lane_control-v0" print(f"=== Before registering `{name}` ===") print(registry.agent_registry) registry.register( name, rla_entrypoint ) # This registers "__main__:random_lane_control-v0" print(f"=== After registering `{name}` ===") print(registry.agent_registry) ...
name = "random_lane_control-v0" print(f"=== Before registering `{name}` ===") print(registry.agent_registry) registry.register( name, rla_entrypoint ) # This registers "__main__:random_lane_control-v0" print(f"=== After registering `{name}` ===") print(registry.agent_registry) ...
144
350
545
895
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
47,779
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/e5_agent_zoo.py
20,21
19,24
act
RandomLaneAgent
21,24
21,24
class RandomLaneAgent(Agent): def act(self, obs, **kwargs): FILL_FUNC_BODY
class RandomLaneAgent(Agent): def act(self, obs, **kwargs): FILL_FUNC_BODY
return random.randint(0, 3)
return random.randint(0, 3)
3
31
18
49
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
"""This is an example to show how SMARTS multi-agent works. This example uses the same kind of agent multiple times but different agents with different action and observation shapes can be mixed in.""" import random import sys from pathlib import Path # This may be necessary to get the repository root into path SMARTS...
47,780
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/e6_agent_action_space.py
32,33
1,52
display_agent_type_spaces
33,43
33,43
"""This is an example to show how agent interface action formatting configuration works.""" from pathlib import Path from examples.tools.argument_parser import empty_parser from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.controllers import Controllers from smarts.core.controllers.act...
"""This is an example to show how agent interface action formatting configuration works.""" from pathlib import Path from examples.tools.argument_parser import empty_parser from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.controllers import Controllers from smarts.core.controllers.act...
method_name, _, _ = f"{AgentInterface.from_type=}".partition("=") print( f"Note that `{method_name}` generates a pre-configured agent type with an existing action space." ) for name, agent_type in AgentType.__members__.items(): agent_type: AgentType print(f"{name.ljust(30)}: {Ag...
method_name, _, _ = f"{AgentInterface.from_type=}".partition("=") print( f"Note that `{method_name}` generates a pre-configured agent type with an existing action space." ) for name, agent_type in AgentType.__members__.items(): agent_type: AgentType print(f"{name.ljust(30)}: {Ag...
29
442
128
570
"""This is an example to show how agent interface action formatting configuration works.""" from pathlib import Path from examples.tools.argument_parser import empty_parser from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.controllers import Controllers from smarts.core.controllers.act...
"""This is an example to show how agent interface action formatting configuration works.""" from pathlib import Path from examples.tools.argument_parser import empty_parser from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.controllers import Controllers from smarts.core.controllers.act...
47,781
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/argument_parser.py
60,61
1,79
default_argument_parser
67,79
61,79
import argparse from typing import Optional def empty_parser(program: Optional[str] = None): """This factory method returns an empty `argparse.ArgumentParser` with primitive configuration. You can extend it with more `parser.add_argument(...)` calls or obtain the arguments via `parser.parse_args()`. ...
import argparse from typing import Optional def empty_parser(program: Optional[str] = None): """This factory method returns an empty `argparse.ArgumentParser` with primitive configuration. You can extend it with more `parser.add_argument(...)` calls or obtain the arguments via `parser.parse_args()`. ...
parser = minimal_argument_parser(program=program) parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--sim_name", help="Simulation name.", type=str, default=None, ) parser.add_argument( "--sumo_port", help="Run SUMO with a specified port...
"""This factory method returns a vanilla `argparse.ArgumentParser` with a slightly broader subset of arguments that should be supported. You can extend it with more `parser.add_argument(...)` calls or obtain the arguments via `parser.parse_args()`. """ parser = minimal_argument_parser(program=...
26
571
128
699
import argparse from typing import Optional def empty_parser(program: Optional[str] = None): """This factory method returns an empty `argparse.ArgumentParser` with primitive configuration. You can extend it with more `parser.add_argument(...)` calls or obtain the arguments via `parser.parse_args()`. ...
import argparse from typing import Optional def empty_parser(program: Optional[str] = None): """This factory method returns an empty `argparse.ArgumentParser` with primitive configuration. You can extend it with more `parser.add_argument(...)` calls or obtain the arguments via `parser.parse_args()`. ...
47,782
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/primitive_agents.py
25,26
1,109
open_entrypoint
26,35
26,35
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
try: open_agent = importlib.import_module("open_agent") except ModuleNotFoundError as e: raise ModuleNotFoundError( f"Ensure that the open-agent has been installed with `pip install open-agent" ) return open_agent.entrypoint(debug=debug, aggressiveness=aggressiveness)
try: open_agent = importlib.import_module("open_agent") except ModuleNotFoundError as e: raise ModuleNotFoundError( f"Ensure that the open-agent has been installed with `pip install open-agent" ) return open_agent.entrypoint(debug=debug, aggressiveness=aggressiveness)
25
989
94
1,083
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
47,783
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/primitive_agents.py
36,37
35,53
act
ChaseViaPointsAgent
37,53
37,53
class ChaseViaPointsAgent(Agent): def act(self, obs: Observation): FILL_FUNC_BODY
class ChaseViaPointsAgent(Agent): def act(self, obs: Observation): FILL_FUNC_BODY
if ( len(obs.via_data.near_via_points) < 1 or obs.ego_vehicle_state.road_id != obs.via_data.near_via_points[0].road_id ): return (obs.waypoint_paths[0][0].speed_limit, 0) nearest = obs.via_data.near_via_points[0] if nearest.lane_index == obs.ego_vehic...
if ( len(obs.via_data.near_via_points) < 1 or obs.ego_vehicle_state.road_id != obs.via_data.near_via_points[0].road_id ): return (obs.waypoint_paths[0][0].speed_limit, 0) nearest = obs.via_data.near_via_points[0] if nearest.lane_index == obs.ego_vehic...
34
34
207
241
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
47,784
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/primitive_agents.py
11,12
10,16
act
KeepLaneAgent
12,16
12,16
class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODY
val = ["keep_lane", "slow_down", "change_lane_left", "change_lane_right"] return random.choice(val)
val = ["keep_lane", "slow_down", "change_lane_left", "change_lane_right"] return random.choice(val)
8
28
46
74
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODYdef kla_entrypoint(*, max_episode_ste...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODYdef kla_entrypoint(*, max_episode_ste...
47,785
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/primitive_agents.py
98,99
97,102
act
StandardLaneFollowerAgent
99,102
99,102
class StandardLaneFollowerAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class StandardLaneFollowerAgent(Agent): def act(self, obs): FILL_FUNC_BODY
return (obs["waypoint_paths"]["speed_limit"][0][0], 0)
return (obs["waypoint_paths"]["speed_limit"][0][0], 0)
3
30
29
59
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
47,786
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/primitive_agents.py
65,66
64,88
act
TrackingAgent
66,88
66,88
class TrackingAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class TrackingAgent(Agent): def act(self, obs): FILL_FUNC_BODY
lane_index = 0 num_trajectory_points = min([10, len(obs.waypoint_paths[lane_index])]) # Desired speed is in m/s desired_speed = 50 / 3.6 trajectory = [ [ obs.waypoint_paths[lane_index][i].pos[0] for i in range(num_trajectory_points) ...
lane_index = 0 num_trajectory_points = min([10, len(obs.waypoint_paths[lane_index])]) # Desired speed is in m/s desired_speed = 50 / 3.6 trajectory = [ [ obs.waypoint_paths[lane_index][i].pos[0] for i in range(num_trajectory_points) ...
50
27
238
265
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
import importlib import random from typing import Optional from smarts.core.agent_interface import AgentInterface, AgentType from smarts.core.observations import Observation from smarts.zoo import Agent, AgentSpec class KeepLaneAgent(Agent): def act(self, obs): val = ["keep_lane", "slow_down", "change_la...
47,787
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/stress_sumo.py
12,14
1,32
spawn_sumo
14,24
14,24
try: import ray except Exception as e: from smarts.core.utils.custom_exceptions import RayException raise RayException.required_to("stress_sumo.py") from smarts.core.scenario import Scenario from smarts.core.sumo_traffic_simulation import SumoTrafficSimulation @ray.remote def spawn_sumo(worker_idx, batc...
try: import ray except Exception as e: from smarts.core.utils.custom_exceptions import RayException raise RayException.required_to("stress_sumo.py") from smarts.core.scenario import Scenario from smarts.core.sumo_traffic_simulation import SumoTrafficSimulation @ray.remote def spawn_sumo(worker_idx, batc...
sumo_sim = SumoTrafficSimulation(headless=True) scenarios_iterator = Scenario.scenario_variations( ["scenarios/sumo/loop"], ["Agent007"], ) sumo_sim.setup(Scenario.next(scenarios_iterator, f"{batch_id}-{worker_idx}")) sumo_sim.teardown()
sumo_sim = SumoTrafficSimulation(headless=True) scenarios_iterator = Scenario.scenario_variations( ["scenarios/sumo/loop"], ["Agent007"], ) sumo_sim.setup(Scenario.next(scenarios_iterator, f"{batch_id}-{worker_idx}")) sumo_sim.teardown()
12
202
117
319
try: import ray except Exception as e: from smarts.core.utils.custom_exceptions import RayException raise RayException.required_to("stress_sumo.py") from smarts.core.scenario import Scenario from smarts.core.sumo_traffic_simulation import SumoTrafficSimulation @ray.remote def spawn_sumo(worker_idx, batc...
try: import ray except Exception as e: from smarts.core.utils.custom_exceptions import RayException raise RayException.required_to("stress_sumo.py") from smarts.core.scenario import Scenario from smarts.core.sumo_traffic_simulation import SumoTrafficSimulation @ray.remote def spawn_sumo(worker_idx, batc...
47,788
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/examples/tools/sumo_multi_clients.py
75,76
1,92
main
76,90
76,90
import os import subprocess import threading import time from smarts.core.utils.sumo_utils import SUMO_PATH, sumolib, traci PORT = 8001 """ Conclusions: 1. connected clients < num-clients: SUMO will block, only start once all clients have connected. 2. connected clients > num-clients: Extra connection will be closed...
import os import subprocess import threading import time from smarts.core.utils.sumo_utils import SUMO_PATH, sumolib, traci PORT = 8001 """ Conclusions: 1. connected clients < num-clients: SUMO will block, only start once all clients have connected. 2. connected clients > num-clients: Extra connection will be closed...
t1 = threading.Thread(target=init_client, args=()) t1.start() t2 = threading.Thread(target=run_client_2, args=()) t2.start() t3 = threading.Thread(target=run_client_3, args=()) t3.start() t1.join() t2.join() t3.join()
t1 = threading.Thread(target=init_client, args=()) t1.start() t2 = threading.Thread(target=run_client_2, args=()) t2.start() t3 = threading.Thread(target=run_client_3, args=()) t3.start() t1.join() t2.join() t3.join()
18
662
122
784
import os import subprocess import threading import time from smarts.core.utils.sumo_utils import SUMO_PATH, sumolib, traci PORT = 8001 """ Conclusions: 1. connected clients < num-clients: SUMO will block, only start once all clients have connected. 2. connected clients > num-clients: Extra connection will be closed...
import os import subprocess import threading import time from smarts.core.utils.sumo_utils import SUMO_PATH, sumolib, traci PORT = 8001 """ Conclusions: 1. connected clients < num-clients: SUMO will block, only start once all clients have connected. 2. connected clients > num-clients: Extra connection will be closed...
47,789
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/scenarios/sumo/intersections/2lane_circle/agent_prefabs.py
9,10
8,13
act
KeepLaneAgent
10,13
10,13
class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODY
return "keep_lane"
return "keep_lane"
2
28
14
42
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, DoneCriteria from smarts.core.controllers import ActionSpaceType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODYclass Stop...
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, DoneCriteria from smarts.core.controllers import ActionSpaceType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class KeepLaneAgent(Agent): def act(self, obs): FILL_FUNC_BODYclass Stop...
47,790
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/scenarios/sumo/intersections/2lane_circle/agent_prefabs.py
14,15
13,18
act
StoppedAgent
15,18
15,18
class StoppedAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class StoppedAgent(Agent): def act(self, obs): FILL_FUNC_BODY
return (0, 0)
return (0, 0)
3
27
14
41
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, DoneCriteria from smarts.core.controllers import ActionSpaceType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class KeepLaneAgent(Agent): def act(self, obs): return "keep_lan...
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, DoneCriteria from smarts.core.controllers import ActionSpaceType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class KeepLaneAgent(Agent): def act(self, obs): return "keep_lan...
47,791
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/scenarios/sumo/intersections/6lane/scenario.py
11,12
1,59
actor_gen
12,22
12,22
import os from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio.sstypes import Mission, Route, Scenario, SocialAgentActor, Traffic from smarts.sstudio.sstypes.entry_tactic import IdEntryTactic from smarts.sstudio.sstypes.route import RandomRoute from smarts.sstudio.sstypes.traffic import...
import os from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio.sstypes import Mission, Route, Scenario, SocialAgentActor, Traffic from smarts.sstudio.sstypes.entry_tactic import IdEntryTactic from smarts.sstudio.sstypes.route import RandomRoute from smarts.sstudio.sstypes.traffic import...
return [ SocialAgentActor( name=f"{id_}-non-interactive-agent-{speed}-v0", agent_locator="zoo.policies:non-interactive-agent-v0", policy_kwargs={"speed": speed}, ) for speed in [10, 30, 80] ]
return [ SocialAgentActor( name=f"{id_}-non-interactive-agent-{speed}-v0", agent_locator="zoo.policies:non-interactive-agent-v0", policy_kwargs={"speed": speed}, ) for speed in [10, 30, 80] ]
15
541
105
646
import os from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio.sstypes import Mission, Route, Scenario, SocialAgentActor, Traffic from smarts.sstudio.sstypes.entry_tactic import IdEntryTactic from smarts.sstudio.sstypes.route import RandomRoute from smarts.sstudio.sstypes.traffic import...
import os from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio.sstypes import Mission, Route, Scenario, SocialAgentActor, Traffic from smarts.sstudio.sstypes.entry_tactic import IdEntryTactic from smarts.sstudio.sstypes.route import RandomRoute from smarts.sstudio.sstypes.traffic import...
47,792
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/scenarios/sumo/zoo_intersection/agent_prefabs.py
13,14
1,33
demo_agent_callable
14,19
14,19
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): return "keep_lane" # You can register a callable that will build your A...
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): return "keep_lane" # You can register a callable that will build your A...
if interface is None: interface = AgentInterface.from_type(AgentType.Laner) return AgentSpec(interface=interface, agent_builder=SimpleAgent)
if interface is None: interface = AgentInterface.from_type(AgentType.Laner) return AgentSpec(interface=interface, agent_builder=SimpleAgent)
10
290
49
339
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): return "keep_lane" # You can register a callable that will build your A...
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): return "keep_lane" # You can register a callable that will build your A...
47,793
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/scenarios/sumo/zoo_intersection/agent_prefabs.py
8,9
7,13
act
SimpleAgent
9,13
9,13
class SimpleAgent(Agent): def act(self, obs): FILL_FUNC_BODY
class SimpleAgent(Agent): def act(self, obs): FILL_FUNC_BODY
return "keep_lane" # You can register a callable that will build your AgentSpec
return "keep_lane" # You can register a callable that will build your AgentSpec
13
26
29
55
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): FILL_FUNC_BODYdef demo_agent_callable(target_prefix=None, interface=None): if...
from smarts.core.agent import Agent from smarts.core.agent_interface import AgentInterface, AgentType from smarts.zoo.agent_spec import AgentSpec from smarts.zoo.registry import register class SimpleAgent(Agent): def act(self, obs): FILL_FUNC_BODYdef demo_agent_callable(target_prefix=None, interface=None): if...
47,794
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
99,100
1,148
costs_to_score
122,144
100,144
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
dist_to_destination = costs.dist_to_destination humanness_error = _score_humanness_error(costs=costs) rule_violation = score_rule_violation(costs=costs) time = costs.steps overall = ( 0.25 * (1 - dist_to_destination) + 0.25 * (1 - time) + 0.25 * (1 - humanness_error) ...
"""Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ ...
54
1,363
233
1,596
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
47,795
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
61,62
53,99
params
Formula
67,82
62,82
class Formula(FormulaBase): """Sets the (i) cost function parameters, and (ii) score computation formula, for an environment. """ def __init__(self): pass def params(self) -> Params: FILL_FUNC_BODY def score(self, records: Dict[str, Dict[str, Record]]) -> Score: """ Comp...
class Formula(FormulaBase): """Sets the (i) cost function parameters, and (ii) score computation formula, for an environment. """ def __init__(self): pass def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Para...
params = Params( collisions=Collisions(active=False), comfort=Comfort(active=True), dist_to_destination=DistToDestination(active=True), dist_to_obstacles=DistToObstacles(active=False), jerk_linear=JerkLinear(active=False), lane_center_offse...
"""Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters. """ params = Params( collisions=Collisions(active=False), comfort=Comfort(active=True), dist_to_destination=DistToDestination(activ...
17
275
191
466
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
47,796
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
99,100
1,148
costs_to_score
122,144
100,144
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
dist_to_destination = costs.dist_to_destination humanness_error = _score_humanness_error(costs=costs) rule_violation = score_rule_violation(costs=costs) vehicle_gap = costs.vehicle_gap overall = ( 0.25 * (1 - dist_to_destination) + 0.25 * (1 - vehicle_gap) + 0.25 * (1 - human...
"""Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ ...
54
1,369
247
1,616
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
47,797
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
82,83
53,99
score
Formula
93,99
83,99
class Formula(FormulaBase): """Sets the (i) cost function parameters, and (ii) score computation formula, for an environment. """ def __init__(self): pass def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Para...
class Formula(FormulaBase): """Sets the (i) cost function parameters, and (ii) score computation formula, for an environment. """ def __init__(self): pass def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Para...
agent_weight = agent_weights(records=records) agent_score = agent_scores(records=records, func=costs_to_score) return weighted_score(scores=agent_score, weights=agent_weight)
""" Computes several sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores. """ ...
10
385
72
457
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
# MIT License # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
47,798
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/actor.py
62,63
48,81
get_dimensions
ActorState
64,66
63,66
@dataclass class ActorState: """Actor state information.""" actor_id: str # must be unique within the simulation actor_type: Optional[str] = None source: Optional[str] = None # the source of truth for this Actor's state role: ActorRole = ActorRole.Unknown updated: bool = False def get_po...
@dataclass class ActorState: """Actor state information.""" actor_id: str # must be unique within the simulation actor_type: Optional[str] = None source: Optional[str] = None # the source of truth for this Actor's state role: ActorRole = ActorRole.Unknown updated: bool = False def get_po...
return None
"""Get the dimensions of this actor. Some actors do not have physical dimensions.""" return None
2
348
7
355
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,799
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/actor_capture_manager.py
65,69
40,220
_make_new_vehicle
ActorCaptureManager
69,88
69,88
class ActorCaptureManager: """The base for managers that handle transition of control of actors.""" 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 ...
class ActorCaptureManager: """The base for managers that handle transition of control of actors.""" 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 ...
if social: return cls.__make_new_social_vehicle(sim, agent_id, initial_speed) agent_interface = sim.agent_manager.agent_interface_for_agent_id(agent_id) plan = Plan(sim.road_map, mission) # Apply agent vehicle association. vehicle = sim.vehicle_index.build_agent_vehic...
if social: return cls.__make_new_social_vehicle(sim, agent_id, initial_speed) agent_interface = sim.agent_manager.agent_interface_for_agent_id(agent_id) plan = Plan(sim.road_map, mission) # Apply agent vehicle association. vehicle = sim.vehicle_index.build_agent_vehic...
40
1,695
220
1,915
# MIT License # # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,800
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent.py
62,63
1,74
deprecated_agent_spec
64,73
63,73
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from smarts.zoo.agent_spec import AgentSpec as AgentSpecAlias warnings.warn( "The AgentSpec class has moved to the following module: smarts.zoo.agent_spec. Calling it from this module will be deprecated.", DeprecationWarning, ) return AgentSpecAlias(*args, **kwargs)
"""Deprecated version of AgentSpec, see smarts.zoo.agent_spec""" from smarts.zoo.agent_spec import AgentSpec as AgentSpecAlias warnings.warn( "The AgentSpec class has moved to the following module: smarts.zoo.agent_spec. Calling it from this module will be deprecated.", DeprecationWarning, ...
30
704
96
800
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,801
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent.py
41,43
28,51
act
Agent
47,51
43,51
class Agent(metaclass=ABCMeta): """The base class for agents""" @classmethod def from_function(cls, agent_function: Callable[[Any], Any]) -> "Agent": """A utility function to create an agent from a lambda or other callable object. .. code-block:: python keep_lane_agent = Agent...
class Agent(metaclass=ABCMeta): """The base class for agents""" @classmethod def from_function(cls, agent_function: Callable[[Any], Any]) -> "Agent": """A utility function to create an agent from a lambda or other callable object. .. code-block:: python keep_lane_agent = Agent...
raise NotImplementedError
"""The agent action. See documentation on observations, `AgentSpec`, and `AgentInterface`. Expects an adapted observation and returns a raw action. """ raise NotImplementedError
2
190
15
205
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,802
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent.py
58,59
51,62
act
FunctionAgent
59,62
59,62
class FunctionAgent(Agent): """An agent generated from a function.""" def __init__(self, agent_function) -> None: assert callable(agent_function) self._agent_function = agent_function def act(self, obs, **configs): FILL_FUNC_BODY
class FunctionAgent(Agent): """An agent generated from a function.""" def __init__(self, agent_function) -> None: assert callable(agent_function) self._agent_function = agent_function def act(self, obs, **configs): FILL_FUNC_BODY
return self._agent_function(obs)
return self._agent_function(obs)
2
79
16
95
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,803
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_buffer.py
34,38
26,40
acquire_agent
AgentBuffer
39,40
38,40
class AgentBuffer(metaclass=abc.ABCMeta): """Defines a buffer of agents for external use.""" @abc.abstractmethod def destroy(self): """Clean up the buffer resources.""" raise NotImplementedError @abc.abstractmethod def acquire_agent( self, retries: int = 3, timeout: Optiona...
class AgentBuffer(metaclass=abc.ABCMeta): """Defines a buffer of agents for external use.""" @abc.abstractmethod def destroy(self): """Clean up the buffer resources.""" raise NotImplementedError @abc.abstractmethod def acquire_agent( self, retries: int = 3, timeout: Optiona...
raise NotImplementedError
"""Get an agent from the buffer.""" raise NotImplementedError
2
125
9
134
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,805
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
142,144
131,147
name
CustomRenderBufferDependency
144,147
144,147
@dataclass class CustomRenderBufferDependency(RenderDependencyBase): """Base for referencing an observation buffer (other than a camera).""" buffer_dependency_name: Union[str, BufferID] """The identification of buffer to reference.""" variable_name: str """The variable name inside the shader.""" ...
@dataclass class CustomRenderBufferDependency(RenderDependencyBase): """Base for referencing an observation buffer (other than a camera).""" buffer_dependency_name: Union[str, BufferID] """The identification of buffer to reference.""" variable_name: str """The variable name inside the shader.""" ...
return self.variable_name
return self.variable_name
2
124
13
137
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,806
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
159,161
147,173
name
CustomRenderCameraDependency
161,163
161,163
@dataclass class CustomRenderCameraDependency(RenderDependencyBase): """Provides a uniform texture access to an existing camera.""" camera_dependency_name: Union[str, CameraSensorID] """The name of the camera (type) to target.""" variable_name: str """The name of the camera texture variable.""" ...
@dataclass class CustomRenderCameraDependency(RenderDependencyBase): """Provides a uniform texture access to an existing camera.""" camera_dependency_name: Union[str, CameraSensorID] """The name of the camera (type) to target.""" variable_name: str """The name of the camera texture variable.""" ...
return self.variable_name
return self.variable_name
2
258
11
269
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,807
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
117,119
108,131
name
CustomRenderVariableDependency
119,121
119,121
@dataclass class CustomRenderVariableDependency(RenderDependencyBase): """Base for renderer value to pass directly to the shader.""" value: Union[int, float, bool, np.ndarray, list, tuple] """The value to pass to the shader.""" variable_name: str """The uniform name inside the shader.""" @prop...
@dataclass class CustomRenderVariableDependency(RenderDependencyBase): """Base for renderer value to pass directly to the shader.""" value: Union[int, float, bool, np.ndarray, list, tuple] """The value to pass to the shader.""" variable_name: str """The uniform name inside the shader.""" @prop...
return self.variable_name
return self.variable_name
2
198
11
209
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,808
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
384,386
359,391
actors_alive
DoneCriteria
387,391
386,391
@dataclass(frozen=True) class DoneCriteria: """Toggle conditions on which cause removal of an agent from the current episode.""" collision: bool = True """End the episode when the agent collides with another vehicle.""" off_road: bool = True """End the episode when the agent drives off the road."""...
@dataclass(frozen=True) class DoneCriteria: """Toggle conditions on which cause removal of an agent from the current episode.""" collision: bool = True """End the episode when the agent collides with another vehicle.""" off_road: bool = True """End the episode when the agent drives off the road."""...
warnings.warn("Use interest.", category=DeprecationWarning) return self.interest
"""Deprecated. Use interest.""" warnings.warn("Use interest.", category=DeprecationWarning) return self.interest
5
335
28
363
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,809
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
343,345
328,349
actors_pattern
InterestDoneCriteria
346,349
345,349
@dataclass(frozen=True) class InterestDoneCriteria: """Require scenario marked interest actors to exist.""" actors_filter: Tuple[str, ...] = () """Interface defined interest actors that should exist to continue this agent.""" include_scenario_marked: bool = True """If scenario marked interest acto...
@dataclass(frozen=True) class InterestDoneCriteria: """Require scenario marked interest actors to exist.""" actors_filter: Tuple[str, ...] = () """Interface defined interest actors that should exist to continue this agent.""" include_scenario_marked: bool = True """If scenario marked interest acto...
return re.compile("|".join(rf"(?:{aoi})" for aoi in self.actors_filter))
"""The expression match pattern for actors covered by this interface specifically.""" return re.compile("|".join(rf"(?:{aoi})" for aoi in self.actors_filter))
6
173
35
208
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,810
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agent_interface.py
101,104
97,108
name
RenderDependencyBase
105,108
104,108
@dataclass class RenderDependencyBase(metaclass=abc.ABCMeta): """Base class for render dependencies""" @property @abc.abstractmethod def name(self) -> str: FILL_FUNC_BODY
@dataclass class RenderDependencyBase(metaclass=abc.ABCMeta): """Base class for render dependencies""" @property @abc.abstractmethod def name(self) -> str: """The name of this dependency.""" FILL_FUNC_BODY
raise NotImplementedError()
"""The name of this dependency.""" raise NotImplementedError()
2
74
14
88
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,812
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agents_provider.py
239,241
232,252
actions
AgentPhysicsProvider
241,252
241,252
class AgentPhysicsProvider(AgentsProvider): """A provider that manages agent vehicles with Ackermann chassis, applying their actions via appropriate controllers to their chassis.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUN...
class AgentPhysicsProvider(AgentsProvider): """A provider that manages agent vehicles with Ackermann chassis, applying their actions via appropriate controllers to their chassis.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUN...
return { ActionSpaceType.Continuous, ActionSpaceType.Lane, ActionSpaceType.ActuatorDynamic, ActionSpaceType.LaneWithContinuousSpeed, ActionSpaceType.Trajectory, ActionSpaceType.MPC, ActionSpaceType.Empty, }
return { ActionSpaceType.Continuous, ActionSpaceType.Lane, ActionSpaceType.ActuatorDynamic, ActionSpaceType.LaneWithContinuousSpeed, ActionSpaceType.Trajectory, ActionSpaceType.MPC, ActionSpaceType.Empty, }
10
95
91
186
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,814
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agents_provider.py
259,261
252,264
actions
DirectControlProvider
261,264
261,264
class DirectControlProvider(AgentsProvider): """A provider that manages agent vehicles that are under direct control. These vehicles must have a Box chassis to allow for bypassing the application of forces.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Se...
class DirectControlProvider(AgentsProvider): """A provider that manages agent vehicles that are under direct control. These vehicles must have a Box chassis to allow for bypassing the application of forces.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Se...
return {ActionSpaceType.Direct}
return {ActionSpaceType.Direct}
2
97
15
112
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,815
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agents_provider.py
270,272
264,279
actions
MotionPlannerProvider
272,279
272,279
class MotionPlannerProvider(AgentsProvider): """A provider that reshapes agent vehicle motion to follow a motion plan.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUNC_BODY
class MotionPlannerProvider(AgentsProvider): """A provider that reshapes agent vehicle motion to follow a motion plan.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUNC_BODY
return { ActionSpaceType.TargetPose, ActionSpaceType.RelativeTargetPose, ActionSpaceType.MultiTargetPose, }
return { ActionSpaceType.TargetPose, ActionSpaceType.RelativeTargetPose, ActionSpaceType.MultiTargetPose, }
6
80
49
129
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,816
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/agents_provider.py
285,287
279,288
actions
TrajectoryInterpolationProvider
287,288
287,288
class TrajectoryInterpolationProvider(AgentsProvider): """A provider used to perform trajectory interpolation on agent actors that request trajectory following.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUNC_BODY
class TrajectoryInterpolationProvider(AgentsProvider): """A provider used to perform trajectory interpolation on agent actors that request trajectory following.""" def __init__(self, sim): super().__init__(sim) @property def actions(self) -> Set[ActionSpaceType]: FILL_FUNC_BODY
return {ActionSpaceType.TrajectoryWithTime}
return {ActionSpaceType.TrajectoryWithTime}
2
83
15
98
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,817
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/buffer_agent.py
41,43
28,45
terminate
BufferAgent
44,45
43,45
class BufferAgent(metaclass=abc.ABCMeta): """An agent which is part of a buffer.""" @abstractmethod def act(self, obs): """Gives a future action based on observations.""" raise NotImplementedError @abstractmethod def start(self, agent_spec: AgentSpec): """Begin operation of...
class BufferAgent(metaclass=abc.ABCMeta): """An agent which is part of a buffer.""" @abstractmethod def act(self, obs): """Gives a future action based on observations.""" raise NotImplementedError @abstractmethod def start(self, agent_spec: AgentSpec): """Begin operation of...
raise NotImplementedError
"""Clean up agent resources.""" raise NotImplementedError
2
135
9
144
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,818
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/controllers/actuator_dynamic_controller.py
35,37
32,66
perform_action
ActuatorDynamicController
40,66
37,66
class ActuatorDynamicController: """A controller that maintains the last steering angle.""" @classmethod def perform_action(cls, vehicle, action, state, dt_sec): FILL_FUNC_BODY
class ActuatorDynamicController: """A controller that maintains the last steering angle.""" @classmethod def perform_action(cls, vehicle, action, state, dt_sec): """Perform throttle, break, and steering, keeping the previous steering angle as the start for the next steering angle. "...
throttle, brake, steering_change = action # The following is the normalized steering change # under the assumption that the steering angles at # wheels can reach to their maximum values in one # second. clipped_steering_change = np.clip( steering_change, ...
"""Perform throttle, break, and steering, keeping the previous steering angle as the start for the next steering angle. """ throttle, brake, steering_change = action # The following is the normalized steering change # under the assumption that the steering angles at ...
83
88
265
353
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,819
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/controllers/direct_controller.py
34,41
30,102
perform_action
DirectController
50,102
41,102
class DirectController: """A controller that directly sets a vehicle's acceleration and angular velocity (rather than applying forces like torque) based on kinematics.""" @classmethod def perform_action( cls, dt: float, vehicle, action: Union[float, Tuple[float, float]],...
class DirectController: """A controller that directly sets a vehicle's acceleration and angular velocity (rather than applying forces like torque) based on kinematics.""" @classmethod def perform_action( cls, dt: float, vehicle, action: Union[float, Tuple[float, float]],...
chassis = vehicle.chassis if isinstance(action, (int, float)): # special case: setting the initial speed if isinstance(chassis, BoxChassis): vehicle.control(vehicle.pose, action, dt) elif isinstance(chassis, AckermannChassis): chassis....
"""Performs an action adapting to the underlying chassis. Args: dt (float): A delta time value. vehicle (Vehicle): The vehicle to control. action (Union[float, Tuple[float, float]]): (speed) XOR (acceleration, angular_ve...
283
182
819
1,001
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,821
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/controllers/trajectory_interpolation_controller.py
58,60
40,127
_interpolate
TrajectoryInterpolationController
65,83
60,83
class TrajectoryInterpolationController: """A controller used to perform trajectory interpolation.""" @classmethod def assert_is_legal_trajectory(cls, trajectory: np.ndarray): """Test if the trajectory is correctly formed.""" assert ( len(trajectory[TrajectoryField.TIME_INDEX]) ...
class TrajectoryInterpolationController: """A controller used to perform trajectory interpolation.""" @classmethod def assert_is_legal_trajectory(cls, trajectory: np.ndarray): """Test if the trajectory is correctly formed.""" assert ( len(trajectory[TrajectoryField.TIME_INDEX]) ...
start_time = ms0[TrajectoryField.TIME_INDEX] end_time = ms1[TrajectoryField.TIME_INDEX] assert ( end_time >= start_time and time >= start_time ), f"{start_time} <= {time} <= {end_time} ?" ratio = math.fabs((time - start_time) / (end_time - start_time)) left_ov...
"""Linearly interpolate between two vehicle motion states. Returns: np.ndarray: New vehicle state between vehicle motion state ms0 and ms1 """ start_time = ms0[TrajectoryField.TIME_INDEX] end_time = ms1[TrajectoryField.TIME_INDEX] assert ( end_tim...
73
831
292
1,123
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,823
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/data_model.py
43,44
31,46
to_agent_spec
SocialAgent
45,46
44,46
@dataclass class SocialAgent: """A serializable representation of a social agent.""" id: str actor_name: str is_boid: bool is_boid_keep_alive: bool agent_locator: str policy_kwargs: Dict[str, Any] = field(default_factory=dict) initial_speed: Optional[float] = None def to_agent_spec...
@dataclass class SocialAgent: """A serializable representation of a social agent.""" id: str actor_name: str is_boid: bool is_boid_keep_alive: bool agent_locator: str policy_kwargs: Dict[str, Any] = field(default_factory=dict) initial_speed: Optional[float] = None def to_agent_spec...
return make(locator=self.agent_locator, **self.policy_kwargs)
"""Generate an agent spec.""" return make(locator=self.agent_locator, **self.policy_kwargs)
3
134
23
157
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,825
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/events.py
54,56
29,59
actors_alive_done
Events
57,59
56,59
class Events(NamedTuple): """Classified observations that can trigger agent done status.""" collisions: Tuple[Collision] """Collisions with other vehicles (if any).""" off_road: bool """True if vehicle is off the road, else False.""" off_route: bool """True if vehicle is off the mission rou...
class Events(NamedTuple): """Classified observations that can trigger agent done status.""" collisions: Tuple[Collision] """Collisions with other vehicles (if any).""" off_road: bool """True if vehicle is off the road, else False.""" off_route: bool """True if vehicle is off the mission rou...
warnings.warn("Use interest_done.", category=DeprecationWarning) return self.interest_done
"""Deprecated. Use interest_done.""" warnings.warn("Use interest_done.", category=DeprecationWarning) return self.interest_done
5
320
28
348
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,826
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/external_provider.py
108,109
35,145
step
ExternalProvider
109,111
109,111
class ExternalProvider(Provider): """A provider that is intended to be used for external intervention in the simulation. Vehicles managed by this provider cannot be hijacked by social agents and may have privileged VehicleStates.""" def __init__(self, sim): # start with the default recovery fla...
class ExternalProvider(Provider): """A provider that is intended to be used for external intervention in the simulation. Vehicles managed by this provider cannot be hijacked by social agents and may have privileged VehicleStates.""" def __init__(self, sim): # start with the default recovery fla...
return self._provider_state
return self._provider_state
2
1,063
11
1,074
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,827
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/id_actor_capture_manager.py
98,99
37,131
reset
IdActorCaptureManager
99,129
99,129
class IdActorCaptureManager(ActorCaptureManager): """The base for managers that handle transition of control of actors.""" def __init__(self) -> None: self._log = logging.getLogger(self.__class__.__name__) self._actor_for_agent: Dict[str, Tuple[str, NavigationMission]] = {} def step(self, ...
class IdActorCaptureManager(ActorCaptureManager): """The base for managers that handle transition of control of actors.""" def __init__(self) -> None: self._log = logging.getLogger(self.__class__.__name__) self._actor_for_agent: Dict[str, Tuple[str, NavigationMission]] = {} def step(self, ...
self._actor_for_agent.clear() missions: Dict[str, NavigationMission] = scenario.missions cancelled_agents = set() for agent_id, mission in missions.items(): if mission is None: continue entry_tactic = mission.entry_tactic if not isinsta...
self._actor_for_agent.clear() missions: Dict[str, NavigationMission] = scenario.missions cancelled_agents = set() for agent_id, mission in missions.items(): if mission is None: continue entry_tactic = mission.entry_tactic if not isinsta...
89
730
433
1,163
# MIT License # # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
47,828
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/local_agent.py
46,47
32,53
start
LocalAgent
48,51
47,51
class LocalAgent(BufferAgent): """A local implementation of a buffer agent.""" def __init__(self): self._agent: Agent = None self._agent_spec: AgentSpec = None def act(self, obs): """Call the agent's act function asynchronously and return a Future.""" act_future = futures....
class LocalAgent(BufferAgent): """A local implementation of a buffer agent.""" def __init__(self): self._agent: Agent = None self._agent_spec: AgentSpec = None def act(self, obs): """Call the agent's act function asynchronously and return a Future.""" act_future = futures....
self._agent_spec = agent_spec self._agent = self._agent_spec.build_agent()
"""Send the AgentSpec to the agent runner.""" self._agent_spec = agent_spec self._agent = self._agent_spec.build_agent()
6
161
31
192
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,829
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/local_agent_buffer.py
36,39
27,41
acquire_agent
LocalAgentBuffer
39,41
39,41
class LocalAgentBuffer(AgentBuffer): """A buffer that manages social agents.""" def __init__(self): pass def destroy(self): pass def acquire_agent( self, retries: int = 3, timeout: Optional[float] = None ) -> BufferAgent: FILL_FUNC_BODY
class LocalAgentBuffer(AgentBuffer): """A buffer that manages social agents.""" def __init__(self): pass def destroy(self): pass def acquire_agent( self, retries: int = 3, timeout: Optional[float] = None ) -> BufferAgent: FILL_FUNC_BODY
localAgent = LocalAgent() return localAgent
localAgent = LocalAgent() return localAgent
5
89
15
104
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,831
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/local_traffic_provider.py
831,833
789,890
_angle_scale
_LaneWindow
833,872
833,872
class _LaneWindow: def __init__( self, lane: RoadMap.Lane, time_left: float, ttc: float, ttre: float, gap: float, lane_coord: RefLinePoint, agent_gap: Optional[float], ahead_id: Optional[str], ...
class _LaneWindow: def __init__( self, lane: RoadMap.Lane, time_left: float, ttc: float, ttre: float, gap: float, lane_coord: RefLinePoint, agent_gap: Optional[float], ahead_id: Optional[str], ...
# we need to correct for not going straight across. # other things being equal, we target ~30 degrees (sin(30)=.5) on average. if abs(self.radius) > 1e5 or self.radius == 0: return safe_division(1.0, math.sin(theta), 1e6) # here we correct for the local ro...
# we need to correct for not going straight across. # other things being equal, we target ~30 degrees (sin(30)=.5) on average. if abs(self.radius) > 1e5 or self.radius == 0: return safe_division(1.0, math.sin(theta), 1e6) # here we correct for the local ro...
151
803
437
1,240
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,832
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/local_traffic_provider.py
1307,1308
1274,1378
predict_crash_in
_RelWindow
1311,1369
1308,1369
class _RelWindow: @dataclass class _RelativeVehInfo: dist: float bearing: float heading: float dt: float def __init__(self, width: int = 5): self._width = width self._junction_foes: Dict[ Tuple[str, int]...
class _RelWindow: @dataclass class _RelativeVehInfo: dist: float bearing: float heading: float dt: float def __init__(self, width: int = 5): self._width = width self._junction_foes: Dict[ Tuple[str, int]...
# CBDR is a good approximation at distance over time with # both vehicles behaving "steadily" (ideally, driving # straight at a constant speed). It breaks down, thankfully # in preictable ways, if these assumptions are violated. # # Range Dependen...
"""Estimate if and when I might collide with veh_id using the constant bearing, decreasing range (CBDR) techique, but attempting to correct for non-linearities.""" # CBDR is a good approximation at distance over time with # both vehicles behaving "steadily" (i...
372
539
830
1,369
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
47,834
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS
/home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/core/observations.py
213,215
207,219
hit_via_points
Vias
216,219
215,219
class Vias(NamedTuple): """Listing of nearby collectible ViaPoints and ViaPoints collected in the last step.""" near_via_points: Tuple[ViaPoint] """Ordered list of nearby points that have not been hit.""" @property def hit_via_points(self) -> Tuple[ViaPoint]: FILL_FUNC_BODY
class Vias(NamedTuple): """Listing of nearby collectible ViaPoints and ViaPoints collected in the last step.""" near_via_points: Tuple[ViaPoint] """Ordered list of nearby points that have not been hit.""" @property def hit_via_points(self) -> Tuple[ViaPoint]: """List of points that were hi...
return tuple(vp for vp in self.near_via_points if vp.hit)
"""List of points that were hit in the previous step.""" return tuple(vp for vp in self.near_via_points if vp.hit)
8
111
30
141
# MIT License # # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
# MIT License # # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...