labours.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import argparse
  2. from datetime import datetime, timedelta
  3. import io
  4. import os
  5. import sys
  6. import tempfile
  7. import warnings
  8. try:
  9. from clint.textui import progress
  10. except ImportError:
  11. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  12. progress = None
  13. import numpy
  14. import yaml
  15. if sys.version_info[0] < 3:
  16. # OK, ancients, I will support Python 2, but you owe me a beer
  17. input = raw_input
  18. def parse_args():
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument("-o", "--output", default="",
  21. help="Path to the output file/directory (empty for display).")
  22. parser.add_argument("-i", "--input", default="-",
  23. help="Path to the input file (- for stdin).")
  24. parser.add_argument("--text-size", default=12, type=int,
  25. help="Size of the labels and legend.")
  26. parser.add_argument("--backend", help="Matplotlib backend to use.")
  27. parser.add_argument("--style", choices=["black", "white"], default="black",
  28. help="Plot's general color scheme.")
  29. parser.add_argument("--relative", action="store_true",
  30. help="Occupy 100%% height for every measurement.")
  31. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  32. parser.add_argument("-m", "--mode",
  33. choices=["project", "file", "person", "matrix", "people", "couples",
  34. "all"],
  35. default="project", help="What to plot.")
  36. parser.add_argument(
  37. "--resample", default="year",
  38. help="The way to resample the time series. Possible values are: "
  39. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  40. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  41. "#offset-aliases).")
  42. args = parser.parse_args()
  43. return args
  44. def read_input(args):
  45. sys.stdout.write("Reading the input... ")
  46. sys.stdout.flush()
  47. if args.input != "-":
  48. with open(args.input) as fin:
  49. data = yaml.load(fin)
  50. else:
  51. data = yaml.load(sys.stdin)
  52. print("done")
  53. return data["burndown"], data["project"], data.get("files"), data.get("people_sequence"), \
  54. data.get("people"), data.get("people_interaction"), data.get("files_coocc"), \
  55. data.get("people_coocc")
  56. def calculate_average_lifetime(matrix):
  57. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  58. for band in matrix:
  59. start = 0
  60. for i, line in enumerate(band):
  61. if i == 0 or band[i - 1] == 0:
  62. start += 1
  63. continue
  64. lifetimes[i - start] = band[i - 1] - line
  65. lifetimes[i - start] = band[i - 1]
  66. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  67. / (lifetimes.sum() * matrix.shape[1]))
  68. def load_main(header, name, matrix, resample):
  69. import pandas
  70. start = header["begin"]
  71. last = header["end"]
  72. granularity = header["granularity"]
  73. sampling = header["sampling"]
  74. start = datetime.fromtimestamp(int(start))
  75. last = datetime.fromtimestamp(int(last))
  76. granularity = int(granularity)
  77. sampling = int(sampling)
  78. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  79. for line in matrix.split("\n")]).T
  80. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  81. finish = start + timedelta(days=matrix.shape[1] * sampling)
  82. if resample not in ("no", "raw"):
  83. # Interpolate the day x day matrix.
  84. # Each day brings equal weight in the granularity.
  85. # Sampling's interpolation is linear.
  86. daily_matrix = numpy.zeros(
  87. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  88. dtype=numpy.float32)
  89. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  90. for y in range(matrix.shape[0]):
  91. for x in range(matrix.shape[1]):
  92. previous = matrix[y, x - 1] if x > 0 else 0
  93. value = ((previous + (matrix[y, x] - previous) * epsrange)
  94. / granularity)[numpy.newaxis, :]
  95. if (y + 1) * granularity <= x * sampling:
  96. daily_matrix[y * granularity:(y + 1) * granularity,
  97. x * sampling:(x + 1) * sampling] = value
  98. elif y * granularity <= (x + 1) * sampling:
  99. for suby in range(y * granularity, (y + 1) * granularity):
  100. for subx in range(suby, (x + 1) * sampling):
  101. daily_matrix[suby, subx] = matrix[
  102. y, x] / granularity
  103. daily_matrix[(last - start).days:] = 0
  104. # Resample the bands
  105. aliases = {
  106. "year": "A",
  107. "month": "M"
  108. }
  109. resample = aliases.get(resample, resample)
  110. periods = 0
  111. date_granularity_sampling = [start]
  112. while date_granularity_sampling[-1] < finish:
  113. periods += 1
  114. date_granularity_sampling = pandas.date_range(
  115. start, periods=periods, freq=resample)
  116. date_range_sampling = pandas.date_range(
  117. date_granularity_sampling[0],
  118. periods=(finish - date_granularity_sampling[0]).days,
  119. freq="1D")
  120. # Fill the new square matrix
  121. matrix = numpy.zeros(
  122. (len(date_granularity_sampling), len(date_range_sampling)),
  123. dtype=numpy.float32)
  124. for i, gdt in enumerate(date_granularity_sampling):
  125. istart = (date_granularity_sampling[i - 1] - start).days \
  126. if i > 0 else 0
  127. ifinish = (gdt - start).days
  128. for j, sdt in enumerate(date_range_sampling):
  129. if (sdt - start).days >= istart:
  130. break
  131. matrix[i, j:] = \
  132. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  133. # Hardcode some cases to improve labels" readability
  134. if resample in ("year", "A"):
  135. labels = [dt.year for dt in date_granularity_sampling]
  136. elif resample in ("month", "M"):
  137. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  138. else:
  139. labels = [dt.date() for dt in date_granularity_sampling]
  140. else:
  141. labels = [
  142. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  143. (
  144. start + timedelta(days=(i + 1) * granularity)).date())
  145. for i in range(matrix.shape[0])]
  146. if len(labels) > 18:
  147. warnings.warn("Too many labels - consider resampling.")
  148. resample = "M" # fake resampling type is checked while plotting
  149. date_range_sampling = pandas.date_range(
  150. start + timedelta(days=sampling), periods=matrix.shape[1],
  151. freq="%dD" % sampling)
  152. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  153. def load_matrix(contents):
  154. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  155. for line in contents.split("\n")])
  156. return matrix
  157. def load_people(header, sequence, contents):
  158. import pandas
  159. start = header["begin"]
  160. last = header["end"]
  161. sampling = header["sampling"]
  162. start = datetime.fromtimestamp(int(start))
  163. last = datetime.fromtimestamp(int(last))
  164. sampling = int(sampling)
  165. people = []
  166. for name in sequence:
  167. people.append(numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  168. for line in contents[name].split("\n")]).sum(axis=1))
  169. people = numpy.array(people)
  170. date_range_sampling = pandas.date_range(
  171. start + timedelta(days=sampling), periods=people[0].shape[0],
  172. freq="%dD" % sampling)
  173. return sequence, people, date_range_sampling, last
  174. def apply_plot_style(figure, axes, legend, style, text_size):
  175. figure.set_size_inches(12, 9)
  176. for side in ("bottom", "top", "left", "right"):
  177. axes.spines[side].set_color(style)
  178. for axis in (axes.xaxis, axes.yaxis):
  179. axis.label.update(dict(fontsize=text_size, color=style))
  180. for axis in ("x", "y"):
  181. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  182. if legend is not None:
  183. frame = legend.get_frame()
  184. for setter in (frame.set_facecolor, frame.set_edgecolor):
  185. setter("black" if style == "white" else "white")
  186. for text in legend.get_texts():
  187. text.set_color(style)
  188. def get_plot_path(base, name):
  189. root, ext = os.path.splitext(base)
  190. if not ext:
  191. ext = ".png"
  192. output = os.path.join(root, name + ext)
  193. os.makedirs(os.path.dirname(output), exist_ok=True)
  194. return output
  195. def deploy_plot(title, output, style):
  196. import matplotlib.pyplot as pyplot
  197. if not output:
  198. pyplot.gcf().canvas.set_window_title(title)
  199. pyplot.show()
  200. else:
  201. if title:
  202. pyplot.title(title, color=style)
  203. pyplot.tight_layout()
  204. pyplot.savefig(output, transparent=True)
  205. pyplot.clf()
  206. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  207. sampling, resample):
  208. import matplotlib
  209. if args.backend:
  210. matplotlib.use(args.backend)
  211. import matplotlib.pyplot as pyplot
  212. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  213. if args.relative:
  214. for i in range(matrix.shape[1]):
  215. matrix[:, i] /= matrix[:, i].sum()
  216. pyplot.ylim(0, 1)
  217. legend_loc = 3
  218. else:
  219. legend_loc = 2
  220. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  221. pyplot.ylabel("Lines of code")
  222. pyplot.xlabel("Time")
  223. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  224. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  225. locator = pyplot.gca().xaxis.get_major_locator()
  226. # set the optimal xticks locator
  227. if "M" not in resample:
  228. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  229. locs = pyplot.gca().get_xticks().tolist()
  230. if len(locs) >= 16:
  231. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  232. locs = pyplot.gca().get_xticks().tolist()
  233. if len(locs) >= 16:
  234. pyplot.gca().xaxis.set_major_locator(locator)
  235. if locs[0] < pyplot.xlim()[0]:
  236. del locs[0]
  237. endindex = -1
  238. if len(locs) >= 2 and \
  239. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  240. locs.append(pyplot.xlim()[1])
  241. endindex = len(locs) - 1
  242. startindex = -1
  243. if len(locs) >= 2 and \
  244. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  245. locs.append(pyplot.xlim()[0])
  246. startindex = len(locs) - 1
  247. pyplot.gca().set_xticks(locs)
  248. # hacking time!
  249. labels = pyplot.gca().get_xticklabels()
  250. if startindex >= 0:
  251. labels[startindex].set_text(date_range_sampling[0].date())
  252. labels[startindex].set_text = lambda _: None
  253. labels[startindex].set_rotation(30)
  254. labels[startindex].set_ha("right")
  255. if endindex >= 0:
  256. labels[endindex].set_text(date_range_sampling[-1].date())
  257. labels[endindex].set_text = lambda _: None
  258. labels[endindex].set_rotation(30)
  259. labels[endindex].set_ha("right")
  260. title = "%s %d x %d (granularity %d, sampling %d)" % \
  261. ((name,) + matrix.shape + (granularity, sampling))
  262. output = args.output
  263. if output:
  264. if args.mode == "project" and target == "project":
  265. output = args.output
  266. else:
  267. if target == "project":
  268. name = "project"
  269. output = get_plot_path(args.output, name)
  270. deploy_plot(title, output, args.style)
  271. def plot_many(args, target, header, parts):
  272. if not args.output:
  273. print("Warning: output not set, showing %d plots." % len(parts))
  274. itercnt = progress.bar(parts.items(), expected_size=len(parts)) \
  275. if progress is not None else parts.items()
  276. stdout = io.StringIO()
  277. for name, matrix in itercnt:
  278. backup = sys.stdout
  279. sys.stdout = stdout
  280. plot_burndown(args, target, *load_main(header, name, matrix, args.resample))
  281. sys.stdout = backup
  282. sys.stdout.write(stdout.getvalue())
  283. def plot_matrix(args, repo, people, matrix):
  284. matrix = matrix.astype(float)
  285. zeros = matrix[:, 0] == 0
  286. matrix[zeros, :] = 1
  287. matrix /= matrix[:, 0][:, None]
  288. matrix = -matrix[:, 1:]
  289. matrix[zeros, :] = 0
  290. import matplotlib
  291. if args.backend:
  292. matplotlib.use(args.backend)
  293. import matplotlib.pyplot as pyplot
  294. s = 4 + matrix.shape[1] * 0.3
  295. fig = pyplot.figure(figsize=(s, s))
  296. ax = fig.add_subplot(111)
  297. ax.xaxis.set_label_position("top")
  298. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  299. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  300. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  301. ax.set_xticklabels(["Unidentified"] + people, rotation=90, ha="center")
  302. ax.set_yticklabels(people, va="center")
  303. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  304. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  305. ax.grid(which="minor")
  306. apply_plot_style(fig, ax, None, args.style, args.text_size)
  307. if not args.output:
  308. pos1 = ax.get_position()
  309. pos2 = (pos1.x0 + 0.245, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  310. ax.set_position(pos2)
  311. if args.mode == "all":
  312. output = get_plot_path(args.output, "matrix")
  313. else:
  314. output = args.output
  315. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  316. if args.output:
  317. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  318. title = ""
  319. deploy_plot(title, output, args.style)
  320. def plot_people(args, repo, names, people, date_range, last):
  321. import matplotlib
  322. if args.backend:
  323. matplotlib.use(args.backend)
  324. import matplotlib.pyplot as pyplot
  325. pyplot.stackplot(date_range, people, labels=names)
  326. pyplot.xlim(date_range[0], last)
  327. if args.relative:
  328. for i in range(people.shape[1]):
  329. people[:, i] /= people[:, i].sum()
  330. pyplot.ylim(0, 1)
  331. legend_loc = 3
  332. else:
  333. legend_loc = 2
  334. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  335. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  336. if args.mode == "all":
  337. output = get_plot_path(args.output, "people")
  338. else:
  339. output = args.output
  340. deploy_plot("%s code ratio through time" % repo, output, args.style)
  341. def train_embeddings(coocc_tree, tmpdir, shard_size=4096):
  342. from scipy.sparse import csr_matrix
  343. import tensorflow as tf
  344. try:
  345. from . import swivel
  346. except SystemError:
  347. import swivel
  348. index = coocc_tree["index"]
  349. print("Reading the sparse matrix...")
  350. data = []
  351. indices = []
  352. indptr = [0]
  353. for row, cd in enumerate(coocc_tree["matrix"]):
  354. for col, val in sorted(cd.items()):
  355. data.append(val)
  356. indices.append(col)
  357. indptr.append(indptr[-1] + len(cd))
  358. matrix = csr_matrix((data, indices, indptr), shape=(len(index), len(index)))
  359. meta_index = []
  360. for i, name in enumerate(index):
  361. meta_index.append((name, matrix[i, i]))
  362. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  363. print("Writing Swivel metadata...")
  364. vocabulary = "\n".join(index)
  365. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  366. out.write(vocabulary)
  367. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  368. out.write(vocabulary)
  369. del vocabulary
  370. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  371. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  372. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  373. out.write(bool_sums_str)
  374. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  375. out.write(bool_sums_str)
  376. del bool_sums_str
  377. reorder = numpy.argsort(-bool_sums)
  378. nshards = len(index) // shard_size
  379. if nshards == 0:
  380. nshards = 1
  381. shard_size = len(index)
  382. print("Writing Swivel shards...")
  383. for row in range(nshards):
  384. for col in range(nshards):
  385. def _int64s(xs):
  386. return tf.train.Feature(
  387. int64_list=tf.train.Int64List(value=list(xs)))
  388. def _floats(xs):
  389. return tf.train.Feature(
  390. float_list=tf.train.FloatList(value=list(xs)))
  391. indices_row = reorder[row::nshards]
  392. indices_col = reorder[col::nshards]
  393. shard = matrix[indices_row][:, indices_col].tocoo()
  394. example = tf.train.Example(features=tf.train.Features(feature={
  395. "global_row": _int64s(indices_row),
  396. "global_col": _int64s(indices_col),
  397. "sparse_local_row": _int64s(shard.row),
  398. "sparse_local_col": _int64s(shard.col),
  399. "sparse_value": _floats(shard.data)}))
  400. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  401. out.write(example.SerializeToString())
  402. print("Training Swivel model...")
  403. swivel.FLAGS.submatrix_rows = shard_size
  404. swivel.FLAGS.submatrix_cols = shard_size
  405. if len(index) < 10000:
  406. embedding_size = 50
  407. num_epochs = 40
  408. elif len(index) < 100000:
  409. embedding_size = 100
  410. num_epochs = 50
  411. elif len(index) < 500000:
  412. embedding_size = 200
  413. num_epochs = 60
  414. else:
  415. embedding_size = 300
  416. num_epochs = 80
  417. swivel.FLAGS.embedding_size = embedding_size
  418. swivel.FLAGS.input_base_path = tmproot
  419. swivel.FLAGS.output_base_path = tmproot
  420. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  421. swivel.FLAGS.num_epochs = num_epochs
  422. swivel.main(None)
  423. print("Reading Swivel embeddings...")
  424. embeddings = []
  425. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  426. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  427. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  428. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  429. assert prow[0] == pcol[0]
  430. erow, ecol = \
  431. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  432. for p in (prow, pcol))
  433. embeddings.append((erow + ecol) / 2)
  434. return meta_index, embeddings
  435. def write_embeddings(name, output, index, embeddings):
  436. print("Writing Tensorflow Projector files...")
  437. if not output:
  438. output = "couples_" + name
  439. metaf = "%s_%s_meta.tsv" % (output, name)
  440. with open(metaf, "w") as fout:
  441. fout.write("name\tcommits\n")
  442. for pair in index:
  443. fout.write("%s\t%s\n" % pair)
  444. print("Wrote", metaf)
  445. dataf = "%s_%s_data.tsv" % (output, name)
  446. with open(dataf, "w") as fout:
  447. for vec in embeddings:
  448. fout.write("\t".join(str(v) for v in vec))
  449. fout.write("\n")
  450. print("Wrote", dataf)
  451. def main():
  452. args = parse_args()
  453. header, main_contents, files_contents, people_sequence, people_contents, people_matrix, \
  454. files_coocc, people_coocc = read_input(args)
  455. name = next(iter(main_contents))
  456. files_warning = "Files stats were not collected. Re-run hercules with -files."
  457. people_warning = "People stats were not collected. Re-run hercules with -people."
  458. if args.mode == "project":
  459. plot_burndown(args, "project",
  460. *load_main(header, name, main_contents[name], args.resample))
  461. elif args.mode == "file":
  462. if not files_contents:
  463. print(files_warning)
  464. return
  465. plot_many(args, "file", header, files_contents)
  466. elif args.mode == "person":
  467. if not people_contents:
  468. print(people_warning)
  469. return
  470. plot_many(args, "person", header, people_contents)
  471. elif args.mode == "matrix":
  472. if not people_contents:
  473. print(people_warning)
  474. return
  475. plot_matrix(args, name, people_sequence, load_matrix(people_matrix))
  476. elif args.mode == "people":
  477. if not people_contents:
  478. print(people_warning)
  479. return
  480. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  481. elif args.mode == "couples":
  482. write_embeddings("files", args.output,
  483. *train_embeddings(files_coocc, args.couples_tmp_dir))
  484. write_embeddings("people", args.output,
  485. *train_embeddings(people_coocc, args.couples_tmp_dir))
  486. elif args.mode == "all":
  487. plot_burndown(args, "project",
  488. *load_main(header, name, main_contents[name], args.resample))
  489. if files_contents:
  490. plot_many(args, "file", header, files_contents)
  491. if people_contents:
  492. plot_many(args, "person", header, people_contents)
  493. plot_matrix(args, name, people_sequence, load_matrix(people_matrix))
  494. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  495. if people_coocc:
  496. assert files_coocc
  497. write_embeddings("files", args.output,
  498. *train_embeddings(files_coocc, args.couples_tmp_dir))
  499. write_embeddings("people", args.output,
  500. *train_embeddings(people_coocc, args.couples_tmp_dir))
  501. if __name__ == "__main__":
  502. sys.exit(main())