labours.py 35 KB

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