labours.py 35 KB

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