interpolatableHelpers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. from fontTools.ttLib.ttGlyphSet import LerpGlyphSet
  2. from fontTools.pens.basePen import AbstractPen, BasePen, DecomposingPen
  3. from fontTools.pens.pointPen import AbstractPointPen, SegmentToPointPen
  4. from fontTools.pens.recordingPen import RecordingPen, DecomposingRecordingPen
  5. from fontTools.misc.transform import Transform
  6. from collections import defaultdict, deque
  7. from math import sqrt, copysign, atan2, pi
  8. from enum import Enum
  9. import itertools
  10. import logging
  11. log = logging.getLogger("fontTools.varLib.interpolatable")
  12. class InterpolatableProblem:
  13. NOTHING = "nothing"
  14. MISSING = "missing"
  15. OPEN_PATH = "open_path"
  16. PATH_COUNT = "path_count"
  17. NODE_COUNT = "node_count"
  18. NODE_INCOMPATIBILITY = "node_incompatibility"
  19. CONTOUR_ORDER = "contour_order"
  20. WRONG_START_POINT = "wrong_start_point"
  21. KINK = "kink"
  22. UNDERWEIGHT = "underweight"
  23. OVERWEIGHT = "overweight"
  24. severity = {
  25. MISSING: 1,
  26. OPEN_PATH: 2,
  27. PATH_COUNT: 3,
  28. NODE_COUNT: 4,
  29. NODE_INCOMPATIBILITY: 5,
  30. CONTOUR_ORDER: 6,
  31. WRONG_START_POINT: 7,
  32. KINK: 8,
  33. UNDERWEIGHT: 9,
  34. OVERWEIGHT: 10,
  35. NOTHING: 11,
  36. }
  37. def sort_problems(problems):
  38. """Sort problems by severity, then by glyph name, then by problem message."""
  39. return dict(
  40. sorted(
  41. problems.items(),
  42. key=lambda _: -min(
  43. (
  44. (InterpolatableProblem.severity[p["type"]] + p.get("tolerance", 0))
  45. for p in _[1]
  46. ),
  47. ),
  48. reverse=True,
  49. )
  50. )
  51. def rot_list(l, k):
  52. """Rotate list by k items forward. Ie. item at position 0 will be
  53. at position k in returned list. Negative k is allowed."""
  54. return l[-k:] + l[:-k]
  55. class PerContourPen(BasePen):
  56. def __init__(self, Pen, glyphset=None):
  57. BasePen.__init__(self, glyphset)
  58. self._glyphset = glyphset
  59. self._Pen = Pen
  60. self._pen = None
  61. self.value = []
  62. def _moveTo(self, p0):
  63. self._newItem()
  64. self._pen.moveTo(p0)
  65. def _lineTo(self, p1):
  66. self._pen.lineTo(p1)
  67. def _qCurveToOne(self, p1, p2):
  68. self._pen.qCurveTo(p1, p2)
  69. def _curveToOne(self, p1, p2, p3):
  70. self._pen.curveTo(p1, p2, p3)
  71. def _closePath(self):
  72. self._pen.closePath()
  73. self._pen = None
  74. def _endPath(self):
  75. self._pen.endPath()
  76. self._pen = None
  77. def _newItem(self):
  78. self._pen = pen = self._Pen()
  79. self.value.append(pen)
  80. class PerContourOrComponentPen(PerContourPen):
  81. def addComponent(self, glyphName, transformation):
  82. self._newItem()
  83. self.value[-1].addComponent(glyphName, transformation)
  84. class SimpleRecordingPointPen(AbstractPointPen):
  85. def __init__(self):
  86. self.value = []
  87. def beginPath(self, identifier=None, **kwargs):
  88. pass
  89. def endPath(self) -> None:
  90. pass
  91. def addPoint(self, pt, segmentType=None):
  92. self.value.append((pt, False if segmentType is None else True))
  93. def vdiff_hypot2(v0, v1):
  94. s = 0
  95. for x0, x1 in zip(v0, v1):
  96. d = x1 - x0
  97. s += d * d
  98. return s
  99. def vdiff_hypot2_complex(v0, v1):
  100. s = 0
  101. for x0, x1 in zip(v0, v1):
  102. d = x1 - x0
  103. s += d.real * d.real + d.imag * d.imag
  104. # This does the same but seems to be slower:
  105. # s += (d * d.conjugate()).real
  106. return s
  107. def matching_cost(G, matching):
  108. return sum(G[i][j] for i, j in enumerate(matching))
  109. def min_cost_perfect_bipartite_matching_scipy(G):
  110. n = len(G)
  111. rows, cols = linear_sum_assignment(G)
  112. assert (rows == list(range(n))).all()
  113. # Convert numpy array and integer to Python types,
  114. # to ensure that this is JSON-serializable.
  115. cols = list(int(e) for e in cols)
  116. return list(cols), matching_cost(G, cols)
  117. def min_cost_perfect_bipartite_matching_munkres(G):
  118. n = len(G)
  119. cols = [None] * n
  120. for row, col in Munkres().compute(G):
  121. cols[row] = col
  122. return cols, matching_cost(G, cols)
  123. def min_cost_perfect_bipartite_matching_bruteforce(G):
  124. n = len(G)
  125. if n > 6:
  126. raise Exception("Install Python module 'munkres' or 'scipy >= 0.17.0'")
  127. # Otherwise just brute-force
  128. permutations = itertools.permutations(range(n))
  129. best = list(next(permutations))
  130. best_cost = matching_cost(G, best)
  131. for p in permutations:
  132. cost = matching_cost(G, p)
  133. if cost < best_cost:
  134. best, best_cost = list(p), cost
  135. return best, best_cost
  136. try:
  137. from scipy.optimize import linear_sum_assignment
  138. min_cost_perfect_bipartite_matching = min_cost_perfect_bipartite_matching_scipy
  139. except ImportError:
  140. try:
  141. from munkres import Munkres
  142. min_cost_perfect_bipartite_matching = (
  143. min_cost_perfect_bipartite_matching_munkres
  144. )
  145. except ImportError:
  146. min_cost_perfect_bipartite_matching = (
  147. min_cost_perfect_bipartite_matching_bruteforce
  148. )
  149. def contour_vector_from_stats(stats):
  150. # Don't change the order of items here.
  151. # It's okay to add to the end, but otherwise, other
  152. # code depends on it. Search for "covariance".
  153. size = sqrt(abs(stats.area))
  154. return (
  155. copysign((size), stats.area),
  156. stats.meanX,
  157. stats.meanY,
  158. stats.stddevX * 2,
  159. stats.stddevY * 2,
  160. stats.correlation * size,
  161. )
  162. def matching_for_vectors(m0, m1):
  163. n = len(m0)
  164. identity_matching = list(range(n))
  165. costs = [[vdiff_hypot2(v0, v1) for v1 in m1] for v0 in m0]
  166. (
  167. matching,
  168. matching_cost,
  169. ) = min_cost_perfect_bipartite_matching(costs)
  170. identity_cost = sum(costs[i][i] for i in range(n))
  171. return matching, matching_cost, identity_cost
  172. def points_characteristic_bits(points):
  173. bits = 0
  174. for pt, b in reversed(points):
  175. bits = (bits << 1) | b
  176. return bits
  177. _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR = 4
  178. def points_complex_vector(points):
  179. vector = []
  180. if not points:
  181. return vector
  182. points = [complex(*pt) for pt, _ in points]
  183. n = len(points)
  184. assert _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR == 4
  185. points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1])
  186. while len(points) < _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR:
  187. points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1])
  188. for i in range(n):
  189. # The weights are magic numbers.
  190. # The point itself
  191. p0 = points[i]
  192. vector.append(p0)
  193. # The vector to the next point
  194. p1 = points[i + 1]
  195. d0 = p1 - p0
  196. vector.append(d0 * 3)
  197. # The turn vector
  198. p2 = points[i + 2]
  199. d1 = p2 - p1
  200. vector.append(d1 - d0)
  201. # The angle to the next point, as a cross product;
  202. # Square root of, to match dimentionality of distance.
  203. cross = d0.real * d1.imag - d0.imag * d1.real
  204. cross = copysign(sqrt(abs(cross)), cross)
  205. vector.append(cross * 4)
  206. return vector
  207. def add_isomorphisms(points, isomorphisms, reverse):
  208. reference_bits = points_characteristic_bits(points)
  209. n = len(points)
  210. # if points[0][0] == points[-1][0]:
  211. # abort
  212. if reverse:
  213. points = points[::-1]
  214. bits = points_characteristic_bits(points)
  215. else:
  216. bits = reference_bits
  217. vector = points_complex_vector(points)
  218. assert len(vector) % n == 0
  219. mult = len(vector) // n
  220. mask = (1 << n) - 1
  221. for i in range(n):
  222. b = ((bits << (n - i)) & mask) | (bits >> i)
  223. if b == reference_bits:
  224. isomorphisms.append(
  225. (rot_list(vector, -i * mult), n - 1 - i if reverse else i, reverse)
  226. )
  227. def find_parents_and_order(glyphsets, locations, *, discrete_axes=set()):
  228. parents = [None] + list(range(len(glyphsets) - 1))
  229. order = list(range(len(glyphsets)))
  230. if locations:
  231. # Order base master first
  232. bases = [
  233. i
  234. for i, l in enumerate(locations)
  235. if all(v == 0 for k, v in l.items() if k not in discrete_axes)
  236. ]
  237. if bases:
  238. logging.info("Found %s base masters: %s", len(bases), bases)
  239. else:
  240. logging.warning("No base master location found")
  241. # Form a minimum spanning tree of the locations
  242. try:
  243. from scipy.sparse.csgraph import minimum_spanning_tree
  244. graph = [[0] * len(locations) for _ in range(len(locations))]
  245. axes = set()
  246. for l in locations:
  247. axes.update(l.keys())
  248. axes = sorted(axes)
  249. vectors = [tuple(l.get(k, 0) for k in axes) for l in locations]
  250. for i, j in itertools.combinations(range(len(locations)), 2):
  251. i_discrete_location = {
  252. k: v for k, v in zip(axes, vectors[i]) if k in discrete_axes
  253. }
  254. j_discrete_location = {
  255. k: v for k, v in zip(axes, vectors[j]) if k in discrete_axes
  256. }
  257. if i_discrete_location != j_discrete_location:
  258. continue
  259. graph[i][j] = vdiff_hypot2(vectors[i], vectors[j])
  260. tree = minimum_spanning_tree(graph, overwrite=True)
  261. rows, cols = tree.nonzero()
  262. graph = defaultdict(set)
  263. for row, col in zip(rows, cols):
  264. graph[row].add(col)
  265. graph[col].add(row)
  266. # Traverse graph from the base and assign parents
  267. parents = [None] * len(locations)
  268. order = []
  269. visited = set()
  270. queue = deque(bases)
  271. while queue:
  272. i = queue.popleft()
  273. visited.add(i)
  274. order.append(i)
  275. for j in sorted(graph[i]):
  276. if j not in visited:
  277. parents[j] = i
  278. queue.append(j)
  279. assert len(order) == len(
  280. parents
  281. ), "Not all masters are reachable; report an issue"
  282. except ImportError:
  283. pass
  284. log.info("Parents: %s", parents)
  285. log.info("Order: %s", order)
  286. return parents, order
  287. def transform_from_stats(stats, inverse=False):
  288. # https://cookierobotics.com/007/
  289. a = stats.varianceX
  290. b = stats.covariance
  291. c = stats.varianceY
  292. delta = (((a - c) * 0.5) ** 2 + b * b) ** 0.5
  293. lambda1 = (a + c) * 0.5 + delta # Major eigenvalue
  294. lambda2 = (a + c) * 0.5 - delta # Minor eigenvalue
  295. theta = atan2(lambda1 - a, b) if b != 0 else (pi * 0.5 if a < c else 0)
  296. trans = Transform()
  297. if lambda2 < 0:
  298. # XXX This is a hack.
  299. # The problem is that the covariance matrix is singular.
  300. # This happens when the contour is a line, or a circle.
  301. # In that case, the covariance matrix is not a good
  302. # representation of the contour.
  303. # We should probably detect this earlier and avoid
  304. # computing the covariance matrix in the first place.
  305. # But for now, we just avoid the division by zero.
  306. lambda2 = 0
  307. if inverse:
  308. trans = trans.translate(-stats.meanX, -stats.meanY)
  309. trans = trans.rotate(-theta)
  310. trans = trans.scale(1 / sqrt(lambda1), 1 / sqrt(lambda2))
  311. else:
  312. trans = trans.scale(sqrt(lambda1), sqrt(lambda2))
  313. trans = trans.rotate(theta)
  314. trans = trans.translate(stats.meanX, stats.meanY)
  315. return trans