labours.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import argparse
  2. from datetime import datetime, timedelta
  3. import io
  4. import os
  5. import sys
  6. import warnings
  7. try:
  8. from clint.textui import progress
  9. except ImportError:
  10. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  11. progress = None
  12. import numpy
  13. if sys.version_info[0] < 3:
  14. # OK, ancients, I will support Python 2, but you owe me a beer
  15. input = raw_input
  16. def parse_args():
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument("-o", "--output", default="",
  19. help="Path to the output file/directory (empty for display).")
  20. parser.add_argument("-i", "--input", default="-",
  21. help="Path to the input file (- for stdin).")
  22. parser.add_argument("--text-size", default=12, type=int,
  23. help="Size of the labels and legend.")
  24. parser.add_argument("--backend", help="Matplotlib backend to use.")
  25. parser.add_argument("--style", choices=["black", "white"], default="black",
  26. help="Plot's general color scheme.")
  27. parser.add_argument("--relative", action="store_true",
  28. help="Occupy 100%% height for every measurement.")
  29. parser.add_argument("-m", "--mode",
  30. choices=["project", "file", "person", "matrix", "people", "all"],
  31. default="project", help="What to plot.")
  32. parser.add_argument(
  33. "--resample", default="year",
  34. help="The way to resample the time series. Possible values are: "
  35. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  36. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  37. "#offset-aliases).")
  38. args = parser.parse_args()
  39. return args
  40. def read_input(args):
  41. main_contents = []
  42. files_contents = []
  43. people_contents = []
  44. if args.input != "-":
  45. with open(args.input) as fin:
  46. header = fin.readline()[:-1]
  47. contents = fin.readlines()
  48. else:
  49. header = input()
  50. contents = sys.stdin.readlines()
  51. for i, line in enumerate(contents):
  52. if line not in ("files\n", "people\n"):
  53. main_contents.append(line)
  54. else:
  55. break
  56. if i < len(contents) and contents[i] == "files\n":
  57. i += 1
  58. while i < len(contents) and contents[i] != "people\n":
  59. files_contents.append(contents[i:i + len(main_contents)])
  60. i += len(main_contents)
  61. if i < len(contents) and contents[i] == "people\n":
  62. i += 1
  63. while contents[i] != "\n":
  64. people_contents.append(contents[i:i + len(main_contents)])
  65. i += len(main_contents)
  66. people_contents.append(contents[i + 1:])
  67. return header, main_contents, files_contents, people_contents
  68. def calculate_average_lifetime(matrix):
  69. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  70. for band in matrix:
  71. start = 0
  72. for i, line in enumerate(band):
  73. if i == 0 or band[i - 1] == 0:
  74. start += 1
  75. continue
  76. lifetimes[i - start] = band[i - 1] - line
  77. lifetimes[i - start] = band[i - 1]
  78. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  79. / (lifetimes.sum() * matrix.shape[1]))
  80. def load_main(header, contents, resample):
  81. import pandas
  82. start, last, granularity, sampling = header.split()
  83. start = datetime.fromtimestamp(int(start))
  84. last = datetime.fromtimestamp(int(last))
  85. granularity = int(granularity)
  86. sampling = int(sampling)
  87. name = contents[0][:-1]
  88. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  89. for line in contents[1:]]).T
  90. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  91. finish = start + timedelta(days=matrix.shape[1] * sampling)
  92. if resample not in ("no", "raw"):
  93. # Interpolate the day x day matrix.
  94. # Each day brings equal weight in the granularity.
  95. # Sampling's interpolation is linear.
  96. daily_matrix = numpy.zeros(
  97. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  98. dtype=numpy.float32)
  99. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  100. for y in range(matrix.shape[0]):
  101. for x in range(matrix.shape[1]):
  102. previous = matrix[y, x - 1] if x > 0 else 0
  103. value = ((previous + (matrix[y, x] - previous) * epsrange)
  104. / granularity)[numpy.newaxis, :]
  105. if (y + 1) * granularity <= x * sampling:
  106. daily_matrix[y * granularity:(y + 1) * granularity,
  107. x * sampling:(x + 1) * sampling] = value
  108. elif y * granularity <= (x + 1) * sampling:
  109. for suby in range(y * granularity, (y + 1) * granularity):
  110. for subx in range(suby, (x + 1) * sampling):
  111. daily_matrix[suby, subx] = matrix[
  112. y, x] / granularity
  113. daily_matrix[(last - start).days:] = 0
  114. # Resample the bands
  115. aliases = {
  116. "year": "A",
  117. "month": "M"
  118. }
  119. resample = aliases.get(resample, resample)
  120. periods = 0
  121. date_granularity_sampling = [start]
  122. while date_granularity_sampling[-1] < finish:
  123. periods += 1
  124. date_granularity_sampling = pandas.date_range(
  125. start, periods=periods, freq=resample)
  126. date_range_sampling = pandas.date_range(
  127. date_granularity_sampling[0],
  128. periods=(finish - date_granularity_sampling[0]).days,
  129. freq="1D")
  130. # Fill the new square matrix
  131. matrix = numpy.zeros(
  132. (len(date_granularity_sampling), len(date_range_sampling)),
  133. dtype=numpy.float32)
  134. for i, gdt in enumerate(date_granularity_sampling):
  135. istart = (date_granularity_sampling[i - 1] - start).days \
  136. if i > 0 else 0
  137. ifinish = (gdt - start).days
  138. for j, sdt in enumerate(date_range_sampling):
  139. if (sdt - start).days >= istart:
  140. break
  141. matrix[i, j:] = \
  142. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  143. # Hardcode some cases to improve labels" readability
  144. if resample in ("year", "A"):
  145. labels = [dt.year for dt in date_granularity_sampling]
  146. elif resample in ("month", "M"):
  147. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  148. else:
  149. labels = [dt.date() for dt in date_granularity_sampling]
  150. else:
  151. labels = [
  152. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  153. (
  154. start + timedelta(days=(i + 1) * granularity)).date())
  155. for i in range(matrix.shape[0])]
  156. if len(labels) > 18:
  157. warnings.warn("Too many labels - consider resampling.")
  158. resample = "M" # fake resampling type is checked while plotting
  159. date_range_sampling = pandas.date_range(
  160. start + timedelta(days=sampling), periods=matrix.shape[1],
  161. freq="%dD" % sampling)
  162. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  163. def load_matrix(contents):
  164. size = len(contents) - 1
  165. people = []
  166. for i, block in enumerate(contents[:-1]):
  167. people.append(block[0].split(": ", 1)[1])
  168. matrix = numpy.array([[int(p) for p in l[:-1].split()]
  169. for l in contents[-1][-size - 1:] if l[:-1]],
  170. dtype=int)
  171. return matrix, people
  172. def load_people(header, contents):
  173. import pandas
  174. start, last, granularity, sampling = header.split()
  175. start = datetime.fromtimestamp(int(start))
  176. sampling = int(sampling)
  177. people = []
  178. names = []
  179. for lines in contents[:-1]:
  180. names.append(lines[0])
  181. people.append(numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  182. for line in lines[1:]]).sum(axis=1))
  183. people = numpy.array(people)
  184. date_range_sampling = pandas.date_range(
  185. start + timedelta(days=sampling), periods=people[0].shape[0],
  186. freq="%dD" % sampling)
  187. return names, people, date_range_sampling
  188. def apply_plot_style(figure, axes, legend, style, text_size):
  189. figure.set_size_inches(12, 9)
  190. for side in ("bottom", "top", "left", "right"):
  191. axes.spines[side].set_color(style)
  192. for axis in (axes.xaxis, axes.yaxis):
  193. axis.label.update(dict(fontsize=text_size, color=style))
  194. for axis in ("x", "y"):
  195. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  196. if legend is not None:
  197. frame = legend.get_frame()
  198. for setter in (frame.set_facecolor, frame.set_edgecolor):
  199. setter("black" if style == "white" else "white")
  200. for text in legend.get_texts():
  201. text.set_color(style)
  202. def get_plot_path(base, name):
  203. root, ext = os.path.splitext(base)
  204. if not ext:
  205. ext = ".png"
  206. output = os.path.join(root, name + ext)
  207. os.makedirs(os.path.dirname(output), exist_ok=True)
  208. return output
  209. def deploy_plot(title, output, style):
  210. import matplotlib.pyplot as pyplot
  211. if not output:
  212. pyplot.gcf().canvas.set_window_title(title)
  213. pyplot.show()
  214. else:
  215. if title:
  216. pyplot.title(title, color=style)
  217. pyplot.tight_layout()
  218. pyplot.savefig(output, transparent=True)
  219. pyplot.clf()
  220. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  221. sampling, resample):
  222. import matplotlib
  223. if args.backend:
  224. matplotlib.use(args.backend)
  225. import matplotlib.pyplot as pyplot
  226. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  227. if args.relative:
  228. for i in range(matrix.shape[1]):
  229. matrix[:, i] /= matrix[:, i].sum()
  230. pyplot.ylim(0, 1)
  231. legend_loc = 3
  232. else:
  233. legend_loc = 2
  234. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  235. pyplot.ylabel("Lines of code")
  236. pyplot.xlabel("Time")
  237. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  238. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  239. locator = pyplot.gca().xaxis.get_major_locator()
  240. # set the optimal xticks locator
  241. if "M" not in resample:
  242. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  243. locs = pyplot.gca().get_xticks().tolist()
  244. if len(locs) >= 16:
  245. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  246. locs = pyplot.gca().get_xticks().tolist()
  247. if len(locs) >= 16:
  248. pyplot.gca().xaxis.set_major_locator(locator)
  249. if locs[0] < pyplot.xlim()[0]:
  250. del locs[0]
  251. endindex = -1
  252. if len(locs) >= 2 and \
  253. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  254. locs.append(pyplot.xlim()[1])
  255. endindex = len(locs) - 1
  256. startindex = -1
  257. if len(locs) >= 2 and \
  258. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  259. locs.append(pyplot.xlim()[0])
  260. startindex = len(locs) - 1
  261. pyplot.gca().set_xticks(locs)
  262. # hacking time!
  263. labels = pyplot.gca().get_xticklabels()
  264. if startindex >= 0:
  265. labels[startindex].set_text(date_range_sampling[0].date())
  266. labels[startindex].set_text = lambda _: None
  267. labels[startindex].set_rotation(30)
  268. labels[startindex].set_ha("right")
  269. if endindex >= 0:
  270. labels[endindex].set_text(date_range_sampling[-1].date())
  271. labels[endindex].set_text = lambda _: None
  272. labels[endindex].set_rotation(30)
  273. labels[endindex].set_ha("right")
  274. title = "%s %d x %d (granularity %d, sampling %d)" % \
  275. ((name,) + matrix.shape + (granularity, sampling))
  276. output = args.output
  277. if output:
  278. if args.mode == "project" and target == "project":
  279. output = args.output
  280. else:
  281. if target == "project":
  282. name = "project"
  283. output = get_plot_path(args.output, name)
  284. deploy_plot(title, output, args.style)
  285. def plot_many(args, target, header, parts):
  286. if not args.output:
  287. print("Warning: output not set, showing %d plots." % len(parts))
  288. itercnt = progress.bar(parts, expected_size=len(parts)) \
  289. if progress is not None else parts
  290. stdout = io.StringIO()
  291. for fc in itercnt:
  292. backup = sys.stdout
  293. sys.stdout = stdout
  294. plot_burndown(args, target, *load_main(header, fc, args.resample))
  295. sys.stdout = backup
  296. sys.stdout.write(stdout.getvalue())
  297. def plot_matrix(args, repo, matrix, people):
  298. matrix = matrix.astype(float)
  299. zeros = matrix[:, 0] == 0
  300. matrix[zeros, :] = 1
  301. matrix /= matrix[:, 0][:, None]
  302. matrix = -matrix[:, 1:]
  303. matrix[zeros, :] = 0
  304. import matplotlib
  305. if args.backend:
  306. matplotlib.use(args.backend)
  307. import matplotlib.pyplot as pyplot
  308. s = 4 + matrix.shape[1] * 0.3
  309. fig = pyplot.figure(figsize=(s, s))
  310. ax = fig.add_subplot(111)
  311. ax.xaxis.set_label_position("top")
  312. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  313. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  314. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  315. ax.set_xticklabels(["Unidentified"] + people, rotation=90, ha="center")
  316. ax.set_yticklabels(people, va="center")
  317. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  318. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  319. ax.grid(which="minor")
  320. apply_plot_style(fig, ax, None, args.style, args.text_size)
  321. if not args.output:
  322. pos1 = ax.get_position()
  323. pos2 = (pos1.x0 + 0.245, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  324. ax.set_position(pos2)
  325. if args.mode == "all":
  326. output = get_plot_path(args.output, "matrix")
  327. else:
  328. output = args.output
  329. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  330. if args.output:
  331. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  332. title = ""
  333. deploy_plot(title, output, args.style)
  334. def plot_people(args, repo, names, people, date_range):
  335. import matplotlib
  336. if args.backend:
  337. matplotlib.use(args.backend)
  338. import matplotlib.pyplot as pyplot
  339. pyplot.stackplot(date_range, people, labels=names)
  340. if args.relative:
  341. for i in range(people.shape[1]):
  342. people[:, i] /= people[:, i].sum()
  343. pyplot.ylim(0, 1)
  344. legend_loc = 3
  345. else:
  346. legend_loc = 2
  347. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  348. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  349. if args.mode == "all":
  350. output = get_plot_path(args.output, "people")
  351. else:
  352. output = args.output
  353. deploy_plot("%s code ratio through time" % repo, output, args.style)
  354. def main():
  355. args = parse_args()
  356. header, main_contents, files_contents, people_contents = read_input(args)
  357. name = main_contents[0][:-1]
  358. files_warning = "Files stats were not collected. Re-run hercules with -files."
  359. people_warning = "People stats were not collected. Re-run hercules with -people."
  360. if args.mode == "project":
  361. plot_burndown(args, "project", *load_main(header, main_contents, args.resample))
  362. elif args.mode == "file":
  363. if not files_contents:
  364. print(files_warning)
  365. return
  366. plot_many(args, "file", header, files_contents)
  367. elif args.mode == "person":
  368. if not people_contents:
  369. print(people_warning)
  370. return
  371. plot_many(args, "person", header, people_contents[:-1])
  372. elif args.mode == "matrix":
  373. if not people_contents:
  374. print(people_warning)
  375. return
  376. plot_matrix(args, name, *load_matrix(people_contents))
  377. elif args.mode == "people":
  378. if not people_contents:
  379. print(people_warning)
  380. return
  381. plot_people(args, name, *load_people(header, people_contents))
  382. elif args.mode == "all":
  383. plot_burndown(args, "project", *load_main(header, main_contents, args.resample))
  384. if files_contents:
  385. plot_many(args, "file", header, files_contents)
  386. if people_contents:
  387. plot_many(args, "person", header, people_contents[:-1])
  388. plot_matrix(args, name, *load_matrix(people_contents))
  389. plot_people(args, name, *load_people(header, people_contents))
  390. if __name__ == "__main__":
  391. sys.exit(main())