labours.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. #!/usr/bin/env python3
  2. import argparse
  3. from datetime import datetime, timedelta
  4. import io
  5. import json
  6. import os
  7. import re
  8. import sys
  9. import tempfile
  10. import threading
  11. import time
  12. import warnings
  13. try:
  14. from clint.textui import progress
  15. except ImportError:
  16. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  17. progress = None
  18. import numpy
  19. import yaml
  20. if sys.version_info[0] < 3:
  21. # OK, ancients, I will support Python 2, but you owe me a beer
  22. input = raw_input
  23. def parse_args():
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument("-o", "--output", default="",
  26. help="Path to the output file/directory (empty for display). "
  27. "If the extension is JSON, the data is saved instead of "
  28. "the real image.")
  29. parser.add_argument("-i", "--input", default="-",
  30. help="Path to the input file (- for stdin).")
  31. parser.add_argument("-f", "--input-format", default="yaml", choices=["yaml", "pb"])
  32. parser.add_argument("--text-size", default=12, type=int,
  33. help="Size of the labels and legend.")
  34. parser.add_argument("--backend", help="Matplotlib backend to use.")
  35. parser.add_argument("--style", choices=["black", "white"], default="black",
  36. help="Plot's general color scheme.")
  37. parser.add_argument("--size", help="Axes' size in inches, for example \"12,9\"")
  38. parser.add_argument("--relative", action="store_true",
  39. help="Occupy 100%% height for every measurement.")
  40. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  41. parser.add_argument("-m", "--mode",
  42. choices=["project", "file", "person", "churn_matrix", "ownership", "couples",
  43. "all"],
  44. default="project", help="What to plot.")
  45. parser.add_argument(
  46. "--resample", default="year",
  47. help="The way to resample the time series. Possible values are: "
  48. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  49. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  50. "#offset-aliases).")
  51. parser.add_argument("--disable-projector", action="store_true",
  52. help="Do not run Tensorflow Projector on couples.")
  53. parser.add_argument("--max-people", default=20, type=int,
  54. help="Maximum number of developers in churn matrix and people plots.")
  55. args = parser.parse_args()
  56. return args
  57. class Reader(object):
  58. def read(self, file):
  59. raise NotImplementedError
  60. def get_name(self):
  61. raise NotImplementedError
  62. def get_header(self):
  63. raise NotImplementedError
  64. def get_project_burndown(self):
  65. raise NotImplementedError
  66. def get_files_burndown(self):
  67. raise NotImplementedError
  68. def get_people_burndown(self):
  69. raise NotImplementedError
  70. def get_ownership_burndown(self):
  71. raise NotImplementedError
  72. def get_people_interaction(self):
  73. raise NotImplementedError
  74. def get_files_coocc(self):
  75. raise NotImplementedError
  76. def get_people_coocc(self):
  77. raise NotImplementedError
  78. class YamlReader(Reader):
  79. def read(self, file):
  80. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  81. try:
  82. loader = yaml.CLoader
  83. except AttributeError:
  84. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  85. loader = yaml.Loader
  86. try:
  87. if file != "-":
  88. with open(file) as fin:
  89. data = yaml.load(fin, Loader=loader)
  90. else:
  91. data = yaml.load(sys.stdin, Loader=loader)
  92. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  93. print("\nInvalid unicode in the input: %s\nPlease filter it through "
  94. "fix_yaml_unicode.py" % e)
  95. sys.exit(1)
  96. self.data = data
  97. def get_name(self):
  98. return next(iter(self.data["project"]))
  99. def get_header(self):
  100. header = self.data["burndown"]
  101. return header["begin"], header["end"], header["sampling"], header["granularity"]
  102. def get_project_burndown(self):
  103. name, matrix = next(iter(self.data["project"].items()))
  104. return name, self._parse_burndown_matrix(matrix).T
  105. def get_files_burndown(self):
  106. return [(p[0], self._parse_burndown_matrix(p[1]).T) for p in self.data["files"].items()]
  107. def get_people_burndown(self):
  108. return [(p[0], self._parse_burndown_matrix(p[1]).T) for p in self.data["people"].items()]
  109. def get_ownership_burndown(self):
  110. return self.data["people_sequence"], {p[0]: self._parse_burndown_matrix(p[1])
  111. for p in self.data["people"].items()}
  112. def get_people_interaction(self):
  113. return self.data["people_sequence"], self._parse_burndown_matrix(self.data["people_interaction"])
  114. def get_files_coocc(self):
  115. coocc = self.data["files_coocc"]
  116. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  117. def get_people_coocc(self):
  118. coocc = self.data["people_coocc"]
  119. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  120. def _parse_burndown_matrix(self, matrix):
  121. return numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  122. for line in matrix.split("\n")])
  123. def _parse_coocc_matrix(self, matrix):
  124. from scipy.sparse import csr_matrix
  125. data = []
  126. indices = []
  127. indptr = [0]
  128. for row in matrix:
  129. for k, v in sorted(row.items()):
  130. data.append(v)
  131. indices.append(k)
  132. indptr.append(indptr[-1] + len(row))
  133. return csr_matrix((data, indices, indptr), shape=(len(matrix),) * 2)
  134. class ProtobufReader(Reader):
  135. def read(self, file):
  136. from pb.pb_pb2 import AnalysisResults
  137. self.data = AnalysisResults()
  138. if file != "-":
  139. with open(file, "rb") as fin:
  140. self.data.ParseFromString(fin.read())
  141. else:
  142. self.data.ParseFromString(sys.stdin.buffer.read())
  143. def get_name(self):
  144. return self.data.header.repository
  145. def get_header(self):
  146. header = self.data.header
  147. return header.begin_unix_time, header.end_unix_time, \
  148. header.sampling, header.granularity
  149. def get_project_burndown(self):
  150. return self._parse_burndown_matrix(self.data.burndown_project)
  151. def get_files_burndown(self):
  152. return [self._parse_burndown_matrix(i) for i in self.data.burndown_files]
  153. def get_people_burndown(self):
  154. return [self._parse_burndown_matrix(i) for i in self.data.burndown_developers]
  155. def get_ownership_burndown(self):
  156. people = self.get_people_burndown()
  157. return [p[0] for p in people], {p[0]: p[1].T for p in people}
  158. def get_people_interaction(self):
  159. return [i.name for i in self.data.burndown_developers], \
  160. self._parse_sparse_matrix(self.data.developers_interaction).toarray()
  161. def get_files_coocc(self):
  162. node = self.data.file_couples
  163. return list(node.index), self._parse_sparse_matrix(node.matrix)
  164. def get_people_coocc(self):
  165. node = self.data.developer_couples
  166. return list(node.index), self._parse_sparse_matrix(node.matrix)
  167. def _parse_burndown_matrix(self, matrix):
  168. dense = numpy.zeros((matrix.number_of_rows, matrix.number_of_columns), dtype=int)
  169. for y, row in enumerate(matrix.rows):
  170. for x, col in enumerate(row.columns):
  171. dense[y, x] = col
  172. return matrix.name, dense.T
  173. def _parse_sparse_matrix(self, matrix):
  174. from scipy.sparse import csr_matrix
  175. return csr_matrix((list(matrix.data), list(matrix.indices), list(matrix.indptr)),
  176. shape=(matrix.number_of_rows, matrix.number_of_columns))
  177. READERS = {"yaml": YamlReader, "pb": ProtobufReader}
  178. def read_input(args):
  179. sys.stdout.write("Reading the input... ")
  180. sys.stdout.flush()
  181. reader = READERS[args.input_format]()
  182. reader.read(args.input)
  183. print("done")
  184. return reader
  185. def calculate_average_lifetime(matrix):
  186. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  187. for band in matrix:
  188. start = 0
  189. for i, line in enumerate(band):
  190. if i == 0 or band[i - 1] == 0:
  191. start += 1
  192. continue
  193. lifetimes[i - start] = band[i - 1] - line
  194. lifetimes[i - start] = band[i - 1]
  195. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  196. / (lifetimes.sum() * matrix.shape[1]))
  197. def load_burndown(header, name, matrix, resample):
  198. import pandas
  199. start, last, sampling, granularity = header
  200. start = datetime.fromtimestamp(start)
  201. last = datetime.fromtimestamp(last)
  202. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  203. finish = start + timedelta(days=matrix.shape[1] * sampling)
  204. if resample not in ("no", "raw"):
  205. # Interpolate the day x day matrix.
  206. # Each day brings equal weight in the granularity.
  207. # Sampling's interpolation is linear.
  208. daily_matrix = numpy.zeros(
  209. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  210. dtype=numpy.float32)
  211. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  212. for y in range(matrix.shape[0]):
  213. for x in range(matrix.shape[1]):
  214. previous = matrix[y, x - 1] if x > 0 else 0
  215. value = ((previous + (matrix[y, x] - previous) * epsrange)
  216. / granularity)[numpy.newaxis, :]
  217. if (y + 1) * granularity <= x * sampling:
  218. daily_matrix[y * granularity:(y + 1) * granularity,
  219. x * sampling:(x + 1) * sampling] = value
  220. elif y * granularity <= (x + 1) * sampling:
  221. for suby in range(y * granularity, (y + 1) * granularity):
  222. for subx in range(suby, (x + 1) * sampling):
  223. daily_matrix[suby, subx] = matrix[
  224. y, x] / granularity
  225. daily_matrix[(last - start).days:] = 0
  226. # Resample the bands
  227. aliases = {
  228. "year": "A",
  229. "month": "M"
  230. }
  231. resample = aliases.get(resample, resample)
  232. periods = 0
  233. date_granularity_sampling = [start]
  234. while date_granularity_sampling[-1] < finish:
  235. periods += 1
  236. date_granularity_sampling = pandas.date_range(
  237. start, periods=periods, freq=resample)
  238. date_range_sampling = pandas.date_range(
  239. date_granularity_sampling[0],
  240. periods=(finish - date_granularity_sampling[0]).days,
  241. freq="1D")
  242. # Fill the new square matrix
  243. matrix = numpy.zeros(
  244. (len(date_granularity_sampling), len(date_range_sampling)),
  245. dtype=numpy.float32)
  246. for i, gdt in enumerate(date_granularity_sampling):
  247. istart = (date_granularity_sampling[i - 1] - start).days \
  248. if i > 0 else 0
  249. ifinish = (gdt - start).days
  250. for j, sdt in enumerate(date_range_sampling):
  251. if (sdt - start).days >= istart:
  252. break
  253. matrix[i, j:] = \
  254. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  255. # Hardcode some cases to improve labels" readability
  256. if resample in ("year", "A"):
  257. labels = [dt.year for dt in date_granularity_sampling]
  258. elif resample in ("month", "M"):
  259. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  260. else:
  261. labels = [dt.date() for dt in date_granularity_sampling]
  262. else:
  263. labels = [
  264. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  265. (
  266. start + timedelta(days=(i + 1) * granularity)).date())
  267. for i in range(matrix.shape[0])]
  268. if len(labels) > 18:
  269. warnings.warn("Too many labels - consider resampling.")
  270. resample = "M" # fake resampling type is checked while plotting
  271. date_range_sampling = pandas.date_range(
  272. start + timedelta(days=sampling), periods=matrix.shape[1],
  273. freq="%dD" % sampling)
  274. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  275. def load_ownership(header, sequence, contents, max_people):
  276. import pandas
  277. start, last, sampling, _ = header
  278. start = datetime.fromtimestamp(start)
  279. last = datetime.fromtimestamp(last)
  280. people = []
  281. for name in sequence:
  282. people.append(contents[name].sum(axis=1))
  283. people = numpy.array(people)
  284. date_range_sampling = pandas.date_range(
  285. start + timedelta(days=sampling), periods=people[0].shape[0],
  286. freq="%dD" % sampling)
  287. if people.shape[0] > max_people:
  288. order = numpy.argsort(-people.sum(axis=1))
  289. people = people[order[:max_people]]
  290. sequence = [sequence[i] for i in order[:max_people]]
  291. print("Warning: truncated people to most owning %d" % max_people)
  292. for i, name in enumerate(sequence):
  293. if len(name) > 40:
  294. sequence[i] = name[:37] + "..."
  295. return sequence, people, date_range_sampling, last
  296. def load_churn_matrix(people, matrix, max_people):
  297. matrix = matrix.astype(float)
  298. if matrix.shape[0] > max_people:
  299. order = numpy.argsort(-matrix[:, 0])
  300. matrix = matrix[order[:max_people]][:, [0, 1] + list(2 + order[:max_people])]
  301. people = [people[i] for i in order[:max_people]]
  302. print("Warning: truncated people to most productive %d" % max_people)
  303. zeros = matrix[:, 0] == 0
  304. matrix[zeros, :] = 1
  305. matrix /= matrix[:, 0][:, None]
  306. matrix = -matrix[:, 1:]
  307. matrix[zeros, :] = 0
  308. for i, name in enumerate(people):
  309. if len(name) > 40:
  310. people[i] = name[:37] + "..."
  311. return people, matrix
  312. def apply_plot_style(figure, axes, legend, style, text_size, axes_size):
  313. if axes_size is None:
  314. axes_size = (12, 9)
  315. else:
  316. axes_size = tuple(float(p) for p in axes_size.split(","))
  317. figure.set_size_inches(*axes_size)
  318. for side in ("bottom", "top", "left", "right"):
  319. axes.spines[side].set_color(style)
  320. for axis in (axes.xaxis, axes.yaxis):
  321. axis.label.update(dict(fontsize=text_size, color=style))
  322. for axis in ("x", "y"):
  323. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  324. if legend is not None:
  325. frame = legend.get_frame()
  326. for setter in (frame.set_facecolor, frame.set_edgecolor):
  327. setter("black" if style == "white" else "white")
  328. for text in legend.get_texts():
  329. text.set_color(style)
  330. def get_plot_path(base, name):
  331. root, ext = os.path.splitext(base)
  332. if not ext:
  333. ext = ".png"
  334. output = os.path.join(root, name + ext)
  335. os.makedirs(os.path.dirname(output), exist_ok=True)
  336. return output
  337. def deploy_plot(title, output, style):
  338. import matplotlib.pyplot as pyplot
  339. if not output:
  340. pyplot.gcf().canvas.set_window_title(title)
  341. pyplot.show()
  342. else:
  343. if title:
  344. pyplot.title(title, color=style)
  345. try:
  346. pyplot.tight_layout()
  347. except:
  348. print("Warning: failed to set the tight layout")
  349. pyplot.savefig(output, transparent=True)
  350. pyplot.clf()
  351. def default_json(x):
  352. if hasattr(x, "tolist"):
  353. return x.tolist()
  354. if hasattr(x, "isoformat"):
  355. return x.isoformat()
  356. return x
  357. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  358. sampling, resample):
  359. if args.output and args.output.endswith(".json"):
  360. data = locals().copy()
  361. del data["args"]
  362. data["type"] = "burndown"
  363. if args.mode == "project" and target == "project":
  364. output = args.output
  365. else:
  366. if target == "project":
  367. name = "project"
  368. output = get_plot_path(args.output, name)
  369. with open(output, "w") as fout:
  370. json.dump(data, fout, sort_keys=True, default=default_json)
  371. return
  372. import matplotlib
  373. if args.backend:
  374. matplotlib.use(args.backend)
  375. import matplotlib.pyplot as pyplot
  376. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  377. if args.relative:
  378. for i in range(matrix.shape[1]):
  379. matrix[:, i] /= matrix[:, i].sum()
  380. pyplot.ylim(0, 1)
  381. legend_loc = 3
  382. else:
  383. legend_loc = 2
  384. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  385. pyplot.ylabel("Lines of code")
  386. pyplot.xlabel("Time")
  387. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size, args.size)
  388. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  389. locator = pyplot.gca().xaxis.get_major_locator()
  390. # set the optimal xticks locator
  391. if "M" not in resample:
  392. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  393. locs = pyplot.gca().get_xticks().tolist()
  394. if len(locs) >= 16:
  395. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  396. locs = pyplot.gca().get_xticks().tolist()
  397. if len(locs) >= 16:
  398. pyplot.gca().xaxis.set_major_locator(locator)
  399. if locs[0] < pyplot.xlim()[0]:
  400. del locs[0]
  401. endindex = -1
  402. if len(locs) >= 2 and \
  403. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  404. locs.append(pyplot.xlim()[1])
  405. endindex = len(locs) - 1
  406. startindex = -1
  407. if len(locs) >= 2 and \
  408. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  409. locs.append(pyplot.xlim()[0])
  410. startindex = len(locs) - 1
  411. pyplot.gca().set_xticks(locs)
  412. # hacking time!
  413. labels = pyplot.gca().get_xticklabels()
  414. if startindex >= 0:
  415. labels[startindex].set_text(date_range_sampling[0].date())
  416. labels[startindex].set_text = lambda _: None
  417. labels[startindex].set_rotation(30)
  418. labels[startindex].set_ha("right")
  419. if endindex >= 0:
  420. labels[endindex].set_text(date_range_sampling[-1].date())
  421. labels[endindex].set_text = lambda _: None
  422. labels[endindex].set_rotation(30)
  423. labels[endindex].set_ha("right")
  424. title = "%s %d x %d (granularity %d, sampling %d)" % \
  425. ((name,) + matrix.shape + (granularity, sampling))
  426. output = args.output
  427. if output:
  428. if args.mode == "project" and target == "project":
  429. output = args.output
  430. else:
  431. if target == "project":
  432. name = "project"
  433. output = get_plot_path(args.output, name)
  434. deploy_plot(title, output, args.style)
  435. def plot_many_burndown(args, target, header, parts):
  436. if not args.output:
  437. print("Warning: output not set, showing %d plots." % len(parts))
  438. itercnt = progress.bar(parts, expected_size=len(parts)) \
  439. if progress is not None else parts
  440. stdout = io.StringIO()
  441. for name, matrix in itercnt:
  442. backup = sys.stdout
  443. sys.stdout = stdout
  444. plot_burndown(args, target, *load_burndown(header, name, matrix, args.resample))
  445. sys.stdout = backup
  446. sys.stdout.write(stdout.getvalue())
  447. def plot_churn_matrix(args, repo, people, matrix):
  448. if args.output and args.output.endswith(".json"):
  449. data = locals().copy()
  450. del data["args"]
  451. data["type"] = "churn_matrix"
  452. if args.mode == "all":
  453. output = get_plot_path(args.output, "matrix")
  454. else:
  455. output = args.output
  456. with open(output, "w") as fout:
  457. json.dump(data, fout, sort_keys=True, default=default_json)
  458. return
  459. import matplotlib
  460. if args.backend:
  461. matplotlib.use(args.backend)
  462. import matplotlib.pyplot as pyplot
  463. s = 4 + matrix.shape[1] * 0.3
  464. fig = pyplot.figure(figsize=(s, s))
  465. ax = fig.add_subplot(111)
  466. ax.xaxis.set_label_position("top")
  467. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  468. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  469. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  470. ax.set_xticklabels(["Unidentified"] + people, rotation=90, ha="center")
  471. ax.set_yticklabels(people, va="center")
  472. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  473. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  474. ax.grid(which="minor")
  475. apply_plot_style(fig, ax, None, args.style, args.text_size, args.size)
  476. if not args.output:
  477. pos1 = ax.get_position()
  478. pos2 = (pos1.x0 + 0.245, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  479. ax.set_position(pos2)
  480. if args.mode == "all":
  481. output = get_plot_path(args.output, "matrix")
  482. else:
  483. output = args.output
  484. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  485. if args.output:
  486. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  487. title = ""
  488. deploy_plot(title, output, args.style)
  489. def plot_ownership(args, repo, names, people, date_range, last):
  490. if args.output and args.output.endswith(".json"):
  491. data = locals().copy()
  492. del data["args"]
  493. data["type"] = "ownership"
  494. if args.mode == "all":
  495. output = get_plot_path(args.output, "people")
  496. else:
  497. output = args.output
  498. with open(output, "w") as fout:
  499. json.dump(data, fout, sort_keys=True, default=default_json)
  500. return
  501. import matplotlib
  502. if args.backend:
  503. matplotlib.use(args.backend)
  504. import matplotlib.pyplot as pyplot
  505. pyplot.stackplot(date_range, people, labels=names)
  506. pyplot.xlim(date_range[0], last)
  507. if args.relative:
  508. for i in range(people.shape[1]):
  509. people[:, i] /= people[:, i].sum()
  510. pyplot.ylim(0, 1)
  511. legend_loc = 3
  512. else:
  513. legend_loc = 2
  514. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  515. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size, args.size)
  516. if args.mode == "all":
  517. output = get_plot_path(args.output, "people")
  518. else:
  519. output = args.output
  520. deploy_plot("%s code ownership through time" % repo, output, args.style)
  521. def train_embeddings(index, matrix, tmpdir, shard_size=4096):
  522. try:
  523. from . import swivel
  524. except (SystemError, ImportError):
  525. import swivel
  526. import tensorflow as tf
  527. assert matrix.shape[0] == matrix.shape[1]
  528. assert len(index) <= matrix.shape[0]
  529. nshards = len(index) // shard_size
  530. if nshards * shard_size < len(index):
  531. nshards += 1
  532. shard_size = len(index) // nshards
  533. nshards = len(index) // shard_size
  534. remainder = len(index) - nshards * shard_size
  535. if remainder > 0:
  536. lengths = matrix.indptr[1:] - matrix.indptr[:-1]
  537. filtered = sorted(numpy.argsort(lengths)[remainder:])
  538. else:
  539. filtered = list(range(len(index)))
  540. if len(filtered) < matrix.shape[0]:
  541. print("Truncating the sparse matrix...")
  542. matrix = matrix[filtered, :][:, filtered]
  543. meta_index = []
  544. for i, j in enumerate(filtered):
  545. meta_index.append((index[j], matrix[i, i]))
  546. index = [mi[0] for mi in meta_index]
  547. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  548. print("Writing Swivel metadata...")
  549. vocabulary = "\n".join(index)
  550. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  551. out.write(vocabulary)
  552. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  553. out.write(vocabulary)
  554. del vocabulary
  555. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  556. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  557. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  558. out.write(bool_sums_str)
  559. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  560. out.write(bool_sums_str)
  561. del bool_sums_str
  562. reorder = numpy.argsort(-bool_sums)
  563. print("Writing Swivel shards...")
  564. for row in range(nshards):
  565. for col in range(nshards):
  566. def _int64s(xs):
  567. return tf.train.Feature(
  568. int64_list=tf.train.Int64List(value=list(xs)))
  569. def _floats(xs):
  570. return tf.train.Feature(
  571. float_list=tf.train.FloatList(value=list(xs)))
  572. indices_row = reorder[row::nshards]
  573. indices_col = reorder[col::nshards]
  574. shard = matrix[indices_row][:, indices_col].tocoo()
  575. example = tf.train.Example(features=tf.train.Features(feature={
  576. "global_row": _int64s(indices_row),
  577. "global_col": _int64s(indices_col),
  578. "sparse_local_row": _int64s(shard.row),
  579. "sparse_local_col": _int64s(shard.col),
  580. "sparse_value": _floats(shard.data)}))
  581. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  582. out.write(example.SerializeToString())
  583. print("Training Swivel model...")
  584. swivel.FLAGS.submatrix_rows = shard_size
  585. swivel.FLAGS.submatrix_cols = shard_size
  586. if len(meta_index) < 10000:
  587. embedding_size = 50
  588. num_epochs = 200
  589. elif len(meta_index) < 100000:
  590. embedding_size = 100
  591. num_epochs = 250
  592. elif len(meta_index) < 500000:
  593. embedding_size = 200
  594. num_epochs = 300
  595. else:
  596. embedding_size = 300
  597. num_epochs = 200
  598. swivel.FLAGS.embedding_size = embedding_size
  599. swivel.FLAGS.input_base_path = tmproot
  600. swivel.FLAGS.output_base_path = tmproot
  601. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  602. swivel.FLAGS.num_epochs = num_epochs
  603. swivel.main(None)
  604. print("Reading Swivel embeddings...")
  605. embeddings = []
  606. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  607. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  608. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  609. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  610. assert prow[0] == pcol[0]
  611. erow, ecol = \
  612. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  613. for p in (prow, pcol))
  614. embeddings.append((erow + ecol) / 2)
  615. return meta_index, embeddings
  616. class CORSWebServer(object):
  617. def __init__(self):
  618. self.thread = threading.Thread(target=self.serve)
  619. self.server = None
  620. def serve(self):
  621. outer = self
  622. try:
  623. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  624. except ImportError: # Python 2
  625. from BaseHTTPServer import HTTPServer, test
  626. from SimpleHTTPServer import SimpleHTTPRequestHandler
  627. class ClojureServer(HTTPServer):
  628. def __init__(self, *args, **kwargs):
  629. HTTPServer.__init__(self, *args, **kwargs)
  630. outer.server = self
  631. class CORSRequestHandler(SimpleHTTPRequestHandler):
  632. def end_headers (self):
  633. self.send_header("Access-Control-Allow-Origin", "*")
  634. SimpleHTTPRequestHandler.end_headers(self)
  635. test(CORSRequestHandler, ClojureServer)
  636. def start(self):
  637. self.thread.start()
  638. def stop(self):
  639. if self.running:
  640. self.server.shutdown()
  641. self.thread.join()
  642. @property
  643. def running(self):
  644. return self.server is not None
  645. web_server = CORSWebServer()
  646. def write_embeddings(name, output, run_server, index, embeddings):
  647. print("Writing Tensorflow Projector files...")
  648. if not output:
  649. output = "couples_" + name
  650. if output.endswith(".json"):
  651. output = os.path.join(output[:-5], "couples")
  652. run_server = False
  653. metaf = "%s_%s_meta.tsv" % (output, name)
  654. with open(metaf, "w") as fout:
  655. fout.write("name\tcommits\n")
  656. for pair in index:
  657. fout.write("%s\t%s\n" % pair)
  658. print("Wrote", metaf)
  659. dataf = "%s_%s_data.tsv" % (output, name)
  660. with open(dataf, "w") as fout:
  661. for vec in embeddings:
  662. fout.write("\t".join(str(v) for v in vec))
  663. fout.write("\n")
  664. print("Wrote", dataf)
  665. jsonf = "%s_%s.json" % (output, name)
  666. with open(jsonf, "w") as fout:
  667. fout.write("""{
  668. "embeddings": [
  669. {
  670. "tensorName": "%s %s coupling",
  671. "tensorShape": [%s, %s],
  672. "tensorPath": "http://0.0.0.0:8000/%s",
  673. "metadataPath": "http://0.0.0.0:8000/%s"
  674. }
  675. ]
  676. }
  677. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  678. print("Wrote %s" % jsonf)
  679. if run_server and not web_server.running:
  680. web_server.start()
  681. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  682. print(url)
  683. if run_server:
  684. os.system("xdg-open " + url)
  685. def main():
  686. args = parse_args()
  687. reader = read_input(args)
  688. header = reader.get_header()
  689. name = reader.get_name()
  690. files_warning = "Files stats were not collected. Re-run hercules with -files."
  691. people_warning = "People stats were not collected. Re-run hercules with -people."
  692. couples_warning = "Coupling stats were not collected. Re-run hercules with -couples."
  693. def project_burndown():
  694. plot_burndown(args, "project",
  695. *load_burndown(header, *reader.get_project_burndown(),
  696. resample=args.resample))
  697. def files_burndown():
  698. try:
  699. plot_many_burndown(args, "file", header, reader.get_files_burndown())
  700. except KeyError:
  701. print(files_warning)
  702. def people_burndown():
  703. try:
  704. plot_many_burndown(args, "person", header, reader.get_people_burndown())
  705. except KeyError:
  706. print(people_warning)
  707. def churn_matrix():
  708. try:
  709. plot_churn_matrix(args, name, *load_churn_matrix(
  710. *reader.get_people_interaction(), max_people=args.max_people))
  711. except KeyError:
  712. print(people_warning)
  713. def ownership_burndown():
  714. try:
  715. plot_ownership(args, name, *load_ownership(
  716. header, *reader.get_ownership_burndown(), max_people=args.max_people))
  717. except KeyError:
  718. print(people_warning)
  719. def couples():
  720. try:
  721. write_embeddings("files", args.output, not args.disable_projector,
  722. *train_embeddings(*reader.get_files_coocc(),
  723. tmpdir=args.couples_tmp_dir))
  724. write_embeddings("people", args.output, not args.disable_projector,
  725. *train_embeddings(*reader.get_people_coocc(),
  726. tmpdir=args.couples_tmp_dir))
  727. except KeyError:
  728. print(couples_warning)
  729. if args.mode == "project":
  730. project_burndown()
  731. elif args.mode == "file":
  732. files_burndown()
  733. elif args.mode == "person":
  734. people_burndown()
  735. elif args.mode == "churn_matrix":
  736. churn_matrix()
  737. elif args.mode == "ownership":
  738. ownership_burndown()
  739. elif args.mode == "couples":
  740. couples()
  741. elif args.mode == "all":
  742. project_burndown()
  743. files_burndown()
  744. people_burndown()
  745. churn_matrix()
  746. ownership_burndown()
  747. couples()
  748. if web_server.running:
  749. print("Sleeping for 60 seconds, safe to Ctrl-C")
  750. try:
  751. time.sleep(60)
  752. except KeyboardInterrupt:
  753. pass
  754. web_server.stop()
  755. if __name__ == "__main__":
  756. sys.exit(main())