interpolatableHelpers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. # Prefer `scipy.optimize.linear_sum_assignment` for performance.
  137. # `Munkres` is also supported as a fallback for minimalistic systems
  138. # where installing SciPy is not feasible.
  139. try:
  140. from scipy.optimize import linear_sum_assignment
  141. min_cost_perfect_bipartite_matching = min_cost_perfect_bipartite_matching_scipy
  142. except ImportError:
  143. try:
  144. from munkres import Munkres
  145. min_cost_perfect_bipartite_matching = (
  146. min_cost_perfect_bipartite_matching_munkres
  147. )
  148. except ImportError:
  149. min_cost_perfect_bipartite_matching = (
  150. min_cost_perfect_bipartite_matching_bruteforce
  151. )
  152. def contour_vector_from_stats(stats):
  153. # Don't change the order of items here.
  154. # It's okay to add to the end, but otherwise, other
  155. # code depends on it. Search for "covariance".
  156. size = sqrt(abs(stats.area))
  157. return (
  158. copysign((size), stats.area),
  159. stats.meanX,
  160. stats.meanY,
  161. stats.stddevX * 2,
  162. stats.stddevY * 2,
  163. stats.correlation * size,
  164. )
  165. def matching_for_vectors(m0, m1):
  166. n = len(m0)
  167. identity_matching = list(range(n))
  168. costs = [[vdiff_hypot2(v0, v1) for v1 in m1] for v0 in m0]
  169. (
  170. matching,
  171. matching_cost,
  172. ) = min_cost_perfect_bipartite_matching(costs)
  173. identity_cost = sum(costs[i][i] for i in range(n))
  174. return matching, matching_cost, identity_cost
  175. def points_characteristic_bits(points):
  176. bits = 0
  177. for pt, b in reversed(points):
  178. bits = (bits << 1) | b
  179. return bits
  180. _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR = 4
  181. def points_complex_vector(points):
  182. vector = []
  183. if not points:
  184. return vector
  185. points = [complex(*pt) for pt, _ in points]
  186. n = len(points)
  187. assert _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR == 4
  188. points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1])
  189. while len(points) < _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR:
  190. points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1])
  191. for i in range(n):
  192. # The weights are magic numbers.
  193. # The point itself
  194. p0 = points[i]
  195. vector.append(p0)
  196. # The vector to the next point
  197. p1 = points[i + 1]
  198. d0 = p1 - p0
  199. vector.append(d0 * 3)
  200. # The turn vector
  201. p2 = points[i + 2]
  202. d1 = p2 - p1
  203. vector.append(d1 - d0)
  204. # The angle to the next point, as a cross product;
  205. # Square root of, to match dimentionality of distance.
  206. cross = d0.real * d1.imag - d0.imag * d1.real
  207. cross = copysign(sqrt(abs(cross)), cross)
  208. vector.append(cross * 4)
  209. return vector
  210. def add_isomorphisms(points, isomorphisms, reverse):
  211. reference_bits = points_characteristic_bits(points)
  212. n = len(points)
  213. # if points[0][0] == points[-1][0]:
  214. # abort
  215. if reverse:
  216. points = points[::-1]
  217. bits = points_characteristic_bits(points)
  218. else:
  219. bits = reference_bits
  220. vector = points_complex_vector(points)
  221. assert len(vector) % n == 0
  222. mult = len(vector) // n
  223. mask = (1 << n) - 1
  224. for i in range(n):
  225. b = ((bits << (n - i)) & mask) | (bits >> i)
  226. if b == reference_bits:
  227. isomorphisms.append(
  228. (rot_list(vector, -i * mult), n - 1 - i if reverse else i, reverse)
  229. )
  230. def find_parents_and_order(glyphsets, locations, *, discrete_axes=set()):
  231. parents = [None] + list(range(len(glyphsets) - 1))
  232. order = list(range(len(glyphsets)))
  233. if locations:
  234. # Order base master first
  235. bases = [
  236. i
  237. for i, l in enumerate(locations)
  238. if all(v == 0 for k, v in l.items() if k not in discrete_axes)
  239. ]
  240. if bases:
  241. logging.info("Found %s base masters: %s", len(bases), bases)
  242. else:
  243. logging.warning("No base master location found")
  244. # Form a minimum spanning tree of the locations
  245. try:
  246. from scipy.sparse.csgraph import minimum_spanning_tree
  247. graph = [[0] * len(locations) for _ in range(len(locations))]
  248. axes = set()
  249. for l in locations:
  250. axes.update(l.keys())
  251. axes = sorted(axes)
  252. vectors = [tuple(l.get(k, 0) for k in axes) for l in locations]
  253. for i, j in itertools.combinations(range(len(locations)), 2):
  254. i_discrete_location = {
  255. k: v for k, v in zip(axes, vectors[i]) if k in discrete_axes
  256. }
  257. j_discrete_location = {
  258. k: v for k, v in zip(axes, vectors[j]) if k in discrete_axes
  259. }
  260. if i_discrete_location != j_discrete_location:
  261. continue
  262. graph[i][j] = vdiff_hypot2(vectors[i], vectors[j])
  263. tree = minimum_spanning_tree(graph, overwrite=True)
  264. rows, cols = tree.nonzero()
  265. graph = defaultdict(set)
  266. for row, col in zip(rows, cols):
  267. graph[row].add(col)
  268. graph[col].add(row)
  269. # Traverse graph from the base and assign parents
  270. parents = [None] * len(locations)
  271. order = []
  272. visited = set()
  273. queue = deque(bases)
  274. while queue:
  275. i = queue.popleft()
  276. visited.add(i)
  277. order.append(i)
  278. for j in sorted(graph[i]):
  279. if j not in visited:
  280. parents[j] = i
  281. queue.append(j)
  282. assert len(order) == len(
  283. parents
  284. ), "Not all masters are reachable; report an issue"
  285. except ImportError:
  286. pass
  287. log.info("Parents: %s", parents)
  288. log.info("Order: %s", order)
  289. return parents, order
  290. def transform_from_stats(stats, inverse=False):
  291. # https://cookierobotics.com/007/
  292. a = stats.varianceX
  293. b = stats.covariance
  294. c = stats.varianceY
  295. delta = (((a - c) * 0.5) ** 2 + b * b) ** 0.5
  296. lambda1 = (a + c) * 0.5 + delta # Major eigenvalue
  297. lambda2 = (a + c) * 0.5 - delta # Minor eigenvalue
  298. theta = atan2(lambda1 - a, b) if b != 0 else (pi * 0.5 if a < c else 0)
  299. trans = Transform()
  300. if lambda2 < 0:
  301. # XXX This is a hack.
  302. # The problem is that the covariance matrix is singular.
  303. # This happens when the contour is a line, or a circle.
  304. # In that case, the covariance matrix is not a good
  305. # representation of the contour.
  306. # We should probably detect this earlier and avoid
  307. # computing the covariance matrix in the first place.
  308. # But for now, we just avoid the division by zero.
  309. lambda2 = 0
  310. if inverse:
  311. trans = trans.translate(-stats.meanX, -stats.meanY)
  312. trans = trans.rotate(-theta)
  313. trans = trans.scale(1 / sqrt(lambda1), 1 / sqrt(lambda2))
  314. else:
  315. trans = trans.scale(sqrt(lambda1), sqrt(lambda2))
  316. trans = trans.rotate(theta)
  317. trans = trans.translate(stats.meanX, stats.meanY)
  318. return trans