-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
88 lines (66 loc) · 1.98 KB
/
utils.py
File metadata and controls
88 lines (66 loc) · 1.98 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
import orjson
import pickle
from typing import AnyStr, Union, Any
import torch
from dataclasses import dataclass
from math import sqrt
from multiprocessing import cpu_count
# DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
DEVICE = torch.device("cpu")
# torch.set_num_threads(cpu_count())
def load_json(fp: AnyStr) -> Union[dict, list]:
with open(fp, "rb") as f:
return orjson.loads(f.read())
def store_json(o: Union[dict, list], fp: AnyStr):
with open(fp, "wb") as f:
f.write(orjson.dumps(o))
def load_pkl(fp: AnyStr) -> Any:
with open(fp, "rb") as f:
return pickle.load(f)
def store_pkl(item: Any, fp: AnyStr):
with open(fp, "wb") as f:
pickle.dump(item, f)
@dataclass
class Point:
x: Union[float, int]
y: Union[float, int]
@staticmethod
def _parse_type(other) -> 'Point':
if isinstance(other, Point):
return other
elif isinstance(other, float) or isinstance(other, int):
return Point(other, other)
raise ValueError()
def __getitem__(self, item):
if item == 0:
return self.x
if item == 1:
return self.y
raise ValueError("index must be 1 or 0")
def __add__(self, other):
other = Point._parse_type(other)
return Point(
self.x + other.x,
self.y + other.y
)
def __sub__(self, other):
other = Point._parse_type(other)
return Point(
self.x - other.x,
self.y - other.y
)
def __truediv__(self, other):
other = Point._parse_type(other)
return Point(
self.x / other.x,
self.y / other.y
)
def __iter__(self):
return iter((self.x, self.y))
def distance(self, other):
if not isinstance(other, Point):
raise ValueError()
dx = other.x - self.x
dy = other.y - self.y
dist = sqrt(dx ** 2 + dy ** 2)
return dist