labours.py 42 KB

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