humalab 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of humalab might be problematic. Click here for more details.
- humalab/__init__.py +9 -0
- humalab/assets/__init__.py +0 -0
- humalab/assets/archive.py +101 -0
- humalab/assets/resource_file.py +28 -0
- humalab/assets/resource_handler.py +175 -0
- humalab/constants.py +7 -0
- humalab/dists/__init__.py +17 -0
- humalab/dists/bernoulli.py +44 -0
- humalab/dists/categorical.py +49 -0
- humalab/dists/discrete.py +56 -0
- humalab/dists/distribution.py +38 -0
- humalab/dists/gaussian.py +49 -0
- humalab/dists/log_uniform.py +49 -0
- humalab/dists/truncated_gaussian.py +64 -0
- humalab/dists/uniform.py +49 -0
- humalab/humalab.py +149 -0
- humalab/humalab_api_client.py +273 -0
- humalab/humalab_config.py +86 -0
- humalab/humalab_test.py +510 -0
- humalab/metrics/__init__.py +11 -0
- humalab/metrics/dist_metric.py +22 -0
- humalab/metrics/metric.py +129 -0
- humalab/metrics/summary.py +54 -0
- humalab/run.py +214 -0
- humalab/scenario.py +225 -0
- humalab/scenario_test.py +911 -0
- humalab-0.0.1.dist-info/METADATA +43 -0
- humalab-0.0.1.dist-info/RECORD +32 -0
- humalab-0.0.1.dist-info/WHEEL +5 -0
- humalab-0.0.1.dist-info/entry_points.txt +2 -0
- humalab-0.0.1.dist-info/licenses/LICENSE +21 -0
- humalab-0.0.1.dist-info/top_level.txt +1 -0
humalab/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
import zipfile
|
|
3
|
+
import tarfile
|
|
4
|
+
import gzip
|
|
5
|
+
import bz2
|
|
6
|
+
import lzma
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
import py7zr # for .7z
|
|
12
|
+
except ImportError:
|
|
13
|
+
py7zr = None
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import rarfile # for .rar
|
|
17
|
+
except ImportError:
|
|
18
|
+
rarfile = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ---------- Detection ---------------------------------------------------------
|
|
22
|
+
def detect_archive_type(path: str | Path) -> str:
|
|
23
|
+
"""Return a simple string label for the archive type, else 'unknown'."""
|
|
24
|
+
p = Path(path).with_suffix("").name.lower() # strip double-suffix like .tar.gz
|
|
25
|
+
ext = Path(path).suffix.lower()
|
|
26
|
+
|
|
27
|
+
if ext == ".zip":
|
|
28
|
+
return "zip"
|
|
29
|
+
if ext in {".tar"}:
|
|
30
|
+
return "tar"
|
|
31
|
+
if ext in {".gz"} and p.endswith(".tar"):
|
|
32
|
+
return "tar.gz"
|
|
33
|
+
if ext in {".bz2"} and p.endswith(".tar"):
|
|
34
|
+
return "tar.bz2"
|
|
35
|
+
if ext in {".xz"} and p.endswith(".tar"):
|
|
36
|
+
return "tar.xz"
|
|
37
|
+
if ext == ".gz":
|
|
38
|
+
return "gzip"
|
|
39
|
+
if ext == ".bz2":
|
|
40
|
+
return "bzip2"
|
|
41
|
+
if ext == ".xz":
|
|
42
|
+
return "xz"
|
|
43
|
+
if ext == ".7z":
|
|
44
|
+
return "7z"
|
|
45
|
+
if ext == ".rar":
|
|
46
|
+
return "rar"
|
|
47
|
+
return "unknown"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _extract_stream(open_func, path: Path, out_dir: Path):
|
|
51
|
+
"""Helper for single-file compressed streams (.gz, .bz2, .xz)."""
|
|
52
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
out_file = out_dir / path.with_suffix("").name
|
|
54
|
+
with open_func(path, "rb") as f_in, open(out_file, "wb") as f_out:
|
|
55
|
+
shutil.copyfileobj(f_in, f_out)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---------- Extraction --------------------------------------------------------
|
|
59
|
+
def extract_archive(path: str | Path, out_dir: str | Path) -> None:
|
|
60
|
+
"""Detect the archive type and extract it into out_dir."""
|
|
61
|
+
path, out_dir = Path(path), Path(out_dir)
|
|
62
|
+
archive_type = detect_archive_type(path)
|
|
63
|
+
|
|
64
|
+
match archive_type:
|
|
65
|
+
# --- ZIP
|
|
66
|
+
case "zip":
|
|
67
|
+
with zipfile.ZipFile(path) as zf:
|
|
68
|
+
zf.extractall(out_dir)
|
|
69
|
+
|
|
70
|
+
# --- tar.* (auto-deduces compression)
|
|
71
|
+
case "tar" | "tar.gz" | "tar.bz2" | "tar.xz":
|
|
72
|
+
with tarfile.open(path, mode="r:*") as tf:
|
|
73
|
+
tf.extractall(out_dir)
|
|
74
|
+
|
|
75
|
+
# --- single-file streams
|
|
76
|
+
case "gzip":
|
|
77
|
+
_extract_stream(gzip.open, path, out_dir)
|
|
78
|
+
case "bzip2":
|
|
79
|
+
_extract_stream(bz2.open, path, out_dir)
|
|
80
|
+
case "xz":
|
|
81
|
+
_extract_stream(lzma.open, path, out_dir)
|
|
82
|
+
|
|
83
|
+
# --- 7-Zip
|
|
84
|
+
case "7z":
|
|
85
|
+
if py7zr is None:
|
|
86
|
+
raise ImportError("py7zr not installed - run `pip install py7zr`")
|
|
87
|
+
with py7zr.SevenZipFile(path, mode="r") as z:
|
|
88
|
+
z.extractall(path=out_dir)
|
|
89
|
+
|
|
90
|
+
# --- RAR
|
|
91
|
+
case "rar":
|
|
92
|
+
if rarfile is None:
|
|
93
|
+
raise ImportError("rarfile not installed - run `pip install rarfile`")
|
|
94
|
+
if not rarfile.is_rarfile(path):
|
|
95
|
+
raise rarfile.BadRarFile(f"{path} is not a valid RAR archive")
|
|
96
|
+
with rarfile.RarFile(path) as rf:
|
|
97
|
+
rf.extractall(out_dir)
|
|
98
|
+
|
|
99
|
+
# --- fallback
|
|
100
|
+
case _:
|
|
101
|
+
raise ValueError(f"Unsupported or unknown archive type: {archive_type}")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
class ResourceFile:
|
|
4
|
+
def __init__(self,
|
|
5
|
+
name: str,
|
|
6
|
+
version: int,
|
|
7
|
+
resource_type: str,
|
|
8
|
+
filepath: str):
|
|
9
|
+
self._name = name
|
|
10
|
+
self._version = version
|
|
11
|
+
self._resource_type = resource_type
|
|
12
|
+
self._filepath = filepath
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def name(self) -> str:
|
|
16
|
+
return self._name
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def version(self) -> int:
|
|
20
|
+
return self._version
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def resource_type(self) -> str:
|
|
24
|
+
return self._resource_type
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def filepath(self) -> str:
|
|
28
|
+
return self._filepath
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import mongoengine as me
|
|
2
|
+
from minio import Minio
|
|
3
|
+
import os
|
|
4
|
+
import glob
|
|
5
|
+
import tempfile
|
|
6
|
+
import trimesh
|
|
7
|
+
from humalab_service.humalab_host import HumaLabHost
|
|
8
|
+
from humalab_service.services.stores.obj_store import ObjStore
|
|
9
|
+
from humalab_service.services.stores.namespace import ObjectType
|
|
10
|
+
from humalab_service.db.resource import ResourceDocument
|
|
11
|
+
from humalab_sdk.assets.archive import extract_archive
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
ASSET_TYPE_TO_EXTENSIONS = {
|
|
15
|
+
"urdf": {"urdf"},
|
|
16
|
+
"mjcf": {"xml"},
|
|
17
|
+
"mesh": trimesh.available_formats(),
|
|
18
|
+
"usd": {"usd"},
|
|
19
|
+
"controller": {"py"},
|
|
20
|
+
"global_controller": {"py"},
|
|
21
|
+
"terminator": {"py"},
|
|
22
|
+
"data": {},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
class ResourceHandler:
|
|
26
|
+
def __init__(self, working_path: str=tempfile.gettempdir()):
|
|
27
|
+
self._minio_client = Minio(
|
|
28
|
+
HumaLabHost.get_minio_service_address(),
|
|
29
|
+
access_key="humalab",
|
|
30
|
+
secret_key="humalab123",
|
|
31
|
+
secure=False
|
|
32
|
+
)
|
|
33
|
+
self._obj_store = ObjStore(self._minio_client)
|
|
34
|
+
self.working_path_root = working_path
|
|
35
|
+
|
|
36
|
+
def search_resource_file(self, resource_filename: str | None, working_path: str, morph_type: str) -> str | None:
|
|
37
|
+
found_filename = None
|
|
38
|
+
if resource_filename:
|
|
39
|
+
search_path = os.path.join(working_path, "**")
|
|
40
|
+
search_pattern = os.path.join(search_path, resource_filename)
|
|
41
|
+
files = glob.glob(search_pattern, recursive=True)
|
|
42
|
+
if len(files) > 0:
|
|
43
|
+
found_filename = files[0]
|
|
44
|
+
|
|
45
|
+
if found_filename is None:
|
|
46
|
+
for ext in ASSET_TYPE_TO_EXTENSIONS[morph_type]:
|
|
47
|
+
search_pattern = os.path.join(working_path, "**", f"*.{ext}")
|
|
48
|
+
files = glob.glob(search_pattern, recursive=True)
|
|
49
|
+
if len(files) > 0:
|
|
50
|
+
found_filename = files[0]
|
|
51
|
+
break
|
|
52
|
+
return found_filename
|
|
53
|
+
|
|
54
|
+
def _save_file(self, filepath: str, data: bytes) -> str:
|
|
55
|
+
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
|
56
|
+
with open(filepath, "wb") as f:
|
|
57
|
+
f.write(data)
|
|
58
|
+
return filepath
|
|
59
|
+
|
|
60
|
+
def _save_and_extract(self, working_path: str, local_filepath: str, file_content: bytes, file_type: str):
|
|
61
|
+
os.makedirs(working_path, exist_ok=True)
|
|
62
|
+
saved_filepath = self._save_file(local_filepath, file_content)
|
|
63
|
+
_, ext = os.path.splitext(saved_filepath)
|
|
64
|
+
ext = ext.lstrip('.') # Remove leading dot
|
|
65
|
+
if ext not in ASSET_TYPE_TO_EXTENSIONS[file_type]:
|
|
66
|
+
extract_archive(saved_filepath, working_path)
|
|
67
|
+
try:
|
|
68
|
+
os.remove(saved_filepath)
|
|
69
|
+
except Exception as e:
|
|
70
|
+
print(f"Error removing saved file {saved_filepath}: {e}")
|
|
71
|
+
|
|
72
|
+
def save_file(self,
|
|
73
|
+
resource_name: str,
|
|
74
|
+
resource_version: int,
|
|
75
|
+
object_type: ObjectType,
|
|
76
|
+
file_content: bytes,
|
|
77
|
+
file_url: str,
|
|
78
|
+
resource_type: str,
|
|
79
|
+
filename: str | None = None) -> str:
|
|
80
|
+
working_path = self.get_working_path(object_type, resource_name, resource_version)
|
|
81
|
+
local_filepath = os.path.join(working_path, os.path.basename(file_url))
|
|
82
|
+
local_filename = None
|
|
83
|
+
if os.path.exists(os.path.dirname(working_path)):
|
|
84
|
+
# if directory exists, try to search for the file
|
|
85
|
+
local_filename = self.search_resource_file(filename, working_path, resource_type)
|
|
86
|
+
if local_filename is None:
|
|
87
|
+
# if not found, save the file and extract the archive,
|
|
88
|
+
# then search for the file again
|
|
89
|
+
self._save_and_extract(working_path, local_filepath, file_content, resource_type)
|
|
90
|
+
local_filename = self.search_resource_file(filename, working_path, resource_type)
|
|
91
|
+
if local_filename is None:
|
|
92
|
+
# if still not found, raise an error
|
|
93
|
+
raise ValueError(f"Resource filename {filename} not found in {working_path}")
|
|
94
|
+
return local_filename
|
|
95
|
+
|
|
96
|
+
def get_working_path(self, obj_type: ObjectType, uuid: str, version: int) -> str:
|
|
97
|
+
return os.path.join(self.working_path_root, "humalab", obj_type.value, uuid + "_" + str(version))
|
|
98
|
+
|
|
99
|
+
def query_and_download_resource(self, resource_name: str, resource_version: int | None = None) -> tuple[str, str]:
|
|
100
|
+
""" Query the resource from the database and download it from the object store.
|
|
101
|
+
Args:
|
|
102
|
+
resource_name (str): The name of the resource.
|
|
103
|
+
resource_version (int | None): The version of the resource. If None, the latest version will be used.
|
|
104
|
+
Returns:
|
|
105
|
+
tuple[str, str]: A tuple containing the local filename of the resource and the working directory
|
|
106
|
+
where the resource was downloaded and extracted.
|
|
107
|
+
"""
|
|
108
|
+
me.connect("humalab", host=f"mongodb://{HumaLabHost.get_mongodb_service_address()}")
|
|
109
|
+
if resource_version is None:
|
|
110
|
+
resource = ResourceDocument.objects(name=resource_name.strip(), latest=True).first()
|
|
111
|
+
else:
|
|
112
|
+
resource = ResourceDocument.objects(name=resource_name.strip(), version=resource_version).first()
|
|
113
|
+
if resource is None:
|
|
114
|
+
raise ValueError(f"Resource {resource_name}:{resource_version} not found")
|
|
115
|
+
return self.download_resource(resource.name, resource.version, resource.file_url, resource.resource_type.value, resource.filename)
|
|
116
|
+
|
|
117
|
+
def download_resource(self,
|
|
118
|
+
resource_name: str,
|
|
119
|
+
resource_version: int,
|
|
120
|
+
resource_url: str,
|
|
121
|
+
resource_type: str,
|
|
122
|
+
resource_filename: str | None = None) -> tuple[str, str]:
|
|
123
|
+
""" Download a resource from the object store.
|
|
124
|
+
Args:
|
|
125
|
+
resource_name (str): The name of the resource.
|
|
126
|
+
resource_version (int): The version of the resource.
|
|
127
|
+
resource_url (str): The URL of the resource in the object store.
|
|
128
|
+
resource_type (str): The type of the resource (e.g., "urdf", "mjcf", "mesh", etc.).
|
|
129
|
+
resource_filename (str | None): The specific filename to search for within the resource directory. If None, the first file found will be used.
|
|
130
|
+
Returns:
|
|
131
|
+
tuple[str, str]: A tuple containing the local filename of the resource and the working directory
|
|
132
|
+
where the resource was downloaded and extracted.
|
|
133
|
+
"""
|
|
134
|
+
return self._download_resource(resource_name,
|
|
135
|
+
resource_version,
|
|
136
|
+
ObjectType.RESOURCE,
|
|
137
|
+
resource_url,
|
|
138
|
+
resource_type,
|
|
139
|
+
resource_filename)
|
|
140
|
+
|
|
141
|
+
def _download_resource(self,
|
|
142
|
+
resource_name: str,
|
|
143
|
+
resource_version: int,
|
|
144
|
+
object_type: ObjectType,
|
|
145
|
+
resource_url: str,
|
|
146
|
+
resource_type: str,
|
|
147
|
+
resource_filename: str | None = None) -> tuple[str, str]:
|
|
148
|
+
"""
|
|
149
|
+
Download an asset from the object store and extract it if necessary.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
asset_uuid (str): The UUID of the asset.
|
|
153
|
+
asset_version (int): The version of the asset.
|
|
154
|
+
asset_type (ObjectType): The type of the asset (e.g., URDF, MJCF, Mesh, etc.).
|
|
155
|
+
asset_url (str): The URL of the asset in the object store.
|
|
156
|
+
asset_file_type (str): The type of the asset file (e.g., "urdf", "mjcf", "mesh", etc.).
|
|
157
|
+
asset_filename (str | None): The specific filename to search for within the asset directory. If None, the first file found will be used.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
tuple[str, str]: A tuple containing the local filename of the asset and the working directory
|
|
161
|
+
where the asset was downloaded and extracted.
|
|
162
|
+
"""
|
|
163
|
+
working_path = self.get_working_path(object_type, resource_name, resource_version)
|
|
164
|
+
local_filepath = os.path.join(working_path, os.path.basename(resource_url))
|
|
165
|
+
if not os.path.exists(working_path):
|
|
166
|
+
os.makedirs(working_path, exist_ok=True)
|
|
167
|
+
self._obj_store.download_file(object_type, resource_url, local_filepath)
|
|
168
|
+
_, ext = os.path.splitext(resource_url)
|
|
169
|
+
ext = ext.lower().lstrip('.')
|
|
170
|
+
if ext not in ASSET_TYPE_TO_EXTENSIONS[resource_type]:
|
|
171
|
+
extract_archive(local_filepath, working_path)
|
|
172
|
+
local_filename = self.search_resource_file(resource_filename, working_path, resource_type)
|
|
173
|
+
if local_filename is None:
|
|
174
|
+
raise ValueError(f"Resource filename {resource_filename} not found in {working_path}")
|
|
175
|
+
return local_filename, working_path
|
humalab/constants.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .bernoulli import Bernoulli
|
|
2
|
+
from .categorical import Categorical
|
|
3
|
+
from .discrete import Discrete
|
|
4
|
+
from .gaussian import Gaussian
|
|
5
|
+
from .log_uniform import LogUniform
|
|
6
|
+
from .truncated_gaussian import TruncatedGaussian
|
|
7
|
+
from .uniform import Uniform
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Bernoulli",
|
|
11
|
+
"Categorical",
|
|
12
|
+
"Discrete",
|
|
13
|
+
"LogUniform",
|
|
14
|
+
"Gaussian",
|
|
15
|
+
"TruncatedGaussian",
|
|
16
|
+
"Uniform",
|
|
17
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from humalab_sdk.dists.distribution import Distribution
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
class Bernoulli(Distribution):
|
|
7
|
+
def __init__(self,
|
|
8
|
+
generator: np.random.Generator,
|
|
9
|
+
p: float | Any,
|
|
10
|
+
size: int | tuple[int, ...] | None = None) -> None:
|
|
11
|
+
"""
|
|
12
|
+
Initialize the Bernoulli distribution.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
generator (np.random.Generator): The random number generator.
|
|
16
|
+
p (float | Any): The probability of success.
|
|
17
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
18
|
+
"""
|
|
19
|
+
super().__init__(generator=generator)
|
|
20
|
+
self._p = p
|
|
21
|
+
self._size = size
|
|
22
|
+
|
|
23
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
24
|
+
return self._generator.binomial(n=1, p=self._p, size=self._size)
|
|
25
|
+
|
|
26
|
+
def __repr__(self) -> str:
|
|
27
|
+
return f"Bernoulli(p={self._p}, size={self._size})"
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def create(generator: np.random.Generator,
|
|
31
|
+
p: float | Any,
|
|
32
|
+
size: int | tuple[int, ...] | None = None) -> 'Bernoulli':
|
|
33
|
+
"""
|
|
34
|
+
Create a Bernoulli distribution.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
generator (np.random.Generator): The random number generator.
|
|
38
|
+
p (float | Any): The probability of success.
|
|
39
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Bernoulli: The created Bernoulli distribution.
|
|
43
|
+
"""
|
|
44
|
+
return Bernoulli(generator=generator, p=p, size=size)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from humalab_sdk.dists.distribution import Distribution
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
class Categorical(Distribution):
|
|
6
|
+
def __init__(self,
|
|
7
|
+
generator: np.random.Generator,
|
|
8
|
+
choices: list,
|
|
9
|
+
weights: list[float] | None = None,
|
|
10
|
+
size: int | tuple[int, ...] | None = None) -> None:
|
|
11
|
+
"""
|
|
12
|
+
Initialize the categorical distribution.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
generator (np.random.Generator): The random number generator.
|
|
16
|
+
choices (list): The list of choices.
|
|
17
|
+
weights (list[float] | None): The weights for each choice.
|
|
18
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
19
|
+
"""
|
|
20
|
+
super().__init__(generator=generator)
|
|
21
|
+
self._choices = choices
|
|
22
|
+
self._size = size
|
|
23
|
+
self._weights = weights
|
|
24
|
+
|
|
25
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
26
|
+
return self._generator.choice(self._choices, size=self._size, p=self._weights)
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"Categorical(choices={self._choices}, size={self._size}, weights={self._weights})"
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def create(generator: np.random.Generator,
|
|
33
|
+
choices: list,
|
|
34
|
+
weights: list[float] | None = None,
|
|
35
|
+
size: int | tuple[int, ...] | None = None
|
|
36
|
+
) -> 'Categorical':
|
|
37
|
+
"""
|
|
38
|
+
Create a categorical distribution.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
generator (np.random.Generator): The random number generator.
|
|
42
|
+
choices (list): The list of choices.
|
|
43
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
44
|
+
weights (list[float] | None): The weights for each choice.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
Categorical: The created categorical distribution.
|
|
48
|
+
"""
|
|
49
|
+
return Categorical(generator=generator, choices=choices, size=size, weights=weights)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from humalab_sdk.dists.distribution import Distribution
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
class Discrete(Distribution):
|
|
7
|
+
def __init__(self,
|
|
8
|
+
generator: np.random.Generator,
|
|
9
|
+
low: int | Any,
|
|
10
|
+
high: int | Any,
|
|
11
|
+
endpoint: bool | None = None,
|
|
12
|
+
size: int | tuple[int, ...] | None = None,
|
|
13
|
+
) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Initialize the discrete distribution.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
generator (np.random.Generator): The random number generator.
|
|
19
|
+
low (int | Any): The lower bound (inclusive).
|
|
20
|
+
high (int | Any): The upper bound (exclusive).
|
|
21
|
+
endpoint (bool | None): Whether to include the endpoint.
|
|
22
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
23
|
+
"""
|
|
24
|
+
super().__init__(generator=generator)
|
|
25
|
+
self._low = np.array(low)
|
|
26
|
+
self._high = np.array(high)
|
|
27
|
+
self._size = size
|
|
28
|
+
self._endpoint = endpoint if endpoint is not None else True
|
|
29
|
+
|
|
30
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
31
|
+
return self._generator.integers(self._low, self._high, size=self._size, endpoint=self._endpoint)
|
|
32
|
+
|
|
33
|
+
def __repr__(self) -> str:
|
|
34
|
+
return f"Discrete(low={self._low}, high={self._high}, size={self._size}, endpoint={self._endpoint})"
|
|
35
|
+
|
|
36
|
+
@staticmethod
|
|
37
|
+
def create(generator: np.random.Generator,
|
|
38
|
+
low: int | Any,
|
|
39
|
+
high: int | Any,
|
|
40
|
+
endpoint: bool = True,
|
|
41
|
+
size: int | tuple[int, ...] | None = None,
|
|
42
|
+
) -> 'Discrete':
|
|
43
|
+
"""
|
|
44
|
+
Create a discrete distribution.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
generator (np.random.Generator): The random number generator.
|
|
48
|
+
low (int | Any): The lower bound (inclusive).
|
|
49
|
+
high (int | Any): The upper bound (exclusive).
|
|
50
|
+
endpoint (bool): Whether to include the endpoint.
|
|
51
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
Discrete: The created discrete distribution.
|
|
55
|
+
"""
|
|
56
|
+
return Discrete(generator=generator, low=low, high=high, size=size, endpoint=endpoint)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
class Distribution(ABC):
|
|
6
|
+
def __init__(self,
|
|
7
|
+
generator: np.random.Generator) -> None:
|
|
8
|
+
"""
|
|
9
|
+
Initialize the distribution.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
generator (np.random.Generator): The random number generator.
|
|
13
|
+
"""
|
|
14
|
+
super().__init__()
|
|
15
|
+
self._generator = generator
|
|
16
|
+
self._last_sample = None
|
|
17
|
+
|
|
18
|
+
def sample(self) -> int | float | np.ndarray:
|
|
19
|
+
"""
|
|
20
|
+
Sample from the distribution.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
int | float | np.ndarray: The sampled value(s).
|
|
24
|
+
"""
|
|
25
|
+
self._last_sample = self._sample()
|
|
26
|
+
return self._last_sample
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def last_sample(self) -> int | float | np.ndarray | None:
|
|
34
|
+
"""Get the last sampled value.
|
|
35
|
+
Returns:
|
|
36
|
+
int | float | np.ndarray | None: The last sampled value, or None if no sample has been taken yet.
|
|
37
|
+
"""
|
|
38
|
+
return self._last_sample
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from humalab_sdk.dists.distribution import Distribution
|
|
2
|
+
from typing import Any
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Gaussian(Distribution):
|
|
7
|
+
def __init__(self,
|
|
8
|
+
generator: np.random.Generator,
|
|
9
|
+
loc: float | Any,
|
|
10
|
+
scale: float | Any,
|
|
11
|
+
size: int | tuple[int, ...] | None = None) -> None:
|
|
12
|
+
"""
|
|
13
|
+
Initialize the Gaussian (normal) distribution.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
generator (np.random.Generator): The random number generator.
|
|
17
|
+
loc (float | Any): The mean of the distribution.
|
|
18
|
+
scale (float | Any): The standard deviation of the distribution.
|
|
19
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
20
|
+
"""
|
|
21
|
+
super().__init__(generator=generator)
|
|
22
|
+
self._loc = loc
|
|
23
|
+
self._scale = scale
|
|
24
|
+
self._size = size
|
|
25
|
+
|
|
26
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
27
|
+
return self._generator.normal(loc=self._loc, scale=self._scale, size=self._size)
|
|
28
|
+
|
|
29
|
+
def __repr__(self) -> str:
|
|
30
|
+
return f"Gaussian(loc={self._loc}, scale={self._scale}, size={self._size})"
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def create(generator: np.random.Generator,
|
|
34
|
+
loc: float | Any,
|
|
35
|
+
scale: float | Any,
|
|
36
|
+
size: int | tuple[int, ...] | None = None) -> 'Gaussian':
|
|
37
|
+
"""
|
|
38
|
+
Create a Gaussian (normal) distribution.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
generator (np.random.Generator): The random number generator.
|
|
42
|
+
loc (float | Any): The mean of the distribution.
|
|
43
|
+
scale (float | Any): The standard deviation of the distribution.
|
|
44
|
+
size (int | tuple[int, ...] | None): The size of the output.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
Gaussian: The created Gaussian distribution.
|
|
48
|
+
"""
|
|
49
|
+
return Gaussian(generator=generator, loc=loc, scale=scale, size=size)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from humalab_sdk.dists.distribution import Distribution
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
class LogUniform(Distribution):
|
|
7
|
+
def __init__(self,
|
|
8
|
+
generator: np.random.Generator,
|
|
9
|
+
low: float | Any,
|
|
10
|
+
high: float | Any,
|
|
11
|
+
size: int | tuple[int, ...]| None = None) -> None:
|
|
12
|
+
"""
|
|
13
|
+
Initialize the log-uniform distribution.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
generator (np.random.Generator): The random number generator.
|
|
17
|
+
low (float | Any): The lower bound (inclusive).
|
|
18
|
+
high (float | Any): The upper bound (exclusive).
|
|
19
|
+
size (int | tuple[int, ...]| None): The size of the output.
|
|
20
|
+
"""
|
|
21
|
+
super().__init__(generator=generator)
|
|
22
|
+
self._log_low = np.log(np.array(low))
|
|
23
|
+
self._log_high = np.log(np.array(high))
|
|
24
|
+
self._size = size
|
|
25
|
+
|
|
26
|
+
def _sample(self) -> int | float | np.ndarray:
|
|
27
|
+
return np.exp(self._generator.uniform(self._log_low, self._log_high, size=self._size))
|
|
28
|
+
|
|
29
|
+
def __repr__(self) -> str:
|
|
30
|
+
return f"LogUniform(low={np.exp(self._log_low)}, high={np.exp(self._log_high)}, size={self._size})"
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def create(generator: np.random.Generator,
|
|
34
|
+
low: float | Any,
|
|
35
|
+
high: float | Any,
|
|
36
|
+
size: int | tuple[int, ...]| None = None) -> 'LogUniform':
|
|
37
|
+
"""
|
|
38
|
+
Create a log-uniform distribution.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
generator (np.random.Generator): The random number generator.
|
|
42
|
+
low (float | Any): The lower bound (inclusive).
|
|
43
|
+
high (float | Any): The upper bound (exclusive).
|
|
44
|
+
size (int | tuple[int, ...]| None): The size of the output.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
LogUniform: The created log-uniform distribution.
|
|
48
|
+
"""
|
|
49
|
+
return LogUniform(generator=generator, low=low, high=high, size=size)
|