labours.py 32 KB

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