labours.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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, type=int,
  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 calculate_average_lifetime(matrix):
  31. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  32. for band in matrix:
  33. start = 0
  34. for i, line in enumerate(band):
  35. if i == 0 or band[i - 1] == 0:
  36. start += 1
  37. continue
  38. lifetimes[i - start] = band[i - 1] - line
  39. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  40. / (lifetimes.sum() * matrix.shape[1]))
  41. def load_matrix(args):
  42. import pandas
  43. if args.input != "-":
  44. with open(args.input) as fin:
  45. header = fin.readline()[:-1]
  46. contents = fin.read()
  47. else:
  48. header = input()
  49. contents = sys.stdin.read()
  50. start, last, granularity, sampling = header.split()
  51. start = datetime.fromtimestamp(int(start))
  52. last = datetime.fromtimestamp(int(last))
  53. granularity = int(granularity)
  54. sampling = int(sampling)
  55. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  56. for line in contents.split("\n")[:-1]]).T
  57. print("Lifetime index:", calculate_average_lifetime(matrix))
  58. finish = start + timedelta(days=matrix.shape[1] * sampling)
  59. if args.resample not in ("no", "raw"):
  60. # Interpolate the day x day matrix.
  61. # Each day brings equal weight in the granularity.
  62. # Sampling's interpolation is linear.
  63. daily_matrix = numpy.zeros(
  64. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  65. dtype=numpy.float32)
  66. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  67. for y in range(matrix.shape[0]):
  68. for x in range(matrix.shape[1]):
  69. previous = matrix[y, x - 1] if x > 0 else 0
  70. value = ((previous + (matrix[y, x] - previous) * epsrange)
  71. / granularity)[numpy.newaxis, :]
  72. if (y + 1) * granularity <= x * sampling:
  73. daily_matrix[y * granularity:(y + 1) * granularity,
  74. x * sampling:(x + 1) * sampling] = value
  75. elif y * granularity <= (x + 1) * sampling:
  76. for suby in range(y * granularity, (y + 1) * granularity):
  77. for subx in range(suby, (x + 1) * sampling):
  78. daily_matrix[suby, subx] = matrix[
  79. y, x] / granularity
  80. daily_matrix[(last - start).days:] = 0
  81. # Resample the bands
  82. aliases = {
  83. "year": "A",
  84. "month": "M"
  85. }
  86. args.resample = aliases.get(args.resample, args.resample)
  87. periods = 0
  88. date_granularity_sampling = [start]
  89. while date_granularity_sampling[-1] < finish:
  90. periods += 1
  91. date_granularity_sampling = pandas.date_range(
  92. start, periods=periods, freq=args.resample)
  93. date_range_sampling = pandas.date_range(
  94. date_granularity_sampling[0],
  95. periods=(finish - date_granularity_sampling[0]).days,
  96. freq="1D")
  97. # Fill the new square matrix
  98. matrix = numpy.zeros(
  99. (len(date_granularity_sampling), len(date_range_sampling)),
  100. dtype=numpy.float32)
  101. for i, gdt in enumerate(date_granularity_sampling):
  102. istart = (date_granularity_sampling[i - 1] - start).days \
  103. if i > 0 else 0
  104. ifinish = (gdt - start).days
  105. for j, sdt in enumerate(date_range_sampling):
  106. if (sdt - start).days >= istart:
  107. break
  108. matrix[i, j:] = \
  109. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  110. # Hardcode some cases to improve labels' readability
  111. if args.resample in ("year", "A"):
  112. labels = [dt.year for dt in date_granularity_sampling]
  113. elif args.resample in ("month", "M"):
  114. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  115. else:
  116. labels = [dt.date() for dt in date_granularity_sampling]
  117. else:
  118. labels = [
  119. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  120. (
  121. start + timedelta(days=(i + 1) * granularity)).date())
  122. for i in range(matrix.shape[0])]
  123. if len(labels) > 18:
  124. warnings.warn("Too many labels - consider resampling.")
  125. args.resample = "M" # fake resampling type is checked while plotting
  126. date_range_sampling = pandas.date_range(
  127. start + timedelta(days=sampling), periods=matrix.shape[1],
  128. freq="%dD" % sampling)
  129. return matrix, date_range_sampling, labels, granularity, sampling
  130. def plot_matrix(args, matrix, date_range_sampling, labels, granularity,
  131. sampling):
  132. import matplotlib
  133. if args.backend:
  134. matplotlib.use(args.backend)
  135. import matplotlib.pyplot as pyplot
  136. if args.style == "white":
  137. pyplot.gca().spines["bottom"].set_color("white")
  138. pyplot.gca().spines["top"].set_color("white")
  139. pyplot.gca().spines["left"].set_color("white")
  140. pyplot.gca().spines["right"].set_color("white")
  141. pyplot.gca().xaxis.label.set_color("white")
  142. pyplot.gca().yaxis.label.set_color("white")
  143. pyplot.gca().tick_params(axis="x", colors="white")
  144. pyplot.gca().tick_params(axis="y", colors="white")
  145. if args.relative:
  146. for i in range(matrix.shape[1]):
  147. matrix[:, i] /= matrix[:, i].sum()
  148. pyplot.ylim(0, 1)
  149. legend_loc = 3
  150. else:
  151. legend_loc = 2
  152. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  153. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  154. frame = legend.get_frame()
  155. frame.set_facecolor("black" if args.style == "white" else "white")
  156. frame.set_edgecolor("black" if args.style == "white" else "white")
  157. for text in legend.get_texts():
  158. text.set_color(args.style)
  159. pyplot.ylabel("Lines of code", fontsize=args.text_size)
  160. pyplot.xlabel("Time", fontsize=args.text_size)
  161. pyplot.tick_params(labelsize=args.text_size)
  162. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  163. pyplot.gcf().set_size_inches(12, 9)
  164. locator = pyplot.gca().xaxis.get_major_locator()
  165. # set the optimal xticks locator
  166. if "M" not in args.resample:
  167. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  168. locs = pyplot.gca().get_xticks().tolist()
  169. if len(locs) >= 16:
  170. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  171. locs = pyplot.gca().get_xticks().tolist()
  172. if len(locs) >= 16:
  173. pyplot.gca().xaxis.set_major_locator(locator)
  174. if locs[0] < pyplot.xlim()[0]:
  175. del locs[0]
  176. endindex = -1
  177. if len(locs) >= 2 and \
  178. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  179. locs.append(pyplot.xlim()[1])
  180. endindex = len(locs) - 1
  181. startindex = -1
  182. if len(locs) >= 2 and \
  183. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  184. locs.append(pyplot.xlim()[0])
  185. startindex = len(locs) - 1
  186. pyplot.gca().set_xticks(locs)
  187. # hacking time!
  188. labels = pyplot.gca().get_xticklabels()
  189. if startindex >= 0:
  190. labels[startindex].set_text(date_range_sampling[0].date())
  191. labels[startindex].set_text = lambda _: None
  192. labels[startindex].set_rotation(30)
  193. labels[startindex].set_ha("right")
  194. if endindex >= 0:
  195. labels[endindex].set_text(date_range_sampling[-1].date())
  196. labels[endindex].set_text = lambda _: None
  197. labels[endindex].set_rotation(30)
  198. labels[endindex].set_ha("right")
  199. if not args.output:
  200. pyplot.gcf().canvas.set_window_title(
  201. "Hercules %d x %d (granularity %d, sampling %d)" %
  202. (matrix.shape + (granularity, sampling)))
  203. pyplot.show()
  204. else:
  205. pyplot.tight_layout()
  206. pyplot.savefig(args.output, transparent=True)
  207. def main():
  208. args = parse_args()
  209. plot_matrix(args, *load_matrix(args))
  210. if __name__ == "__main__":
  211. sys.exit(main())