labours.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import argparse
  2. from datetime import datetime, timedelta
  3. import sys
  4. import warnings
  5. import numpy
  6. if sys.version_info[0] < 3:
  7. # OK, ancients, I will support Python 2, but you owe me a beer
  8. input = raw_input
  9. def parse_args():
  10. parser = argparse.ArgumentParser()
  11. parser.add_argument("--output", default="",
  12. help="Path to the output file (empty for display).")
  13. parser.add_argument("--input", default="-",
  14. help="Path to the input file (- for stdin).")
  15. parser.add_argument("--text-size", default=12,
  16. help="Size of the labels and legend.")
  17. parser.add_argument("--backend", help="Matplotlib backend to use.")
  18. parser.add_argument("--style", choices=["black", "white"], default="black",
  19. help="Plot's general color scheme.")
  20. parser.add_argument("--relative", action="store_true",
  21. help="Occupy 100% height for every measurement.")
  22. parser.add_argument(
  23. "--resample", default="year",
  24. help="The way to resample the time series. Possible values are: "
  25. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  26. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  27. "#offset-aliases).")
  28. args = parser.parse_args()
  29. return args
  30. def load_matrix(args):
  31. import pandas
  32. if args.input != "-":
  33. with open(args.input) as fin:
  34. header = fin.readline()[:-1]
  35. contents = fin.read()
  36. else:
  37. header = input()
  38. contents = sys.stdin.read()
  39. start, last, granularity, sampling = header.split()
  40. start = datetime.fromtimestamp(int(start))
  41. last = datetime.fromtimestamp(int(last))
  42. granularity = int(granularity)
  43. sampling = int(sampling)
  44. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  45. for line in contents.split("\n")[:-1]]).T
  46. finish = start + timedelta(days=matrix.shape[1] * sampling)
  47. if args.resample not in ("no", "raw"):
  48. # Interpolate the day x day matrix.
  49. # Each day brings equal weight in the granularity.
  50. # Sampling's interpolation is linear.
  51. daily_matrix = numpy.zeros(
  52. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  53. dtype=numpy.float32)
  54. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  55. for y in range(matrix.shape[0]):
  56. for x in range(matrix.shape[1]):
  57. previous = matrix[y, x - 1] if x > 0 else 0
  58. value = ((previous + (matrix[y, x] - previous) * epsrange)
  59. / granularity)[numpy.newaxis, :]
  60. if (y + 1) * granularity <= x * sampling:
  61. daily_matrix[y * granularity:(y + 1) * granularity,
  62. x * sampling:(x + 1) * sampling] = value
  63. elif y * granularity <= (x + 1) * sampling:
  64. for suby in range(y * granularity, (y + 1) * granularity):
  65. for subx in range(suby, (x + 1) * sampling):
  66. daily_matrix[suby, subx] = matrix[
  67. y, x] / granularity
  68. daily_matrix[(last - start).days:] = 0
  69. # Resample the time interval
  70. aliases = {
  71. "year": "A",
  72. "month": "M"
  73. }
  74. args.resample = aliases.get(args.resample, args.resample)
  75. periods = 0
  76. date_range_sampling = [start]
  77. while date_range_sampling[-1] < finish:
  78. periods += 1
  79. date_range_sampling = pandas.date_range(
  80. start, periods=periods, freq=args.resample)
  81. # Fill the new square matrix
  82. matrix = numpy.zeros((len(date_range_sampling),) * 2,
  83. dtype=numpy.float32)
  84. for i, gdt in enumerate(date_range_sampling):
  85. istart = (date_range_sampling[i - 1] - start).days if i > 0 else 0
  86. ifinish = (gdt - start).days
  87. for j, sdt in enumerate(date_range_sampling[i:]):
  88. jfinish = min((date_range_sampling[i + j] - start).days,
  89. daily_matrix.shape[1] - 1)
  90. matrix[i, i + j] = daily_matrix[istart:ifinish, jfinish].sum()
  91. # Hardcode some cases to improve labels' readability
  92. if args.resample in ("year", "A"):
  93. labels = [dt.year for dt in date_range_sampling]
  94. elif args.resample in ("month", "M"):
  95. labels = [dt.strftime("%Y %B") for dt in date_range_sampling]
  96. else:
  97. labels = [dt.date() for dt in date_range_sampling]
  98. else:
  99. labels = [
  100. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  101. (
  102. start + timedelta(days=(i + 1) * granularity)).date())
  103. for i in range(matrix.shape[0])]
  104. if len(labels) > 18:
  105. warnings.warn("Too many labels - consider resampling.")
  106. args.resample = "M" # fake resampling type is checked while plotting
  107. date_range_sampling = pandas.date_range(
  108. start + timedelta(days=sampling), periods=matrix.shape[1],
  109. freq="%dD" % sampling)
  110. return matrix, date_range_sampling, labels, granularity, sampling
  111. def plot_matrix(args, matrix, date_range_sampling, labels, granularity,
  112. sampling):
  113. import matplotlib
  114. if args.backend:
  115. matplotlib.use(args.backend)
  116. import matplotlib.pyplot as pyplot
  117. if args.style == "white":
  118. pyplot.gca().spines["bottom"].set_color("white")
  119. pyplot.gca().spines["top"].set_color("white")
  120. pyplot.gca().spines["left"].set_color("white")
  121. pyplot.gca().spines["right"].set_color("white")
  122. pyplot.gca().xaxis.label.set_color("white")
  123. pyplot.gca().yaxis.label.set_color("white")
  124. pyplot.gca().tick_params(axis="x", colors="white")
  125. pyplot.gca().tick_params(axis="y", colors="white")
  126. if args.relative:
  127. for i in range(matrix.shape[1]):
  128. matrix[:, i] /= matrix[:, i].sum()
  129. pyplot.ylim(0, 1)
  130. legend_loc = 3
  131. else:
  132. legend_loc = 2
  133. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  134. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  135. frame = legend.get_frame()
  136. frame.set_facecolor("black" if args.style == "white" else "white")
  137. frame.set_edgecolor("black" if args.style == "white" else "white")
  138. for text in legend.get_texts():
  139. text.set_color(args.style)
  140. pyplot.ylabel("Lines of code", fontsize=args.text_size)
  141. pyplot.xlabel("Time", fontsize=args.text_size)
  142. pyplot.tick_params(labelsize=args.text_size)
  143. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  144. pyplot.gcf().set_size_inches(12, 9)
  145. locator = pyplot.gca().xaxis.get_major_locator()
  146. # set the optimal xticks locator
  147. if "M" not in args.resample:
  148. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  149. locs = pyplot.gca().get_xticks().tolist()
  150. if len(locs) >= 16:
  151. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  152. locs = pyplot.gca().get_xticks().tolist()
  153. if len(locs) >= 16:
  154. pyplot.gca().xaxis.set_major_locator(locator)
  155. if locs[0] < pyplot.xlim()[0]:
  156. del locs[0]
  157. endindex = -1
  158. if len(locs) >= 2 and \
  159. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 3:
  160. locs.append(pyplot.xlim()[1])
  161. endindex = len(locs) - 1
  162. startindex = -1
  163. if len(locs) >= 2 and \
  164. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 3:
  165. locs.append(pyplot.xlim()[0])
  166. startindex = len(locs) - 1
  167. pyplot.gca().set_xticks(locs)
  168. # hacking time!
  169. labels = pyplot.gca().get_xticklabels()
  170. if startindex >= 0:
  171. if "M" in args.resample:
  172. labels[startindex].set_text(date_range_sampling[0].date())
  173. labels[startindex].set_text = lambda _: None
  174. labels[startindex].set_rotation(30)
  175. labels[startindex].set_ha("right")
  176. if endindex >= 0:
  177. if "M" in args.resample:
  178. labels[endindex].set_text(date_range_sampling[-1].date())
  179. labels[endindex].set_text = lambda _: None
  180. labels[endindex].set_rotation(30)
  181. labels[endindex].set_ha("right")
  182. if not args.output:
  183. pyplot.gcf().canvas.set_window_title(
  184. "Hercules %d x %d (granularity %d, sampling %d)" %
  185. (matrix.shape + (granularity, sampling)))
  186. pyplot.show()
  187. else:
  188. pyplot.tight_layout()
  189. pyplot.savefig(args.output, transparent=True)
  190. def main():
  191. args = parse_args()
  192. plot_matrix(args, *load_matrix(args))
  193. if __name__ == "__main__":
  194. sys.exit(main())