labours.py 29 KB

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