labours.py 35 KB

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