Modal-Decomposition 0.5.1__cp313-cp313-win_amd64.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.
- Modal_Decomposition/Base/CPU.py +73 -0
- Modal_Decomposition/Base/Cache.py +432 -0
- Modal_Decomposition/Base/Chunk.py +373 -0
- Modal_Decomposition/Base/Memory.py +356 -0
- Modal_Decomposition/Base/Seed.py +109 -0
- Modal_Decomposition/Base/__init__.py +42 -0
- Modal_Decomposition/CEEFD.py +321 -0
- Modal_Decomposition/CEEMD.py +367 -0
- Modal_Decomposition/CEEMDAN.py +577 -0
- Modal_Decomposition/Define/ClassDefine.py +180 -0
- Modal_Decomposition/Define/ConfigDefine.py +48 -0
- Modal_Decomposition/Define/ConstDefine.py +149 -0
- Modal_Decomposition/Define/PathDefine.py +10 -0
- Modal_Decomposition/Define/TextDefine.py +45 -0
- Modal_Decomposition/Define/__init__.py +18 -0
- Modal_Decomposition/EEMD.py +348 -0
- Modal_Decomposition/EFD.py +202 -0
- Modal_Decomposition/EMD.py +442 -0
- Modal_Decomposition/EWT.py +1322 -0
- Modal_Decomposition/Error/__init__.py +15 -0
- Modal_Decomposition/FMD.py +625 -0
- Modal_Decomposition/ICEEMDAN.py +598 -0
- Modal_Decomposition/LMD.py +557 -0
- Modal_Decomposition/MEMD.py +430 -0
- Modal_Decomposition/Operator/Daubechies_polynomial.py +29 -0
- Modal_Decomposition/Operator/Empirical_wavelet.py +36 -0
- Modal_Decomposition/Operator/__init__.py +2 -0
- Modal_Decomposition/RPSEMD.py +504 -0
- Modal_Decomposition/SSA.py +566 -0
- Modal_Decomposition/SVMD.py +278 -0
- Modal_Decomposition/Utils/Check.py +555 -0
- Modal_Decomposition/Utils/Envelope.py +152 -0
- Modal_Decomposition/Utils/Hilbert.py +48 -0
- Modal_Decomposition/Utils/Mirror.py +436 -0
- Modal_Decomposition/Utils/Monotonicity.py +309 -0
- Modal_Decomposition/Utils/Peaks.py +319 -0
- Modal_Decomposition/Utils/Poly.py +31 -0
- Modal_Decomposition/Utils/Slepian.py +441 -0
- Modal_Decomposition/Utils/_Hilbert/__init__.py +129 -0
- Modal_Decomposition/Utils/_Hilbert/_fft.py +105 -0
- Modal_Decomposition/Utils/_Hilbert/_fht.py +232 -0
- Modal_Decomposition/Utils/_Hilbert/_fht_native.cp313-win_amd64.pyd +0 -0
- Modal_Decomposition/Utils/_Hilbert/_fir.py +0 -0
- Modal_Decomposition/Utils/_Hilbert/_forth_order_wave.py +0 -0
- Modal_Decomposition/Utils/_Hilbert/_kramers_kronig.py +0 -0
- Modal_Decomposition/Utils/_Hilbert/_scipy_backend.py +8 -0
- Modal_Decomposition/Utils/_Hilbert/_wave.py +0 -0
- Modal_Decomposition/Utils/_Slepian/C.py +228 -0
- Modal_Decomposition/Utils/_Slepian/_C/_slepian_native.cp313-win_amd64.pyd +0 -0
- Modal_Decomposition/Utils/_Slepian/__init__.py +1 -0
- Modal_Decomposition/Utils/_Slepian/numpy_slepian.py +297 -0
- Modal_Decomposition/Utils/__init__.py +11 -0
- Modal_Decomposition/VMD.py +1136 -0
- Modal_Decomposition/__init__.py +146 -0
- modal_decomposition-0.5.1.dist-info/METADATA +361 -0
- modal_decomposition-0.5.1.dist-info/RECORD +59 -0
- modal_decomposition-0.5.1.dist-info/WHEEL +5 -0
- modal_decomposition-0.5.1.dist-info/licenses/LICENSE +202 -0
- modal_decomposition-0.5.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from ..Define import PYTHON_VERSION, DEFAULT_ALLOCABLE_CPU_RATIO
|
|
4
|
+
|
|
5
|
+
__all__ = ["cpu_num", "allocable_cpu_num", "total_cpu", "set_allocable"]
|
|
6
|
+
|
|
7
|
+
cpu_num = None
|
|
8
|
+
allocable_cpu_num = None
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def total_cpu() -> int:
|
|
12
|
+
"""
|
|
13
|
+
本机可用逻辑 CPU 数 (至少 1)
|
|
14
|
+
|
|
15
|
+
如版本 >= 3.13, 则使用 os.process_cpu_count, 否则 os.cpu_count()
|
|
16
|
+
"""
|
|
17
|
+
global cpu_num
|
|
18
|
+
if cpu_num is None:
|
|
19
|
+
if PYTHON_VERSION.major == 3 and PYTHON_VERSION.minor >= 13:
|
|
20
|
+
try:
|
|
21
|
+
cpu_num = os.process_cpu_count()
|
|
22
|
+
except Exception:
|
|
23
|
+
cpu_num = None
|
|
24
|
+
|
|
25
|
+
if cpu_num is None:
|
|
26
|
+
cpu_num = os.cpu_count()
|
|
27
|
+
|
|
28
|
+
return cpu_num
|
|
29
|
+
|
|
30
|
+
def set_allocable(value: int | float) -> int:
|
|
31
|
+
"""
|
|
32
|
+
set allocable_cpu_num.
|
|
33
|
+
int means cpu num, [1, total];
|
|
34
|
+
float means cpu ratio, (0, 1];
|
|
35
|
+
-1 means all.
|
|
36
|
+
:param value:
|
|
37
|
+
:return:
|
|
38
|
+
"""
|
|
39
|
+
global cpu_num, allocable_cpu_num
|
|
40
|
+
|
|
41
|
+
if isinstance(value, bool):
|
|
42
|
+
raise TypeError(f"value must be int or float, got {value!r}")
|
|
43
|
+
|
|
44
|
+
if isinstance(value, int):
|
|
45
|
+
# 整数是绝对核数:取值 0 < value <= cpu_num;-1 是"全部"哨兵,等价于 cpu_num。
|
|
46
|
+
if value == -1:
|
|
47
|
+
allocable_cpu_num = cpu_num
|
|
48
|
+
return allocable_cpu_num
|
|
49
|
+
|
|
50
|
+
if value <= 0 or value > cpu_num:
|
|
51
|
+
raise ValueError(f"num of value must in (0, {cpu_num})]")
|
|
52
|
+
|
|
53
|
+
allocable_cpu_num = value
|
|
54
|
+
return allocable_cpu_num
|
|
55
|
+
|
|
56
|
+
if isinstance(value, float):
|
|
57
|
+
if not (0.0 < value <= 1.0):
|
|
58
|
+
raise ValueError(f"ratio of value must in (0, 1], got {value!r}")
|
|
59
|
+
|
|
60
|
+
allocable_cpu_num = int(cpu_num * value)
|
|
61
|
+
if allocable_cpu_num < 1:
|
|
62
|
+
allocable_cpu_num = 1
|
|
63
|
+
|
|
64
|
+
allocable_cpu_num = allocable_cpu_num
|
|
65
|
+
return allocable_cpu_num
|
|
66
|
+
|
|
67
|
+
raise TypeError(f"value must be int or float, got {type(value)!r}")
|
|
68
|
+
|
|
69
|
+
if cpu_num is None:
|
|
70
|
+
total_cpu()
|
|
71
|
+
|
|
72
|
+
if allocable_cpu_num is None:
|
|
73
|
+
allocable_cpu_num = set_allocable(DEFAULT_ALLOCABLE_CPU_RATIO)
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""
|
|
2
|
+
第三方子模块的 import 缓存 (进程级注册表)。
|
|
3
|
+
|
|
4
|
+
进程级、线程安全的注册表, 存放已导入的第三方子模块 (如 ``scipy.signal`` /
|
|
5
|
+
``scipy.interpolate``)。同一进程内每个模块至多 import 一次, 之后所有使用方
|
|
6
|
+
都经 :meth:`cache.get` 取用同一实例。
|
|
7
|
+
|
|
8
|
+
唯一性契约
|
|
9
|
+
----------
|
|
10
|
+
- 键是**区分大小写、非空**的 str (推荐模块式名字, 如 ``"scipy.signal"``);
|
|
11
|
+
``""``、纯空白和非 str 名字在入口处即被拒绝。
|
|
12
|
+
- :meth:`cache.add` **永不覆盖**: 注册已存在的名字返回 ``False`` 并保留原 api;
|
|
13
|
+
替换只能先显式 :meth:`cache.remove` 再 :meth:`cache.add`。
|
|
14
|
+
- 存储是类属性, 由类和所有实例共享, 因此唯一性保证是进程级的, 与谁注册无关。
|
|
15
|
+
- 每个条目带一条描述串 (见 :meth:`cache.describe`); 注册时不给就用自动生成的说明。
|
|
16
|
+
|
|
17
|
+
线程安全
|
|
18
|
+
--------
|
|
19
|
+
所有读写都在一把可重入锁内, 因此并发注册不同名字安全, 并发注册同名恰好成功一次。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import functools
|
|
23
|
+
import threading
|
|
24
|
+
import types
|
|
25
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
26
|
+
|
|
27
|
+
__all__ = ["Cache", "cache"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class cache:
|
|
31
|
+
"""
|
|
32
|
+
Import cache: 已导入模块的唯一名字注册表。
|
|
33
|
+
|
|
34
|
+
公开 API 以 classmethod 实现, 两种写法等价且共享同一份进程级存储::
|
|
35
|
+
|
|
36
|
+
cache.add("scipy.signal", scipy.signal) # 类上直接调用
|
|
37
|
+
cache().add("scipy.signal", scipy.signal) # 经实例调用
|
|
38
|
+
|
|
39
|
+
共享状态 (类属性, 实例也读写同一份)
|
|
40
|
+
----------------------------------
|
|
41
|
+
``_entries``: ``{name: api}``; ``_descriptions``: ``{name: description}``,
|
|
42
|
+
与 ``_entries`` 同步增删; ``_exists``: 记录 import 失败过的名字, 用作负缓存
|
|
43
|
+
(进程内不再重试); ``_lock``: 保护全部读写的 ``RLock``。
|
|
44
|
+
|
|
45
|
+
Examples
|
|
46
|
+
--------
|
|
47
|
+
>>> from Modal_Decomposition.Base.Cache import cache
|
|
48
|
+
>>> import scipy.signal as ss
|
|
49
|
+
>>> cache.add("scipy.signal", ss, description="signal processing submodule")
|
|
50
|
+
True
|
|
51
|
+
>>> cache.check("scipy.signal")
|
|
52
|
+
True
|
|
53
|
+
>>> cache.get("scipy.signal") is ss
|
|
54
|
+
True
|
|
55
|
+
>>> cache.describe("scipy.signal")
|
|
56
|
+
'signal processing submodule'
|
|
57
|
+
>>> cache.add("scipy.signal", ss) # 重复注册: 永不覆盖
|
|
58
|
+
False
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
# --- 进程级共享状态: 类属性, 实例也读写同一份 ---
|
|
62
|
+
_entries: Dict[str, Any] = {}
|
|
63
|
+
_exists: Dict[str, bool] = {}
|
|
64
|
+
_descriptions: Dict[str, str] = {}
|
|
65
|
+
_lock = threading.RLock()
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def _validate_name(name) -> str:
|
|
69
|
+
"""
|
|
70
|
+
校验注册键。
|
|
71
|
+
|
|
72
|
+
名字按原样保留 (精确字符串、区分大小写), 只拒绝极端情况后返回。
|
|
73
|
+
|
|
74
|
+
Raises
|
|
75
|
+
------
|
|
76
|
+
TypeError
|
|
77
|
+
名字不是 str (None、int、bytes 等)。
|
|
78
|
+
ValueError
|
|
79
|
+
名字为空或纯空白。
|
|
80
|
+
"""
|
|
81
|
+
if not isinstance(name, str):
|
|
82
|
+
raise TypeError(
|
|
83
|
+
f"cache name must be a str, got {type(name).__name__}"
|
|
84
|
+
)
|
|
85
|
+
if not name.strip():
|
|
86
|
+
raise ValueError("cache name must not be empty or whitespace")
|
|
87
|
+
return name
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
def _validate_api(api) -> None:
|
|
91
|
+
"""拒绝 None api: 缓存 None 与"条目缺失"无法区分。"""
|
|
92
|
+
if api is None:
|
|
93
|
+
raise TypeError("cache api must not be None")
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def _validate_description(description: Optional[str]) -> Optional[str]:
|
|
97
|
+
"""描述必须是 str 或 None; 空串 / 纯空白等价于 None。"""
|
|
98
|
+
if description is None:
|
|
99
|
+
return None
|
|
100
|
+
if not isinstance(description, str):
|
|
101
|
+
raise TypeError(
|
|
102
|
+
f"cache description must be a str or None, "
|
|
103
|
+
f"got {type(description).__name__}"
|
|
104
|
+
)
|
|
105
|
+
stripped = description.strip()
|
|
106
|
+
return stripped if stripped else None
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _api_label(api) -> str:
|
|
110
|
+
"""缓存对象的人类可读标签 (模块名或类型名)。"""
|
|
111
|
+
if isinstance(api, types.ModuleType):
|
|
112
|
+
return getattr(api, "__name__", str(api))
|
|
113
|
+
return f"{type(api).__module__}.{type(api).__qualname__}"
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def get(cls, name):
|
|
117
|
+
"""
|
|
118
|
+
取回已缓存的 api。
|
|
119
|
+
|
|
120
|
+
Raises
|
|
121
|
+
------
|
|
122
|
+
KeyError
|
|
123
|
+
``name`` 未注册; 错误信息里带上已注册的键。
|
|
124
|
+
"""
|
|
125
|
+
name = cls._validate_name(name)
|
|
126
|
+
with cls._lock:
|
|
127
|
+
if name not in cls._entries:
|
|
128
|
+
raise KeyError(
|
|
129
|
+
f"'{name}' is not registered in the cache; "
|
|
130
|
+
f"registered entries: {sorted(cls._entries)}"
|
|
131
|
+
)
|
|
132
|
+
return cls._entries[name]
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def add(
|
|
136
|
+
cls,
|
|
137
|
+
name,
|
|
138
|
+
api,
|
|
139
|
+
verbose: bool = False,
|
|
140
|
+
description: Optional[str] = None,
|
|
141
|
+
) -> bool:
|
|
142
|
+
"""
|
|
143
|
+
把模块 / 函数 / 类的 api 注册进缓存。
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
name : str
|
|
148
|
+
唯一注册键 (区分大小写, 非空)。
|
|
149
|
+
api : object
|
|
150
|
+
要缓存的已导入对象 (通常是模块); 不能是 None。
|
|
151
|
+
verbose : bool
|
|
152
|
+
为 True 时打印每条新注册与每次被拒的重复注册。
|
|
153
|
+
description : str, optional
|
|
154
|
+
该模块的一行描述, 之后用 :meth:`cache.describe` 取回; 省略时用自动
|
|
155
|
+
生成的说明。
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
bool
|
|
160
|
+
注册成功为 True; ``name`` 已注册时为 False (既有 api 原样保留)。
|
|
161
|
+
"""
|
|
162
|
+
name = cls._validate_name(name)
|
|
163
|
+
cls._validate_api(api)
|
|
164
|
+
description = cls._validate_description(description)
|
|
165
|
+
|
|
166
|
+
with cls._lock:
|
|
167
|
+
if name in cls._entries:
|
|
168
|
+
if verbose:
|
|
169
|
+
print(
|
|
170
|
+
f"[cache] '{name}' is already registered; "
|
|
171
|
+
f"duplicate registration ignored"
|
|
172
|
+
)
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
cls._entries[name] = api
|
|
176
|
+
cls._descriptions[name] = description if description is not None \
|
|
177
|
+
else f"<no description provided at registration of '{name}'>"
|
|
178
|
+
|
|
179
|
+
if verbose:
|
|
180
|
+
print(f"[cache] registered '{name}' ({cls._api_label(api)})")
|
|
181
|
+
return True
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def import_module(
|
|
185
|
+
cls,
|
|
186
|
+
name: str,
|
|
187
|
+
description: Optional[str] = None,
|
|
188
|
+
verbose: bool = False,
|
|
189
|
+
):
|
|
190
|
+
"""
|
|
191
|
+
抽象并集中管理经典惰性导入样板::
|
|
192
|
+
|
|
193
|
+
if <flag> is None:
|
|
194
|
+
try:
|
|
195
|
+
import <name> as <flag>
|
|
196
|
+
except ImportError:
|
|
197
|
+
raise ImportError(...)
|
|
198
|
+
|
|
199
|
+
- 首次调用: import 目标模块, 以模块名 ``name`` 注册进统一缓存 (持 ``RLock``, 恰好执行一次);
|
|
200
|
+
- 之后调用: 直接返回缓存实例, 不再执行 import;
|
|
201
|
+
- 导入失败: 名字记进 ``_exists`` 作负缓存, 返回 ``None`` (``verbose=True`` 时改抛
|
|
202
|
+
``ImportError``); 同一进程内不再重试, 不假设运行期会动态 pip install;
|
|
203
|
+
- 键已存在时 (可能由另一条 import 路径先注册) 直接返回既有实例, 维持"永不覆盖"契约。
|
|
204
|
+
|
|
205
|
+
Parameters
|
|
206
|
+
----------
|
|
207
|
+
name : str
|
|
208
|
+
要 import 的模块名, 同时作注册键 (sys.modules 风格, 区分大小写, 非空)。
|
|
209
|
+
description : str, optional
|
|
210
|
+
存入缓存、供 :meth:`cache.describe` 取回的一行描述。
|
|
211
|
+
verbose : bool
|
|
212
|
+
模块导入失败时抛 ``ImportError``; 为 False 时返回 ``None``。
|
|
213
|
+
|
|
214
|
+
Returns
|
|
215
|
+
-------
|
|
216
|
+
module | None
|
|
217
|
+
已 import 并注册的模块实例; 模块不存在且 ``verbose=False`` 时为 ``None``。
|
|
218
|
+
"""
|
|
219
|
+
# --- 快路径: 已缓存 (正命中) 或已知不存在 (负命中) ---
|
|
220
|
+
# 命中时只做一次 dict 查找: 名字在写入缓存时已经校验过, 不必重复校验; CPython 下
|
|
221
|
+
# dict 读受 GIL 保护是原子的, "只读命中"也不需要取锁。实测命中路径 315 ns -> ~110 ns
|
|
222
|
+
# (省掉 _validate_name ~45 + _validate_description ~25 + RLock ~55; 55 是省掉的开销,
|
|
223
|
+
# 不是端到端耗时 —— 端到端还含 ~25 ns 的 bound-method 与调用开销)。
|
|
224
|
+
# 并发安全性: 两个线程同时未命中会一起进慢路径, 由 _lock 保证"恰好执行一次";
|
|
225
|
+
# 这里的无锁读只读不写, 不会破坏"永不覆盖"契约。
|
|
226
|
+
entries = cls._entries
|
|
227
|
+
if type(name) is str: # str 子类留给慢路径走完整校验
|
|
228
|
+
api = entries.get(name)
|
|
229
|
+
if api is not None:
|
|
230
|
+
return api
|
|
231
|
+
if name in cls._exists:
|
|
232
|
+
if verbose:
|
|
233
|
+
raise ImportError(f"the {name} module is not pip!")
|
|
234
|
+
return None
|
|
235
|
+
|
|
236
|
+
# --- 慢路径: 首次导入 / 非法参数 ---
|
|
237
|
+
name = cls._validate_name(name)
|
|
238
|
+
description = cls._validate_description(description)
|
|
239
|
+
|
|
240
|
+
with cls._lock:
|
|
241
|
+
if name in cls._entries:
|
|
242
|
+
return cls._entries[name]
|
|
243
|
+
|
|
244
|
+
if name not in cls._exists:
|
|
245
|
+
from importlib import import_module as _import_module
|
|
246
|
+
try:
|
|
247
|
+
api = _import_module(name) # ImportError 原样传播, 不写入缓存
|
|
248
|
+
except ImportError:
|
|
249
|
+
cls._exists[name] = False
|
|
250
|
+
api = None
|
|
251
|
+
else:
|
|
252
|
+
api = None
|
|
253
|
+
|
|
254
|
+
if api is not None:
|
|
255
|
+
cls._entries[name] = api
|
|
256
|
+
cls._descriptions[name] = (
|
|
257
|
+
description if description is not None
|
|
258
|
+
else f"<imported module '{name}'>"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
if verbose and api is None:
|
|
262
|
+
raise ImportError(f"the {name} module is not pip!")
|
|
263
|
+
|
|
264
|
+
return api
|
|
265
|
+
|
|
266
|
+
@classmethod
|
|
267
|
+
def lazy(cls, name: str, description: Optional[str] = None, verbose: bool = False):
|
|
268
|
+
"""
|
|
269
|
+
装饰器: 把零参加载函数变成"进程内恰好执行一次"的惰性取用器。
|
|
270
|
+
|
|
271
|
+
对调用方完全透明 (``functools.wraps`` 保留签名与 docstring), 缓存藏在背后: 调用者只看到一个普通函数调用。
|
|
272
|
+
|
|
273
|
+
- 首次调用: 持 ``RLock`` 执行原函数, 结果以 ``name`` 注册进缓存并返回;
|
|
274
|
+
- 之后调用: 返回缓存实例, 原函数不再执行;
|
|
275
|
+
- 原函数抛异常: 原样传播且不缓存, 下次调用可重试;
|
|
276
|
+
- 键已存在: 不执行原函数, 返回既有实例 (永不覆盖);
|
|
277
|
+
- 带参调用或原函数返回 ``None``: 抛 ``TypeError``。
|
|
278
|
+
|
|
279
|
+
Parameters
|
|
280
|
+
----------
|
|
281
|
+
name : str
|
|
282
|
+
Unique registry key (case-sensitive, non-empty).
|
|
283
|
+
description : str, optional
|
|
284
|
+
One-line description stored for :meth:`cache.describe`.
|
|
285
|
+
verbose : bool
|
|
286
|
+
Print a line when the entry is newly registered.
|
|
287
|
+
"""
|
|
288
|
+
name = cls._validate_name(name)
|
|
289
|
+
description = cls._validate_description(description)
|
|
290
|
+
|
|
291
|
+
def dec(fn):
|
|
292
|
+
@functools.wraps(fn)
|
|
293
|
+
def wrapper(*args, **kwargs):
|
|
294
|
+
if args or kwargs:
|
|
295
|
+
raise TypeError(
|
|
296
|
+
f"cache.lazy loader {fn.__qualname__!r} takes no "
|
|
297
|
+
f"arguments (got {len(args)} positional, "
|
|
298
|
+
f"{sorted(kwargs)} keyword)"
|
|
299
|
+
)
|
|
300
|
+
with cls._lock:
|
|
301
|
+
if name in cls._entries:
|
|
302
|
+
return cls._entries[name]
|
|
303
|
+
api = fn()
|
|
304
|
+
cls._validate_api(api)
|
|
305
|
+
cls._entries[name] = api
|
|
306
|
+
cls._descriptions[name] = (
|
|
307
|
+
description if description is not None
|
|
308
|
+
else f"<lazy '{name}' via {fn.__qualname__}>"
|
|
309
|
+
)
|
|
310
|
+
if verbose:
|
|
311
|
+
print(
|
|
312
|
+
f"[cache] registered '{name}' "
|
|
313
|
+
f"via lazy loader {fn.__qualname__} "
|
|
314
|
+
f"({cls._api_label(api)})"
|
|
315
|
+
)
|
|
316
|
+
return api
|
|
317
|
+
|
|
318
|
+
return wrapper
|
|
319
|
+
|
|
320
|
+
return dec
|
|
321
|
+
|
|
322
|
+
@classmethod
|
|
323
|
+
def check(cls, name) -> bool:
|
|
324
|
+
"""
|
|
325
|
+
查询 ``name`` 是否已注册。
|
|
326
|
+
|
|
327
|
+
Returns
|
|
328
|
+
-------
|
|
329
|
+
bool
|
|
330
|
+
已注册为 True, 否则 False。
|
|
331
|
+
"""
|
|
332
|
+
name = cls._validate_name(name)
|
|
333
|
+
with cls._lock:
|
|
334
|
+
return name in cls._entries
|
|
335
|
+
|
|
336
|
+
@classmethod
|
|
337
|
+
def describe(cls, name) -> str:
|
|
338
|
+
"""
|
|
339
|
+
返回已注册条目的描述。
|
|
340
|
+
|
|
341
|
+
注册时显式给出的 ``description`` 原样返回; 未给出时返回注册时自动生成的
|
|
342
|
+
说明 (如 ``<imported module 'x'>``)。
|
|
343
|
+
|
|
344
|
+
Raises
|
|
345
|
+
------
|
|
346
|
+
KeyError
|
|
347
|
+
``name`` 未注册。
|
|
348
|
+
"""
|
|
349
|
+
name = cls._validate_name(name)
|
|
350
|
+
with cls._lock:
|
|
351
|
+
if name not in cls._descriptions:
|
|
352
|
+
raise KeyError(
|
|
353
|
+
f"'{name}' is not registered in the cache; "
|
|
354
|
+
f"registered entries: {sorted(cls._entries)}"
|
|
355
|
+
)
|
|
356
|
+
return cls._descriptions[name]
|
|
357
|
+
|
|
358
|
+
@classmethod
|
|
359
|
+
def remove(cls, name) -> bool:
|
|
360
|
+
"""
|
|
361
|
+
删除一个条目 (api 与描述) 并返回它原先是否存在。
|
|
362
|
+
|
|
363
|
+
删除是唯一能为"替换注册"腾出位置的途径。
|
|
364
|
+
"""
|
|
365
|
+
name = cls._validate_name(name)
|
|
366
|
+
with cls._lock:
|
|
367
|
+
existed = name in cls._entries
|
|
368
|
+
cls._entries.pop(name, None)
|
|
369
|
+
cls._descriptions.pop(name, None)
|
|
370
|
+
cls._exists.pop(name, None)
|
|
371
|
+
return existed
|
|
372
|
+
|
|
373
|
+
@classmethod
|
|
374
|
+
def clear(cls) -> None:
|
|
375
|
+
"""清空所有已注册条目。"""
|
|
376
|
+
with cls._lock:
|
|
377
|
+
cls._entries.clear()
|
|
378
|
+
cls._descriptions.clear()
|
|
379
|
+
cls._exists.clear()
|
|
380
|
+
|
|
381
|
+
@classmethod
|
|
382
|
+
def names(cls) -> List[str]:
|
|
383
|
+
"""已注册键的升序列表。"""
|
|
384
|
+
with cls._lock:
|
|
385
|
+
return sorted(cls._entries)
|
|
386
|
+
|
|
387
|
+
@classmethod
|
|
388
|
+
def keys(cls) -> List[str]:
|
|
389
|
+
"""``names`` 的别名。"""
|
|
390
|
+
return cls.names()
|
|
391
|
+
|
|
392
|
+
@classmethod
|
|
393
|
+
def values(cls) -> List[Any]:
|
|
394
|
+
"""已缓存 api 的列表, 按键升序。"""
|
|
395
|
+
with cls._lock:
|
|
396
|
+
return [cls._entries[k] for k in sorted(cls._entries)]
|
|
397
|
+
|
|
398
|
+
@classmethod
|
|
399
|
+
def items(cls) -> List[Tuple[str, Any]]:
|
|
400
|
+
"""``(name, api)`` 对的列表, 按键升序。"""
|
|
401
|
+
with cls._lock:
|
|
402
|
+
return [(k, cls._entries[k]) for k in sorted(cls._entries)]
|
|
403
|
+
|
|
404
|
+
@classmethod
|
|
405
|
+
def descriptions(cls) -> Dict[str, str]:
|
|
406
|
+
"""``{name: description}`` 的快照 dict。"""
|
|
407
|
+
with cls._lock:
|
|
408
|
+
return dict(cls._descriptions)
|
|
409
|
+
|
|
410
|
+
# ------------------------------------------------------------------ #
|
|
411
|
+
# 便捷协议 (实例级: len(cache())、'x' in cache()、cache()['x'])
|
|
412
|
+
# ------------------------------------------------------------------ #
|
|
413
|
+
def __contains__(self, name) -> bool:
|
|
414
|
+
return self.check(name)
|
|
415
|
+
|
|
416
|
+
def __len__(self) -> int:
|
|
417
|
+
with self._lock:
|
|
418
|
+
return len(self._entries)
|
|
419
|
+
|
|
420
|
+
def __getitem__(self, name):
|
|
421
|
+
return self.get(name)
|
|
422
|
+
|
|
423
|
+
def __repr__(self) -> str:
|
|
424
|
+
with self._lock:
|
|
425
|
+
return (
|
|
426
|
+
f"<cache entries={sorted(self._entries)} "
|
|
427
|
+
f"n={len(self._entries)}>"
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# 首字母大写别名: 与 Base 包其余类(Config / Decomposer)风格一致。
|
|
432
|
+
Cache = cache
|