labours.py 42 KB

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