statisticsPen.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. """Pen calculating area, center of mass, variance and standard-deviation,
  2. covariance and correlation, and slant, of glyph shapes."""
  3. from math import sqrt, degrees, atan
  4. from fontTools.pens.basePen import BasePen, OpenContourError
  5. from fontTools.pens.momentsPen import MomentsPen
  6. __all__ = ["StatisticsPen", "StatisticsControlPen"]
  7. class StatisticsBase:
  8. def __init__(self):
  9. self._zero()
  10. def _zero(self):
  11. self.area = 0
  12. self.meanX = 0
  13. self.meanY = 0
  14. self.varianceX = 0
  15. self.varianceY = 0
  16. self.stddevX = 0
  17. self.stddevY = 0
  18. self.covariance = 0
  19. self.correlation = 0
  20. self.slant = 0
  21. def _update(self):
  22. # XXX The variance formulas should never produce a negative value,
  23. # but due to reasons I don't understand, both of our pens do.
  24. # So we take the absolute value here.
  25. self.varianceX = abs(self.varianceX)
  26. self.varianceY = abs(self.varianceY)
  27. self.stddevX = stddevX = sqrt(self.varianceX)
  28. self.stddevY = stddevY = sqrt(self.varianceY)
  29. # Correlation(X,Y) = Covariance(X,Y) / ( stddev(X) * stddev(Y) )
  30. # https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
  31. if stddevX * stddevY == 0:
  32. correlation = float("NaN")
  33. else:
  34. # XXX The above formula should never produce a value outside
  35. # the range [-1, 1], but due to reasons I don't understand,
  36. # (probably the same issue as above), it does. So we clamp.
  37. correlation = self.covariance / (stddevX * stddevY)
  38. correlation = max(-1, min(1, correlation))
  39. self.correlation = correlation if abs(correlation) > 1e-3 else 0
  40. slant = (
  41. self.covariance / self.varianceY if self.varianceY != 0 else float("NaN")
  42. )
  43. self.slant = slant if abs(slant) > 1e-3 else 0
  44. class StatisticsPen(StatisticsBase, MomentsPen):
  45. """Pen calculating area, center of mass, variance and
  46. standard-deviation, covariance and correlation, and slant,
  47. of glyph shapes.
  48. Note that if the glyph shape is self-intersecting, the values
  49. are not correct (but well-defined). Moreover, area will be
  50. negative if contour directions are clockwise."""
  51. def __init__(self, glyphset=None):
  52. MomentsPen.__init__(self, glyphset=glyphset)
  53. StatisticsBase.__init__(self)
  54. def _closePath(self):
  55. MomentsPen._closePath(self)
  56. self._update()
  57. def _update(self):
  58. area = self.area
  59. if not area:
  60. self._zero()
  61. return
  62. # Center of mass
  63. # https://en.wikipedia.org/wiki/Center_of_mass#A_continuous_volume
  64. self.meanX = meanX = self.momentX / area
  65. self.meanY = meanY = self.momentY / area
  66. # Var(X) = E[X^2] - E[X]^2
  67. self.varianceX = self.momentXX / area - meanX * meanX
  68. self.varianceY = self.momentYY / area - meanY * meanY
  69. # Covariance(X,Y) = (E[X.Y] - E[X]E[Y])
  70. self.covariance = self.momentXY / area - meanX * meanY
  71. StatisticsBase._update(self)
  72. class StatisticsControlPen(StatisticsBase, BasePen):
  73. """Pen calculating area, center of mass, variance and
  74. standard-deviation, covariance and correlation, and slant,
  75. of glyph shapes, using the control polygon only.
  76. Note that if the glyph shape is self-intersecting, the values
  77. are not correct (but well-defined). Moreover, area will be
  78. negative if contour directions are clockwise."""
  79. def __init__(self, glyphset=None):
  80. BasePen.__init__(self, glyphset)
  81. StatisticsBase.__init__(self)
  82. self._nodes = []
  83. def _moveTo(self, pt):
  84. self._nodes.append(complex(*pt))
  85. def _lineTo(self, pt):
  86. self._nodes.append(complex(*pt))
  87. def _qCurveToOne(self, pt1, pt2):
  88. for pt in (pt1, pt2):
  89. self._nodes.append(complex(*pt))
  90. def _curveToOne(self, pt1, pt2, pt3):
  91. for pt in (pt1, pt2, pt3):
  92. self._nodes.append(complex(*pt))
  93. def _closePath(self):
  94. self._update()
  95. def _endPath(self):
  96. p0 = self._getCurrentPoint()
  97. if p0 != self.__startPoint:
  98. raise OpenContourError("Glyph statistics not defined on open contours.")
  99. def _update(self):
  100. nodes = self._nodes
  101. n = len(nodes)
  102. # Triangle formula
  103. self.area = (
  104. sum(
  105. (p0.real * p1.imag - p1.real * p0.imag)
  106. for p0, p1 in zip(nodes, nodes[1:] + nodes[:1])
  107. )
  108. / 2
  109. )
  110. # Center of mass
  111. # https://en.wikipedia.org/wiki/Center_of_mass#A_system_of_particles
  112. sumNodes = sum(nodes)
  113. self.meanX = meanX = sumNodes.real / n
  114. self.meanY = meanY = sumNodes.imag / n
  115. if n > 1:
  116. # Var(X) = (sum[X^2] - sum[X]^2 / n) / (n - 1)
  117. # https://www.statisticshowto.com/probability-and-statistics/descriptive-statistics/sample-variance/
  118. self.varianceX = varianceX = (
  119. sum(p.real * p.real for p in nodes)
  120. - (sumNodes.real * sumNodes.real) / n
  121. ) / (n - 1)
  122. self.varianceY = varianceY = (
  123. sum(p.imag * p.imag for p in nodes)
  124. - (sumNodes.imag * sumNodes.imag) / n
  125. ) / (n - 1)
  126. # Covariance(X,Y) = (sum[X.Y] - sum[X].sum[Y] / n) / (n - 1)
  127. self.covariance = covariance = (
  128. sum(p.real * p.imag for p in nodes)
  129. - (sumNodes.real * sumNodes.imag) / n
  130. ) / (n - 1)
  131. else:
  132. self.varianceX = varianceX = 0
  133. self.varianceY = varianceY = 0
  134. self.covariance = covariance = 0
  135. StatisticsBase._update(self)
  136. def _test(glyphset, upem, glyphs, quiet=False, *, control=False):
  137. from fontTools.pens.transformPen import TransformPen
  138. from fontTools.misc.transform import Scale
  139. wght_sum = 0
  140. wght_sum_perceptual = 0
  141. wdth_sum = 0
  142. slnt_sum = 0
  143. slnt_sum_perceptual = 0
  144. for glyph_name in glyphs:
  145. glyph = glyphset[glyph_name]
  146. if control:
  147. pen = StatisticsControlPen(glyphset=glyphset)
  148. else:
  149. pen = StatisticsPen(glyphset=glyphset)
  150. transformer = TransformPen(pen, Scale(1.0 / upem))
  151. glyph.draw(transformer)
  152. area = abs(pen.area)
  153. width = glyph.width
  154. wght_sum += area
  155. wght_sum_perceptual += pen.area * width
  156. wdth_sum += width
  157. slnt_sum += pen.slant
  158. slnt_sum_perceptual += pen.slant * width
  159. if quiet:
  160. continue
  161. print()
  162. print("glyph:", glyph_name)
  163. for item in [
  164. "area",
  165. "momentX",
  166. "momentY",
  167. "momentXX",
  168. "momentYY",
  169. "momentXY",
  170. "meanX",
  171. "meanY",
  172. "varianceX",
  173. "varianceY",
  174. "stddevX",
  175. "stddevY",
  176. "covariance",
  177. "correlation",
  178. "slant",
  179. ]:
  180. print("%s: %g" % (item, getattr(pen, item)))
  181. if not quiet:
  182. print()
  183. print("font:")
  184. print("weight: %g" % (wght_sum * upem / wdth_sum))
  185. print("weight (perceptual): %g" % (wght_sum_perceptual / wdth_sum))
  186. print("width: %g" % (wdth_sum / upem / len(glyphs)))
  187. slant = slnt_sum / len(glyphs)
  188. print("slant: %g" % slant)
  189. print("slant angle: %g" % -degrees(atan(slant)))
  190. slant_perceptual = slnt_sum_perceptual / wdth_sum
  191. print("slant (perceptual): %g" % slant_perceptual)
  192. print("slant (perceptual) angle: %g" % -degrees(atan(slant_perceptual)))
  193. def main(args):
  194. """Report font glyph shape geometricsl statistics"""
  195. if args is None:
  196. import sys
  197. args = sys.argv[1:]
  198. import argparse
  199. parser = argparse.ArgumentParser(
  200. "fonttools pens.statisticsPen",
  201. description="Report font glyph shape geometricsl statistics",
  202. )
  203. parser.add_argument("font", metavar="font.ttf", help="Font file.")
  204. parser.add_argument("glyphs", metavar="glyph-name", help="Glyph names.", nargs="*")
  205. parser.add_argument(
  206. "-y",
  207. metavar="<number>",
  208. help="Face index into a collection to open. Zero based.",
  209. )
  210. parser.add_argument(
  211. "-c",
  212. "--control",
  213. action="store_true",
  214. help="Use the control-box pen instead of the Green therem.",
  215. )
  216. parser.add_argument(
  217. "-q", "--quiet", action="store_true", help="Only report font-wide statistics."
  218. )
  219. parser.add_argument(
  220. "--variations",
  221. metavar="AXIS=LOC",
  222. default="",
  223. help="List of space separated locations. A location consist in "
  224. "the name of a variation axis, followed by '=' and a number. E.g.: "
  225. "wght=700 wdth=80. The default is the location of the base master.",
  226. )
  227. options = parser.parse_args(args)
  228. glyphs = options.glyphs
  229. fontNumber = int(options.y) if options.y is not None else 0
  230. location = {}
  231. for tag_v in options.variations.split():
  232. fields = tag_v.split("=")
  233. tag = fields[0].strip()
  234. v = int(fields[1])
  235. location[tag] = v
  236. from fontTools.ttLib import TTFont
  237. font = TTFont(options.font, fontNumber=fontNumber)
  238. if not glyphs:
  239. glyphs = font.getGlyphOrder()
  240. _test(
  241. font.getGlyphSet(location=location),
  242. font["head"].unitsPerEm,
  243. glyphs,
  244. quiet=options.quiet,
  245. control=options.control,
  246. )
  247. if __name__ == "__main__":
  248. import sys
  249. main(sys.argv[1:])