labours.py 40 KB

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