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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
492
493
494
"""This code is taken from <https://github.com/alexandre01/deepsvg>
by Alexandre Carlier, Martin Danelljan, Alexandre Alahi and Radu Timofte
from the paper >https://arxiv.org/pdf/2007.11301.pdf>
"""

from __future__ import annotations
import numpy as np
from enum import Enum
import torch
from typing import List, Union
Num = Union[int, float]
float_type = (int, float, np.float32)


def det(a: Point, b: Point):
    return a.pos[0] * b.pos[1] - a.pos[1] * b.pos[0]


def get_rotation_matrix(angle: Union[Angle, float]):
    if isinstance(angle, Angle):
        theta = angle.rad
    else:
        theta = angle
    c, s = np.cos(theta), np.sin(theta)
    rot_m = np.array([[c, -s],
                      [s, c]], dtype=np.float32)
    return rot_m


def union_bbox(bbox_list: List[Bbox]):
    res = None
    for bbox in bbox_list:
        res = bbox.union(res)
    return res


class Geom:
    def copy(self):
        raise NotImplementedError

    def to_str(self):
        raise NotImplementedError

    def to_tensor(self):
        raise NotImplementedError

    @staticmethod
    def from_tensor(vector: torch.Tensor):
        raise NotImplementedError

    def scale(self, factor):
        pass

    def translate(self, vec):
        pass

    def rotate(self, angle: Union[Angle, float]):
        pass

    def numericalize(self, n=256):
        raise NotImplementedError


######### Point
class Point(Geom):
    num_args = 2

    def __init__(self, x=None, y=None):
        if isinstance(x, np.ndarray):
            self.pos = x.astype(np.float32)
        elif x is None and y is None:
            self.pos = np.array([0., 0.], dtype=np.float32)
        elif (isinstance(x, float_type) or x is None) and (isinstance(y, float_type) or y is None):
            if x is None:
                x = y
            if y is None:
                y = x
            self.pos = np.array([x, y], dtype=np.float32)
        else:
            raise ValueError()

    def copy(self):
        return Point(self.pos.copy())

    @property
    def x(self):
        return self.pos[0]

    @property
    def y(self):
        return self.pos[1]

    def xproj(self):
        return Point(self.x, 0.)

    def yproj(self):
        return Point(0., self.y)

    def __add__(self, other):
        return Point(self.pos + other.pos)

    def __sub__(self, other):
        return self + other.__neg__()

    def __mul__(self, lmbda):
        if isinstance(lmbda, Point):
            return Point(self.pos * lmbda.pos)

        assert isinstance(lmbda, float_type)
        return Point(lmbda * self.pos)

    def __rmul__(self, lmbda):
        return self * lmbda

    def __truediv__(self, lmbda):
        if isinstance(lmbda, Point):
            return Point(self.pos / lmbda.pos)

        assert isinstance(lmbda, float_type)
        return self * (1 / lmbda)

    def __neg__(self):
        return self * -1

    def __repr__(self):
        return f"P({self.x}, {self.y})"

    def to_str(self):
        return f"{self.x} {self.y}"

    def tolist(self):
        return self.pos.tolist()

    def to_tensor(self):
        return torch.tensor(self.pos)

    @staticmethod
    def from_tensor(vector: torch.Tensor):
        return Point(*vector.tolist())

    def translate(self, vec: Point):
        self.pos += vec.pos

    def matmul(self, m):
        return Point(m @ self.pos)

    def rotate(self, angle: Union[Angle, float]):
        rot_m = get_rotation_matrix(angle)
        return self.matmul(rot_m)

    def rotate_(self, angle: Union[Angle, float]):
        rot_m = get_rotation_matrix(angle)
        self.pos = rot_m @ self.pos

    def scale(self, factor):
        self.pos *= factor

    def dot(self, other: Point):
        return self.pos.dot(other.pos)

    def norm(self):
        return float(np.linalg.norm(self.pos))

    def cross(self, other: Point):
        return np.cross(self.pos, other.pos)

    def dist(self, other: Point):
        return (self - other).norm()

    def angle(self, other: Point, signed=False):
        rad = np.arccos(np.clip(self.normalize().dot(other.normalize()), -1., 1.))

        if signed:
            sign = 1 if det(self, other) >= 0 else -1
            rad *= sign
        return Angle.Rad(rad)

    def distToLine(self, p1: Point, p2: Point):
        if p1.isclose(p2):
            return self.dist(p1)

        return abs((p2 - p1).cross(p1 - self)) / (p2 - p1).norm()

    def normalize(self):
        return self / self.norm()

    def numericalize(self, n=256):
        self.pos = self.pos.round().clip(min=0, max=n-1)

    def isclose(self, other: Point):
        return np.allclose(self.pos, other.pos)

    def iszero(self):
        return np.all(self.pos == 0)

    def pointwise_min(self, other: Point):
        return Point(min(self.x, other.x), min(self.y, other.y))

    def pointwise_max(self, other: Point):
        return Point(max(self.x, other.x), max(self.y, other.y))


class Radius(Point):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def copy(self):
        return Radius(self.pos.copy())

    def __repr__(self):
        return f"Rad({self.pos[0]}, {self.pos[1]})"

    def translate(self, vec: Point):
        pass


class Size(Point):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def copy(self):
        return Size(self.pos.copy())

    def __repr__(self):
        return f"Size({self.pos[0]}, {self.pos[1]})"

    def max(self):
        return self.pos.max()

    def min(self):
        return self.pos.min()

    def translate(self, vec: Point):
        pass


######### Coord
class Coord(Geom):
    num_args = 1

    class XY(Enum):
        X = "x"
        Y = "y"

    def __init__(self, coord, xy: XY = XY.X):
        self.coord = coord
        self.xy = xy

    def __repr__(self):
        return f"{self.xy.value}({self.coord})"

    def to_str(self):
        return str(self.coord)

    def to_tensor(self):
        return torch.tensor([self.coord])

    def __add__(self, other):
        if isinstance(other, float_type):
            return Coord(self.coord + other, self.xy)
        elif isinstance(other, Coord):
            if self.xy != other.xy:
                raise ValueError()
            return Coord(self.coord + other.coord, self.xy)
        elif isinstance(other, Point):
            return Coord(self.coord + getattr(other, self.xy.value), self.xy)
        else:
            raise ValueError()

    def __sub__(self, other):
        return self + other.__neg__()

    def __mul__(self, lmbda):
        assert isinstance(lmbda, float_type)
        return Coord(lmbda * self.coord)

    def __neg__(self):
        return self * -1

    def scale(self, factor):
        self.coord *= factor

    def translate(self, vec: Point):
        self.coord += getattr(vec, self.xy.value)

    def to_point(self, pos: Point, is_absolute=True):
        point = pos.copy() if is_absolute else Point(0.)
        point.pos[int(self.xy == Coord.XY.Y)] = self.coord
        return point


class XCoord(Coord):
    def __init__(self, coord):
        super().__init__(coord, xy=Coord.XY.X)

    def copy(self):
        return XCoord(self.coord)


class YCoord(Coord):
    def __init__(self, coord):
        super().__init__(coord, xy=Coord.XY.Y)

    def copy(self):
        return YCoord(self.coord)


######### Bbox
class Bbox(Geom):
    num_args = 4

    def __init__(self, x=None, y=None, w=None, h=None):
        if isinstance(x, Point) and isinstance(y, Point):
            self.xy = x
            wh = y - x
            self.wh = Size(wh.x, wh.y)
        elif (isinstance(x, float_type) or x is None) and (isinstance(y, float_type) or y is None):
            if x is None:
                x = 0.
            if y is None:
                y = float(x)

            if w is None and h is None:
                w, h = float(x), float(y)
                x, y = 0., 0.
            self.xy = Point(x, y)
            self.wh = Size(w, h)
        else:
            raise ValueError()

    @property
    def xy2(self):
        return self.xy + self.wh

    def copy(self):
        bbox = Bbox()
        bbox.xy = self.xy.copy()
        bbox.wh = self.wh.copy()
        return bbox

    @property
    def size(self):
        return self.wh

    @property
    def center(self):
        return self.xy + self.wh / 2

    def __repr__(self):
        return f"Bbox({self.xy.to_str()} {self.wh.to_str()})"

    def to_str(self):
        return f"{self.xy.to_str()} {self.wh.to_str()}"

    def to_tensor(self):
        return torch.tensor([*self.xy.to_tensor(), *self.wh.to_tensor()])

    def make_square(self, min_size=None):
        center = self.center
        size = self.wh.max()

        if min_size is not None:
            size = max(size, min_size)

        self.wh = Size(size, size)
        self.xy = center - self.wh / 2

        return self

    def translate(self, vec):
        self.xy.translate(vec)

    def scale(self, factor):
        self.xy.scale(factor)
        self.wh.scale(factor)

    def union(self, other: Bbox):
        if other is None:
            return self
        return Bbox(self.xy.pointwise_min(other.xy), self.xy2.pointwise_max(other.xy2))

    def intersect(self, other: Bbox):
        if other is None:
            return self

        bbox = Bbox(self.xy.pointwise_max(other.xy), self.xy2.pointwise_min(other.xy2))
        if bbox.wh.x < 0 or bbox.wh.y < 0:
            return None

        return bbox

    @staticmethod
    def from_points(points: List[Point]):
        if not points:
            return None
        xy = xy2 = points[0]
        for p in points[1:]:
            xy = xy.pointwise_min(p)
            xy2 = xy2.pointwise_max(p)
        return Bbox(xy, xy2)

    def to_rectangle(self, *args, **kwargs):
        from .svg_primitive import SVGRectangle
        return SVGRectangle(self.xy, self.wh, *args, **kwargs)

    def area(self):
        return self.wh.pos.prod()

    def overlap(self, other):
        inter = self.intersect(other)
        if inter is None:
            return 0.
        return inter.area() / self.area()


######### Angle
class Angle(Geom):
    num_args = 1

    def __init__(self, deg):
        self.deg = deg

    @property
    def rad(self):
        return np.deg2rad(self.deg)

    def copy(self):
        return Angle(self.deg)

    def __repr__(self):
        return f"α({self.deg})"

    def to_str(self):
        return str(self.deg)

    def to_tensor(self):
        return torch.tensor([self.deg])

    @staticmethod
    def from_tensor(vector: torch.Tensor):
        return Angle(vector.item())

    @staticmethod
    def Rad(rad):
        return Angle(np.rad2deg(rad))

    def __add__(self, other: Angle):
        return Angle(self.deg + other.deg)

    def __sub__(self, other: Angle):
        return self + other.__neg__()

    def __mul__(self, lmbda):
        assert isinstance(lmbda, float_type)
        return Angle(lmbda * self.deg)

    def __rmul__(self, lmbda):
        assert isinstance(lmbda, float_type)
        return self * lmbda

    def __truediv__(self, lmbda):
        assert isinstance(lmbda, float_type)
        return self * (1 / lmbda)

    def __neg__(self):
        return self * -1


######### Flag
class Flag(Geom):
    num_args = 1

    def __init__(self, flag):
        self.flag = int(flag)

    def copy(self):
        return Flag(self.flag)

    def __repr__(self):
        return f"flag({self.flag})"

    def to_str(self):
        return str(self.flag)

    def to_tensor(self):
        return torch.tensor([self.flag])

    def __invert__(self):
        return Flag(1 - self.flag)

    @staticmethod
    def from_tensor(vector: torch.Tensor):
        return Flag(vector.item())