labours.py 33 KB

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