This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsigil.py
191 lines (136 loc) · 4.91 KB
/
sigil.py
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
import json
try:
import numpy
except ImportError:
numpy = None
class Sigil(object):
def __init__(self, ops, origin=None, char=None, angle=0):
'''Given a list of differential ops, and an optional origin, create a
Sigil instance. If origin is omitted, it is estimated with ops_origin.
If part of a SigilDict, char is the character this Sigil represents.'''
self.origin = origin
if origin is None:
self.origin = ops_origin(ops)
self.scale = ops_scale(ops)
self.ops = ops
self.char = char
self.angle = angle
x1, x2, y1, y2 = ops_bb(ops)
if angle == 0:
self.width = x2 - x1
elif angle == -90:
self.width = y2 - y1
@staticmethod
def from_abs_ops(ops):
return Sigil(diff_ops(ops))
def to_dict(self):
return {
'origin': self.origin,
'ops': self.ops,
}
def rotated(self, angle=-90):
'''Return a copy of the sigil rotated clockwise by the given angle.'''
if numpy is None:
raise NotImplementedError('rotated() requires numpy')
theta = angle * numpy.pi / 180.0
matrix = numpy.array([[ numpy.cos(theta), numpy.sin(theta)],
[-numpy.sin(theta), numpy.cos(theta)]])
trans_ops = [(list(matrix.dot(coords)), operator)
for (coords, operator) in self.ops]
trans_origin = list(matrix.dot(self.origin))
return Sigil(ops=trans_ops,
origin=trans_origin,
char=self.char,
angle=self.angle + angle)
def cmp(self, other):
if len(self.ops) != len(other.ops):
print 'different lengths ({}, {}). trying prefix'.format(len(self.ops), len(other.ops))
ans = []
for ((x1, y1), c1), ((x2, y2), c2) in zip(self.ops, other.ops):
s = '{:.2g}'.format(max(abs(x1-x2), abs(y1-y2)))
if c1 != c2:
s = s+'*'
ans.append(s)
return ', '.join(ans)
def rescale(self, sf):
self.origin = [x*sf for x in self.origin]
for (i, op) in enumerate(self.ops):
self.ops[i] = [[x*sf for x in op[0]], op[1]]
self.scale = ops_scale(self.ops)
x1, x2, _, _ = ops_bb(self.ops)
self.width = x2 - x1
def __len__(self):
return len(self.ops)
def __str__(self):
ops_str = '[{}]'.format(', '.join(
'(({:.2f}, {:.2f}), {})'.format(op[0][0], op[0][1], op[1])
for op in self.ops))
return 'Sigil({!r}, {})'.format(self.char, ops_str)
class SigilDict(dict):
@staticmethod
def from_json(json_file):
result = SigilDict()
for k, v in json.load(json_file).items():
if isinstance(v, dict):
v = [v]
result[k] = [Sigil(char=str(k), **params) for params in v]
return result
def to_json(self, json_file):
json.dump({k: [s.to_dict() for s in v] for (k, v) in self.items()},
json_file, sort_keys=True, indent=4)
def remove_zero_ops(ops, tol=0.01):
'''Given a list of absolute ops, remove all ops with a length of less than
tol (0.01 by default).'''
assert ops[0][1] == 'm'
px, py = ops[0][0]
ans = [ops[0]]
tol = 0.01
for (x, y), c in ops[1:]:
n2 = (x-px) ** 2 + (y-py) ** 2
if n2 > tol ** 2:
ans.append( ((x, y), c) )
px, py = x, y
return ans
def diff_ops(ops):
'''Convert a list of absolute ops (eg from a PDF) to differential ops,
by subtracting the coords of the first 'm' op.'''
assert ops[0][1] == 'm'
px, py = ops[0][0]
ans = []
for (x, y), c in ops[1:]:
ans.append( ((x-px, y-py), c) )
px, py = x, y
return ans
def ops_bb(ops):
'''Given a differential ops list, determine the bounding box as
(min x, max x, min y, max y).
It ignores the points on curve (c) operators, since the line doesn't
necessarily reach these points.'''
px, py = 0, 0
xs, ys = [0], [0]
for (dx, dy), c in ops:
px += dx
py += dy
if c != 'c':
xs.append(px)
ys.append(py)
return (min(xs), max(xs), min(ys), max(ys))
def ops_origin(ops):
'''Given a differential ops list, estimate the origin, as a vector from
the initial position. The origin is the (min x)-(min y) corner of the
bounding box.'''
min_x, _, min_y, _ = ops_bb(ops)
return (min_x, min_y)
def ops_height(ops):
'''Given a differential ops list, determine the height of the bounding
box.'''
_, _, min_y, max_y = ops_bb(ops)
return max_y - min_y
def ops_scale(ops):
'''Get an arbitrary number indicating the scale of the sigil,
given some differential operations.
Uses sum |dx_i| + |dy_i|.'''
ans = 0
for (dx, dy), _ in ops:
ans += abs(dx) + abs(dy)
return ans