-
Notifications
You must be signed in to change notification settings - Fork 609
Expand file tree
/
Copy pathpath.py
More file actions
491 lines (404 loc) · 12.7 KB
/
path.py
File metadata and controls
491 lines (404 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# SPDX-License-Identifier: LGPL-3.0-or-later
import itertools
import os
from abc import (
ABC,
abstractmethod,
)
from functools import (
lru_cache,
)
from pathlib import (
Path,
)
from typing import (
Any,
ClassVar,
)
import h5py
import numpy as np
from typing_extensions import (
Self,
)
from wcmatch.glob import (
globfilter,
)
class DPPath(ABC):
"""The path class to data system (DeepmdData).
Parameters
----------
path : str
path
mode : str, optional
mode, by default "r"
"""
def __new__(cls, path: str, mode: str = "r") -> Self:
if cls is DPPath:
if os.path.isdir(path):
return super().__new__(DPOSPath)
elif os.path.isfile(path.split("#")[0]):
# assume h5 if it is not dir
return super().__new__(DPH5Path)
raise FileNotFoundError(f"{path} not found")
return super().__new__(cls)
@abstractmethod
def load_numpy(self) -> np.ndarray:
"""Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array
"""
@abstractmethod
def load_txt(self, **kwargs: Any) -> np.ndarray:
"""Load NumPy array from text.
Returns
-------
np.ndarray
loaded NumPy array
"""
@abstractmethod
def save_numpy(self, arr: np.ndarray) -> None:
"""Save NumPy array.
Parameters
----------
arr : np.ndarray
NumPy array
"""
@abstractmethod
def glob(self, pattern: str) -> list["DPPath"]:
"""Search path using the glob pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
@abstractmethod
def rglob(self, pattern: str) -> list["DPPath"]:
"""This is like calling :meth:`DPPath.glob()` with `**/` added in front
of the given relative pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
@abstractmethod
def is_file(self) -> bool:
"""Check if self is file."""
@abstractmethod
def is_dir(self) -> bool:
"""Check if self is directory."""
@abstractmethod
def __getnewargs__(self) -> tuple[str, str]:
"""Return the arguments to be passed to __new__ when unpickling an instance."""
@abstractmethod
def __truediv__(self, key: str) -> "DPPath":
"""Used for / operator."""
@abstractmethod
def __lt__(self, other: "DPPath") -> bool:
"""Whether this DPPath is less than other for sorting."""
@abstractmethod
def __str__(self) -> str:
"""Represent string."""
def __repr__(self) -> str:
return f"{type(self)} ({self!s})"
def __eq__(self, other: object) -> bool:
return str(self) == str(other)
def __hash__(self) -> int:
return hash(str(self))
@property
@abstractmethod
def name(self) -> str:
"""Name of the path."""
@abstractmethod
def mkdir(self, parents: bool = False, exist_ok: bool = False) -> None:
"""Make directory.
Parameters
----------
parents : bool, optional
If true, any missing parents of this directory are created as well.
exist_ok : bool, optional
If true, no error will be raised if the target directory already exists.
"""
class DPOSPath(DPPath):
"""The OS path class to data system (DeepmdData) for real directories.
Parameters
----------
path : Union[str, Path]
path
mode : str, optional
mode, by default "r"
"""
def __init__(self, path: str | Path, mode: str = "r") -> None:
super().__init__()
self.mode = mode
self.path = Path(path)
def __getnewargs__(self) -> tuple[str, str]:
return (self.path, self.mode)
def load_numpy(self) -> np.ndarray:
"""Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array
"""
return np.load(str(self.path))
def load_txt(self, **kwargs: Any) -> np.ndarray:
"""Load NumPy array from text.
Returns
-------
np.ndarray
loaded NumPy array
"""
return np.loadtxt(str(self.path), **kwargs)
def save_numpy(self, arr: np.ndarray) -> None:
"""Save NumPy array.
Parameters
----------
arr : np.ndarray
NumPy array
"""
if self.mode == "r":
raise ValueError("Cannot save to read-only path")
with self.path.open("wb") as f:
np.save(f, arr)
def glob(self, pattern: str) -> list["DPPath"]:
"""Search path using the glob pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
# currently DPOSPath will only derivative DPOSPath
return [type(self)(p, mode=self.mode) for p in self.path.glob(pattern)]
def rglob(self, pattern: str) -> list["DPPath"]:
"""This is like calling :meth:`DPPath.glob()` with `**/` added in front
of the given relative pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
return [type(self)(p, mode=self.mode) for p in self.path.rglob(pattern)]
def is_file(self) -> bool:
"""Check if self is file."""
return self.path.is_file()
def is_dir(self) -> bool:
"""Check if self is directory."""
return self.path.is_dir()
def __truediv__(self, key: str) -> "DPPath":
"""Used for / operator."""
return type(self)(self.path / key, mode=self.mode)
def __lt__(self, other: "DPOSPath") -> bool:
"""Whether this DPPath is less than other for sorting."""
return self.path < other.path
def __str__(self) -> str:
"""Represent string."""
return str(self.path)
@property
def name(self) -> str:
"""Name of the path."""
return self.path.name
def mkdir(self, parents: bool = False, exist_ok: bool = False) -> None:
"""Make directory.
Parameters
----------
parents : bool, optional
If true, any missing parents of this directory are created as well.
exist_ok : bool, optional
If true, no error will be raised if the target directory already exists.
"""
if self.mode == "r":
raise ValueError("Cannot mkdir to read-only path")
self.path.mkdir(parents=parents, exist_ok=exist_ok)
class DPH5Path(DPPath):
"""The path class to data system (DeepmdData) for HDF5 files.
Notes
-----
OS - HDF5 relationship:
directory - Group
file - Dataset
Parameters
----------
path : str
path
mode : str, optional
mode, by default "r"
"""
def __init__(self, path: str, mode: str = "r") -> None:
super().__init__()
self.mode = mode
# we use "#" to split path
# so we do not support file names containing #...
s = path.split("#")
self.root_path = s[0]
if not os.path.isfile(self.root_path):
raise FileNotFoundError(f"{self.root_path} not found")
self.root = self._load_h5py(s[0], mode)
# h5 path: default is the root path
self._name = s[1] if len(s) > 1 else "/"
def __getnewargs__(self) -> tuple[str, str]:
return (self.root_path, self.mode)
@classmethod
@lru_cache(None)
def _load_h5py(cls, path: str, mode: str = "r") -> h5py.File:
"""Load hdf5 file.
Parameters
----------
path : str
path to hdf5 file
mode : str, optional
mode, by default 'r'
"""
# this method has cache to avoid duplicated
# loading from different DPH5Path
# However the file will be never closed?
return h5py.File(path, mode)
def load_numpy(self) -> np.ndarray:
"""Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array
"""
return self.root[self._name][:]
def load_txt(self, dtype: np.dtype | None = None, **kwargs: Any) -> np.ndarray:
"""Load NumPy array from text.
Returns
-------
np.ndarray
loaded NumPy array
"""
arr = self.load_numpy()
if dtype:
arr = arr.astype(dtype)
return arr
def save_numpy(self, arr: np.ndarray) -> None:
"""Save NumPy array.
Parameters
----------
arr : np.ndarray
NumPy array
"""
if self._name in self._keys:
del self.root[self._name]
self.root.create_dataset(self._name, data=arr)
self.root.flush()
self._new_keys.append(self._name)
def glob(self, pattern: str) -> list["DPPath"]:
"""Search path using the glob pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
# got paths starts with current path first, which is faster
subpaths = [
ii
for ii in itertools.chain(self._keys, self._new_keys)
if ii.startswith(self._name)
]
return [
type(self)(f"{self.root_path}#{pp}", mode=self.mode)
for pp in globfilter(subpaths, self._connect_path(pattern))
]
def rglob(self, pattern: str) -> list["DPPath"]:
"""This is like calling :meth:`DPPath.glob()` with `**/` added in front
of the given relative pattern.
Parameters
----------
pattern : str
glob pattern
Returns
-------
list[DPPath]
list of paths
"""
return self.glob("**" + pattern)
@property
def _keys(self) -> list[str]:
"""Walk all groups and dataset."""
return self._file_keys(self.root)
__file_new_keys: ClassVar[dict[h5py.File, list[str]]] = {}
@property
def _new_keys(self) -> list[str]:
"""New keys that haven't been cached."""
self.__file_new_keys.setdefault(self.root, [])
return self.__file_new_keys[self.root]
@classmethod
@lru_cache(None)
def _file_keys(cls, file: h5py.File) -> list[str]:
"""Walk all groups and dataset."""
l = []
file.visit(lambda x: l.append("/" + x))
return l
def is_file(self) -> bool:
"""Check if self is file."""
if self._name not in self._keys and self._name not in self._new_keys:
return False
return isinstance(self.root[self._name], h5py.Dataset)
def is_dir(self) -> bool:
"""Check if self is directory."""
if self._name == "/":
return True
if self._name not in self._keys and self._name not in self._new_keys:
return False
return isinstance(self.root[self._name], h5py.Group)
def __truediv__(self, key: str) -> "DPPath":
"""Used for / operator."""
return type(self)(f"{self.root_path}#{self._connect_path(key)}", mode=self.mode)
def _connect_path(self, path: str) -> str:
"""Connect self with path."""
if self._name.endswith("/"):
return f"{self._name}{path}"
return f"{self._name}/{path}"
def __lt__(self, other: "DPH5Path") -> bool:
"""Whether this DPPath is less than other for sorting."""
if self.root_path == other.root_path:
return self._name < other._name
return self.root_path < other.root_path
def __str__(self) -> str:
"""Returns path of self."""
return f"{self.root_path}#{self._name}"
@property
def name(self) -> str:
"""Name of the path."""
return self._name.split("/")[-1]
def mkdir(self, parents: bool = False, exist_ok: bool = False) -> None:
"""Make directory.
Parameters
----------
parents : bool, optional
If true, any missing parents of this directory are created as well.
exist_ok : bool, optional
If true, no error will be raised if the target directory already exists.
"""
if self._name in self._keys:
if not exist_ok:
raise FileExistsError(f"{self} already exists")
return
if parents:
self.root.require_group(self._name)
else:
self.root.create_group(self._name)
self._new_keys.append(self._name)