labours.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. #!/usr/bin/env python3
  2. import argparse
  3. from collections import defaultdict, namedtuple
  4. from datetime import datetime, timedelta
  5. from importlib import import_module
  6. from itertools import chain
  7. import io
  8. import json
  9. import os
  10. import re
  11. import shutil
  12. import subprocess
  13. import sys
  14. import tempfile
  15. import threading
  16. import time
  17. import warnings
  18. try:
  19. from clint.textui import progress
  20. except ImportError:
  21. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  22. progress = None
  23. import numpy
  24. import yaml
  25. if sys.version_info[0] < 3:
  26. # OK, ancients, I will support Python 2, but you owe me a beer
  27. input = raw_input # noqa: F821
  28. def list_matplotlib_styles():
  29. script = "import sys; from matplotlib import pyplot; " \
  30. "sys.stdout.write(repr(pyplot.style.available))"
  31. styles = eval(subprocess.check_output([sys.executable, "-c", script]))
  32. styles.remove("classic")
  33. return ["default", "classic"] + styles
  34. def parse_args():
  35. parser = argparse.ArgumentParser()
  36. parser.add_argument("-o", "--output", default="",
  37. help="Path to the output file/directory (empty for display). "
  38. "If the extension is JSON, the data is saved instead of "
  39. "the real image.")
  40. parser.add_argument("-i", "--input", default="-",
  41. help="Path to the input file (- for stdin).")
  42. parser.add_argument("-f", "--input-format", default="auto", choices=["yaml", "pb", "auto"])
  43. parser.add_argument("--font-size", default=12, type=int,
  44. help="Size of the labels and legend.")
  45. parser.add_argument("--style", default="ggplot", choices=list_matplotlib_styles(),
  46. help="Plot style to use.")
  47. parser.add_argument("--backend", help="Matplotlib backend to use.")
  48. parser.add_argument("--background", choices=["black", "white"], default="white",
  49. help="Plot's general color scheme.")
  50. parser.add_argument("--size", help="Axes' size in inches, for example \"12,9\"")
  51. parser.add_argument("--relative", action="store_true",
  52. help="Occupy 100%% height for every measurement.")
  53. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  54. parser.add_argument("-m", "--mode",
  55. choices=["burndown-project", "burndown-file", "burndown-person",
  56. "churn-matrix", "ownership", "couples", "shotness", "sentiment",
  57. "devs", "old-vs-new", "all", "run-times"],
  58. help="What to plot.")
  59. parser.add_argument(
  60. "--resample", default="year",
  61. help="The way to resample the time series. Possible values are: "
  62. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  63. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  64. "#offset-aliases).")
  65. parser.add_argument("--disable-projector", action="store_true",
  66. help="Do not run Tensorflow Projector on couples.")
  67. parser.add_argument("--max-people", default=20, type=int,
  68. help="Maximum number of developers in churn matrix and people plots.")
  69. args = parser.parse_args()
  70. return args
  71. class Reader(object):
  72. def read(self, file):
  73. raise NotImplementedError
  74. def get_name(self):
  75. raise NotImplementedError
  76. def get_header(self):
  77. raise NotImplementedError
  78. def get_burndown_parameters(self):
  79. raise NotImplementedError
  80. def get_project_burndown(self):
  81. raise NotImplementedError
  82. def get_files_burndown(self):
  83. raise NotImplementedError
  84. def get_people_burndown(self):
  85. raise NotImplementedError
  86. def get_ownership_burndown(self):
  87. raise NotImplementedError
  88. def get_people_interaction(self):
  89. raise NotImplementedError
  90. def get_files_coocc(self):
  91. raise NotImplementedError
  92. def get_people_coocc(self):
  93. raise NotImplementedError
  94. def get_shotness_coocc(self):
  95. raise NotImplementedError
  96. def get_shotness(self):
  97. raise NotImplementedError
  98. def get_sentiment(self):
  99. raise NotImplementedError
  100. def get_devs(self):
  101. raise NotImplementedError
  102. class YamlReader(Reader):
  103. def read(self, file):
  104. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  105. try:
  106. loader = yaml.CLoader
  107. except AttributeError:
  108. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  109. loader = yaml.Loader
  110. try:
  111. if file != "-":
  112. with open(file) as fin:
  113. data = yaml.load(fin, Loader=loader)
  114. else:
  115. data = yaml.load(sys.stdin, Loader=loader)
  116. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  117. print("\nInvalid unicode in the input: %s\nPlease filter it through "
  118. "fix_yaml_unicode.py" % e)
  119. sys.exit(1)
  120. if data is None:
  121. print("\nNo data has been read - has Hercules crashed?")
  122. sys.exit(1)
  123. self.data = data
  124. def get_run_times(self):
  125. return {}
  126. def get_name(self):
  127. return self.data["hercules"]["repository"]
  128. def get_header(self):
  129. header = self.data["hercules"]
  130. return header["begin_unix_time"], header["end_unix_time"]
  131. def get_burndown_parameters(self):
  132. header = self.data["Burndown"]
  133. return header["sampling"], header["granularity"]
  134. def get_project_burndown(self):
  135. return self.data["hercules"]["repository"], \
  136. self._parse_burndown_matrix(self.data["Burndown"]["project"]).T
  137. def get_files_burndown(self):
  138. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  139. for p in self.data["Burndown"]["files"].items()]
  140. def get_people_burndown(self):
  141. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  142. for p in self.data["Burndown"]["people"].items()]
  143. def get_ownership_burndown(self):
  144. return self.data["Burndown"]["people_sequence"].copy(),\
  145. {p[0]: self._parse_burndown_matrix(p[1])
  146. for p in self.data["Burndown"]["people"].items()}
  147. def get_people_interaction(self):
  148. return self.data["Burndown"]["people_sequence"].copy(), \
  149. self._parse_burndown_matrix(self.data["Burndown"]["people_interaction"])
  150. def get_files_coocc(self):
  151. coocc = self.data["Couples"]["files_coocc"]
  152. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  153. def get_people_coocc(self):
  154. coocc = self.data["Couples"]["people_coocc"]
  155. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  156. def get_shotness_coocc(self):
  157. shotness = self.data["Shotness"]
  158. index = ["%s:%s" % (i["file"], i["name"]) for i in shotness]
  159. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int64)
  160. indices = []
  161. data = []
  162. for i, record in enumerate(shotness):
  163. pairs = [(int(k), v) for k, v in record["counters"].items()]
  164. pairs.sort()
  165. indptr[i + 1] = indptr[i] + len(pairs)
  166. for k, v in pairs:
  167. indices.append(k)
  168. data.append(v)
  169. indices = numpy.array(indices, dtype=numpy.int32)
  170. data = numpy.array(data, dtype=numpy.int32)
  171. from scipy.sparse import csr_matrix
  172. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  173. def get_shotness(self):
  174. from munch import munchify
  175. obj = munchify(self.data["Shotness"])
  176. # turn strings into ints
  177. for item in obj:
  178. item.counters = {int(k): v for k, v in item.counters.items()}
  179. if len(obj) == 0:
  180. raise KeyError
  181. return obj
  182. def get_sentiment(self):
  183. from munch import munchify
  184. return munchify({int(key): {
  185. "Comments": vals[2].split("|"),
  186. "Commits": vals[1],
  187. "Value": float(vals[0])
  188. } for key, vals in self.data["Sentiment"].items()})
  189. def get_devs(self):
  190. people = self.data["Devs"]["people"]
  191. days = {int(d): {int(dev): DevDay(*(int(x) for x in day[:-1]))
  192. for dev, day in devs.items()}
  193. for d, devs in self.data["Devs"]["days"].items()}
  194. return days, people
  195. def _parse_burndown_matrix(self, matrix):
  196. return numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  197. for line in matrix.split("\n")])
  198. def _parse_coocc_matrix(self, matrix):
  199. from scipy.sparse import csr_matrix
  200. data = []
  201. indices = []
  202. indptr = [0]
  203. for row in matrix:
  204. for k, v in sorted(row.items()):
  205. data.append(v)
  206. indices.append(k)
  207. indptr.append(indptr[-1] + len(row))
  208. return csr_matrix((data, indices, indptr), shape=(len(matrix),) * 2)
  209. class ProtobufReader(Reader):
  210. def read(self, file):
  211. try:
  212. from internal.pb.pb_pb2 import AnalysisResults
  213. except ImportError as e:
  214. print("\n\n>>> You need to generate internal/pb/pb_pb2.py - run \"make\"\n",
  215. file=sys.stderr)
  216. raise e from None
  217. self.data = AnalysisResults()
  218. if file != "-":
  219. with open(file, "rb") as fin:
  220. self.data.ParseFromString(fin.read())
  221. else:
  222. self.data.ParseFromString(sys.stdin.buffer.read())
  223. self.contents = {}
  224. for key, val in self.data.contents.items():
  225. try:
  226. mod, name = PB_MESSAGES[key].rsplit(".", 1)
  227. except KeyError:
  228. sys.stderr.write("Warning: there is no registered PB decoder for %s\n" % key)
  229. continue
  230. cls = getattr(import_module(mod), name)
  231. self.contents[key] = msg = cls()
  232. msg.ParseFromString(val)
  233. def get_run_times(self):
  234. return {key: val for key, val in self.data.header.run_time_per_item.items()}
  235. def get_name(self):
  236. return self.data.header.repository
  237. def get_header(self):
  238. header = self.data.header
  239. return header.begin_unix_time, header.end_unix_time
  240. def get_burndown_parameters(self):
  241. burndown = self.contents["Burndown"]
  242. return burndown.sampling, burndown.granularity
  243. def get_project_burndown(self):
  244. return self._parse_burndown_matrix(self.contents["Burndown"].project)
  245. def get_files_burndown(self):
  246. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].files]
  247. def get_people_burndown(self):
  248. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].people]
  249. def get_ownership_burndown(self):
  250. people = self.get_people_burndown()
  251. return [p[0] for p in people], {p[0]: p[1].T for p in people}
  252. def get_people_interaction(self):
  253. burndown = self.contents["Burndown"]
  254. return [i.name for i in burndown.people], \
  255. self._parse_sparse_matrix(burndown.people_interaction).toarray()
  256. def get_files_coocc(self):
  257. node = self.contents["Couples"].file_couples
  258. return list(node.index), self._parse_sparse_matrix(node.matrix)
  259. def get_people_coocc(self):
  260. node = self.contents["Couples"].people_couples
  261. return list(node.index), self._parse_sparse_matrix(node.matrix)
  262. def get_shotness_coocc(self):
  263. shotness = self.get_shotness()
  264. index = ["%s:%s" % (i.file, i.name) for i in shotness]
  265. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int32)
  266. indices = []
  267. data = []
  268. for i, record in enumerate(shotness):
  269. pairs = list(record.counters.items())
  270. pairs.sort()
  271. indptr[i + 1] = indptr[i] + len(pairs)
  272. for k, v in pairs:
  273. indices.append(k)
  274. data.append(v)
  275. indices = numpy.array(indices, dtype=numpy.int32)
  276. data = numpy.array(data, dtype=numpy.int32)
  277. from scipy.sparse import csr_matrix
  278. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  279. def get_shotness(self):
  280. records = self.contents["Shotness"].records
  281. if len(records) == 0:
  282. raise KeyError
  283. return records
  284. def get_sentiment(self):
  285. byday = self.contents["Sentiment"].SentimentByDay
  286. if len(byday) == 0:
  287. raise KeyError
  288. return byday
  289. def get_devs(self):
  290. people = list(self.contents["Devs"].dev_index)
  291. days = {d: {dev: DevDay(stats.commits, stats.stats.added, stats.stats.removed,
  292. stats.stats.changed)
  293. for dev, stats in day.devs.items()}
  294. for d, day in self.contents["Devs"].days.items()}
  295. return days, people
  296. def _parse_burndown_matrix(self, matrix):
  297. dense = numpy.zeros((matrix.number_of_rows, matrix.number_of_columns), dtype=int)
  298. for y, row in enumerate(matrix.rows):
  299. for x, col in enumerate(row.columns):
  300. dense[y, x] = col
  301. return matrix.name, dense.T
  302. def _parse_sparse_matrix(self, matrix):
  303. from scipy.sparse import csr_matrix
  304. return csr_matrix((list(matrix.data), list(matrix.indices), list(matrix.indptr)),
  305. shape=(matrix.number_of_rows, matrix.number_of_columns))
  306. READERS = {"yaml": YamlReader, "yml": YamlReader, "pb": ProtobufReader}
  307. PB_MESSAGES = {
  308. "Burndown": "internal.pb.pb_pb2.BurndownAnalysisResults",
  309. "Couples": "internal.pb.pb_pb2.CouplesAnalysisResults",
  310. "Shotness": "internal.pb.pb_pb2.ShotnessAnalysisResults",
  311. "Devs": "internal.pb.pb_pb2.DevsAnalysisResults",
  312. }
  313. def read_input(args):
  314. sys.stdout.write("Reading the input... ")
  315. sys.stdout.flush()
  316. if args.input != "-":
  317. if args.input_format == "auto":
  318. args.input_format = args.input.rsplit(".", 1)[1]
  319. elif args.input_format == "auto":
  320. args.input_format = "yaml"
  321. reader = READERS[args.input_format]()
  322. reader.read(args.input)
  323. print("done")
  324. return reader
  325. class DevDay(namedtuple("DevDay", ("Commits", "Added", "Removed", "Changed"))):
  326. def add(self, dd):
  327. return DevDay(Commits=self.Commits + dd.Commits,
  328. Added=self.Added + dd.Added,
  329. Removed=self.Removed + dd.Removed,
  330. Changed=self.Changed + dd.Changed)
  331. def calculate_average_lifetime(matrix):
  332. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  333. for band in matrix:
  334. start = 0
  335. for i, line in enumerate(band):
  336. if i == 0 or band[i - 1] == 0:
  337. start += 1
  338. continue
  339. lifetimes[i - start] = band[i - 1] - line
  340. lifetimes[i - start] = band[i - 1]
  341. lsum = lifetimes.sum()
  342. if lsum != 0:
  343. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  344. / (lsum * matrix.shape[1]))
  345. return numpy.nan
  346. def interpolate_burndown_matrix(matrix, granularity, sampling):
  347. daily = numpy.zeros(
  348. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  349. dtype=numpy.float32)
  350. """
  351. ----------> samples, x
  352. |
  353. |
  354. |
  355. bands, y
  356. """
  357. for y in range(matrix.shape[0]):
  358. for x in range(matrix.shape[1]):
  359. if y * granularity > (x + 1) * sampling:
  360. # the future is zeros
  361. continue
  362. def decay(start_index: int, start_val: float):
  363. if start_val == 0:
  364. return
  365. k = matrix[y][x] / start_val # <= 1
  366. scale = (x + 1) * sampling - start_index
  367. for i in range(y * granularity, (y + 1) * granularity):
  368. initial = daily[i][start_index - 1]
  369. for j in range(start_index, (x + 1) * sampling):
  370. daily[i][j] = initial * (
  371. 1 + (k - 1) * (j - start_index + 1) / scale)
  372. def grow(finish_index: int, finish_val: float):
  373. initial = matrix[y][x - 1] if x > 0 else 0
  374. start_index = x * sampling
  375. if start_index < y * granularity:
  376. start_index = y * granularity
  377. if finish_index == start_index:
  378. return
  379. avg = (finish_val - initial) / (finish_index - start_index)
  380. for j in range(x * sampling, finish_index):
  381. for i in range(start_index, j + 1):
  382. daily[i][j] = avg
  383. # copy [x*g..y*s)
  384. for j in range(x * sampling, finish_index):
  385. for i in range(y * granularity, x * sampling):
  386. daily[i][j] = daily[i][j - 1]
  387. if (y + 1) * granularity >= (x + 1) * sampling:
  388. # x*granularity <= (y+1)*sampling
  389. # 1. x*granularity <= y*sampling
  390. # y*sampling..(y+1)sampling
  391. #
  392. # x+1
  393. # /
  394. # /
  395. # / y+1 -|
  396. # / |
  397. # / y -|
  398. # /
  399. # / x
  400. #
  401. # 2. x*granularity > y*sampling
  402. # x*granularity..(y+1)sampling
  403. #
  404. # x+1
  405. # /
  406. # /
  407. # / y+1 -|
  408. # / |
  409. # / x -|
  410. # /
  411. # / y
  412. if y * granularity <= x * sampling:
  413. grow((x + 1) * sampling, matrix[y][x])
  414. elif (x + 1) * sampling > y * granularity:
  415. grow((x + 1) * sampling, matrix[y][x])
  416. avg = matrix[y][x] / ((x + 1) * sampling - y * granularity)
  417. for j in range(y * granularity, (x + 1) * sampling):
  418. for i in range(y * granularity, j + 1):
  419. daily[i][j] = avg
  420. elif (y + 1) * granularity >= x * sampling:
  421. # y*sampling <= (x+1)*granularity < (y+1)sampling
  422. # y*sampling..(x+1)*granularity
  423. # (x+1)*granularity..(y+1)sampling
  424. # x+1
  425. # /\
  426. # / \
  427. # / \
  428. # / y+1
  429. # /
  430. # y
  431. v1 = matrix[y][x - 1]
  432. v2 = matrix[y][x]
  433. delta = (y + 1) * granularity - x * sampling
  434. previous = 0
  435. if x > 0 and (x - 1) * sampling >= y * granularity:
  436. # x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  437. # |________|.......^
  438. if x > 1:
  439. previous = matrix[y][x - 2]
  440. scale = sampling
  441. else:
  442. # (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  443. # |______|.......^
  444. scale = sampling if x == 0 else x * sampling - y * granularity
  445. peak = v1 + (v1 - previous) / scale * delta
  446. if v2 > peak:
  447. # we need to adjust the peak, it may not be less than the decayed value
  448. if x < matrix.shape[1] - 1:
  449. # y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  450. # ^.........|_________|
  451. k = (v2 - matrix[y][x + 1]) / sampling # > 0
  452. peak = matrix[y][x] + k * ((x + 1) * sampling - (y + 1) * granularity)
  453. # peak > v2 > v1
  454. else:
  455. peak = v2
  456. # not enough data to interpolate; this is at least not restricted
  457. grow((y + 1) * granularity, peak)
  458. decay((y + 1) * granularity, peak)
  459. else:
  460. # (x+1)*granularity < y*sampling
  461. # y*sampling..(y+1)sampling
  462. decay(x * sampling, matrix[y][x - 1])
  463. return daily
  464. def load_burndown(header, name, matrix, resample):
  465. import pandas
  466. start, last, sampling, granularity = header
  467. assert sampling > 0
  468. assert granularity >= sampling
  469. start = datetime.fromtimestamp(start)
  470. last = datetime.fromtimestamp(last)
  471. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  472. finish = start + timedelta(days=matrix.shape[1] * sampling)
  473. if resample not in ("no", "raw"):
  474. print("resampling to %s, please wait..." % resample)
  475. # Interpolate the day x day matrix.
  476. # Each day brings equal weight in the granularity.
  477. # Sampling's interpolation is linear.
  478. daily = interpolate_burndown_matrix(matrix, granularity, sampling)
  479. daily[(last - start).days:] = 0
  480. # Resample the bands
  481. aliases = {
  482. "year": "A",
  483. "month": "M"
  484. }
  485. resample = aliases.get(resample, resample)
  486. periods = 0
  487. date_granularity_sampling = [start]
  488. while date_granularity_sampling[-1] < finish:
  489. periods += 1
  490. date_granularity_sampling = pandas.date_range(
  491. start, periods=periods, freq=resample)
  492. date_range_sampling = pandas.date_range(
  493. date_granularity_sampling[0],
  494. periods=(finish - date_granularity_sampling[0]).days,
  495. freq="1D")
  496. # Fill the new square matrix
  497. matrix = numpy.zeros(
  498. (len(date_granularity_sampling), len(date_range_sampling)),
  499. dtype=numpy.float32)
  500. for i, gdt in enumerate(date_granularity_sampling):
  501. istart = (date_granularity_sampling[i - 1] - start).days \
  502. if i > 0 else 0
  503. ifinish = (gdt - start).days
  504. for j, sdt in enumerate(date_range_sampling):
  505. if (sdt - start).days >= istart:
  506. break
  507. matrix[i, j:] = \
  508. daily[istart:ifinish, (sdt - start).days:].sum(axis=0)
  509. # Hardcode some cases to improve labels' readability
  510. if resample in ("year", "A"):
  511. labels = [dt.year for dt in date_granularity_sampling]
  512. elif resample in ("month", "M"):
  513. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  514. else:
  515. labels = [dt.date() for dt in date_granularity_sampling]
  516. else:
  517. labels = [
  518. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  519. (
  520. start + timedelta(days=(i + 1) * granularity)).date())
  521. for i in range(matrix.shape[0])]
  522. if len(labels) > 18:
  523. warnings.warn("Too many labels - consider resampling.")
  524. resample = "M" # fake resampling type is checked while plotting
  525. date_range_sampling = pandas.date_range(
  526. start + timedelta(days=sampling), periods=matrix.shape[1],
  527. freq="%dD" % sampling)
  528. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  529. def load_ownership(header, sequence, contents, max_people):
  530. import pandas
  531. start, last, sampling, _ = header
  532. start = datetime.fromtimestamp(start)
  533. last = datetime.fromtimestamp(last)
  534. people = []
  535. for name in sequence:
  536. people.append(contents[name].sum(axis=1))
  537. people = numpy.array(people)
  538. date_range_sampling = pandas.date_range(
  539. start + timedelta(days=sampling), periods=people[0].shape[0],
  540. freq="%dD" % sampling)
  541. if people.shape[0] > max_people:
  542. order = numpy.argsort(-people.sum(axis=1))
  543. people = people[order[:max_people]]
  544. sequence = [sequence[i] for i in order[:max_people]]
  545. print("Warning: truncated people to most owning %d" % max_people)
  546. for i, name in enumerate(sequence):
  547. if len(name) > 40:
  548. sequence[i] = name[:37] + "..."
  549. return sequence, people, date_range_sampling, last
  550. def load_churn_matrix(people, matrix, max_people):
  551. matrix = matrix.astype(float)
  552. if matrix.shape[0] > max_people:
  553. order = numpy.argsort(-matrix[:, 0])
  554. matrix = matrix[order[:max_people]][:, [0, 1] + list(2 + order[:max_people])]
  555. people = [people[i] for i in order[:max_people]]
  556. print("Warning: truncated people to most productive %d" % max_people)
  557. zeros = matrix[:, 0] == 0
  558. matrix[zeros, :] = 1
  559. matrix /= matrix[:, 0][:, None]
  560. matrix = -matrix[:, 1:]
  561. matrix[zeros, :] = 0
  562. for i, name in enumerate(people):
  563. if len(name) > 40:
  564. people[i] = name[:37] + "..."
  565. return people, matrix
  566. def import_pyplot(backend, style):
  567. import matplotlib
  568. if backend:
  569. matplotlib.use(backend)
  570. from matplotlib import pyplot
  571. pyplot.style.use(style)
  572. return matplotlib, pyplot
  573. def apply_plot_style(figure, axes, legend, background, font_size, axes_size):
  574. foreground = "black" if background == "white" else "white"
  575. if axes_size is None:
  576. axes_size = (12, 9)
  577. else:
  578. axes_size = tuple(float(p) for p in axes_size.split(","))
  579. figure.set_size_inches(*axes_size)
  580. for side in ("bottom", "top", "left", "right"):
  581. axes.spines[side].set_color(foreground)
  582. for axis in (axes.xaxis, axes.yaxis):
  583. axis.label.update(dict(fontsize=font_size, color=foreground))
  584. for axis in ("x", "y"):
  585. getattr(axes, axis + "axis").get_offset_text().set_size(font_size)
  586. axes.tick_params(axis=axis, colors=foreground, labelsize=font_size)
  587. try:
  588. axes.ticklabel_format(axis="y", style="sci", scilimits=(0, 3))
  589. except AttributeError:
  590. pass
  591. figure.patch.set_facecolor(background)
  592. axes.set_facecolor(background)
  593. if legend is not None:
  594. frame = legend.get_frame()
  595. for setter in (frame.set_facecolor, frame.set_edgecolor):
  596. setter(background)
  597. for text in legend.get_texts():
  598. text.set_color(foreground)
  599. def get_plot_path(base, name):
  600. root, ext = os.path.splitext(base)
  601. if not ext:
  602. ext = ".png"
  603. output = os.path.join(root, name + ext)
  604. os.makedirs(os.path.dirname(output), exist_ok=True)
  605. return output
  606. def deploy_plot(title, output, background):
  607. import matplotlib.pyplot as pyplot
  608. if not output:
  609. pyplot.gcf().canvas.set_window_title(title)
  610. pyplot.show()
  611. else:
  612. if title:
  613. pyplot.title(title, color="black" if background == "white" else "white")
  614. try:
  615. pyplot.tight_layout()
  616. except: # noqa: E722
  617. print("Warning: failed to set the tight layout")
  618. pyplot.savefig(output, transparent=True)
  619. pyplot.clf()
  620. def default_json(x):
  621. if hasattr(x, "tolist"):
  622. return x.tolist()
  623. if hasattr(x, "isoformat"):
  624. return x.isoformat()
  625. return x
  626. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  627. sampling, resample):
  628. if args.output and args.output.endswith(".json"):
  629. data = locals().copy()
  630. del data["args"]
  631. data["type"] = "burndown"
  632. if args.mode == "project" and target == "project":
  633. output = args.output
  634. else:
  635. if target == "project":
  636. name = "project"
  637. output = get_plot_path(args.output, name)
  638. with open(output, "w") as fout:
  639. json.dump(data, fout, sort_keys=True, default=default_json)
  640. return
  641. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  642. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  643. if args.relative:
  644. for i in range(matrix.shape[1]):
  645. matrix[:, i] /= matrix[:, i].sum()
  646. pyplot.ylim(0, 1)
  647. legend_loc = 3
  648. else:
  649. legend_loc = 2
  650. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size)
  651. pyplot.ylabel("Lines of code")
  652. pyplot.xlabel("Time")
  653. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  654. args.font_size, args.size)
  655. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  656. locator = pyplot.gca().xaxis.get_major_locator()
  657. # set the optimal xticks locator
  658. if "M" not in resample:
  659. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  660. locs = pyplot.gca().get_xticks().tolist()
  661. if len(locs) >= 16:
  662. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  663. locs = pyplot.gca().get_xticks().tolist()
  664. if len(locs) >= 16:
  665. pyplot.gca().xaxis.set_major_locator(locator)
  666. if locs[0] < pyplot.xlim()[0]:
  667. del locs[0]
  668. endindex = -1
  669. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  670. locs.append(pyplot.xlim()[1])
  671. endindex = len(locs) - 1
  672. startindex = -1
  673. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  674. locs.append(pyplot.xlim()[0])
  675. startindex = len(locs) - 1
  676. pyplot.gca().set_xticks(locs)
  677. # hacking time!
  678. labels = pyplot.gca().get_xticklabels()
  679. if startindex >= 0:
  680. labels[startindex].set_text(date_range_sampling[0].date())
  681. labels[startindex].set_text = lambda _: None
  682. labels[startindex].set_rotation(30)
  683. labels[startindex].set_ha("right")
  684. if endindex >= 0:
  685. labels[endindex].set_text(date_range_sampling[-1].date())
  686. labels[endindex].set_text = lambda _: None
  687. labels[endindex].set_rotation(30)
  688. labels[endindex].set_ha("right")
  689. title = "%s %d x %d (granularity %d, sampling %d)" % \
  690. ((name,) + matrix.shape + (granularity, sampling))
  691. output = args.output
  692. if output:
  693. if args.mode == "project" and target == "project":
  694. output = args.output
  695. else:
  696. if target == "project":
  697. name = "project"
  698. output = get_plot_path(args.output, name)
  699. deploy_plot(title, output, args.style)
  700. def plot_many_burndown(args, target, header, parts):
  701. if not args.output:
  702. print("Warning: output not set, showing %d plots." % len(parts))
  703. itercnt = progress.bar(parts, expected_size=len(parts)) \
  704. if progress is not None else parts
  705. stdout = io.StringIO()
  706. for name, matrix in itercnt:
  707. backup = sys.stdout
  708. sys.stdout = stdout
  709. plot_burndown(args, target, *load_burndown(header, name, matrix, args.resample))
  710. sys.stdout = backup
  711. sys.stdout.write(stdout.getvalue())
  712. def plot_churn_matrix(args, repo, people, matrix):
  713. if args.output and args.output.endswith(".json"):
  714. data = locals().copy()
  715. del data["args"]
  716. data["type"] = "churn_matrix"
  717. if args.mode == "all":
  718. output = get_plot_path(args.output, "matrix")
  719. else:
  720. output = args.output
  721. with open(output, "w") as fout:
  722. json.dump(data, fout, sort_keys=True, default=default_json)
  723. return
  724. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  725. s = 4 + matrix.shape[1] * 0.3
  726. fig = pyplot.figure(figsize=(s, s))
  727. ax = fig.add_subplot(111)
  728. ax.xaxis.set_label_position("top")
  729. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  730. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  731. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  732. ax.set_yticklabels(people, va="center")
  733. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  734. ax.set_xticklabels(["Unidentified"] + people, rotation=45, ha="left",
  735. va="bottom", rotation_mode="anchor")
  736. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  737. ax.grid(False)
  738. ax.grid(which="minor")
  739. apply_plot_style(fig, ax, None, args.background, args.font_size, args.size)
  740. if not args.output:
  741. pos1 = ax.get_position()
  742. pos2 = (pos1.x0 + 0.15, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  743. ax.set_position(pos2)
  744. if args.mode == "all" and args.output:
  745. output = get_plot_path(args.output, "matrix")
  746. else:
  747. output = args.output
  748. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  749. if args.output:
  750. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  751. title = ""
  752. deploy_plot(title, output, args.style)
  753. def plot_ownership(args, repo, names, people, date_range, last):
  754. if args.output and args.output.endswith(".json"):
  755. data = locals().copy()
  756. del data["args"]
  757. data["type"] = "ownership"
  758. if args.mode == "all" and args.output:
  759. output = get_plot_path(args.output, "people")
  760. else:
  761. output = args.output
  762. with open(output, "w") as fout:
  763. json.dump(data, fout, sort_keys=True, default=default_json)
  764. return
  765. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  766. pyplot.stackplot(date_range, people, labels=names)
  767. pyplot.xlim(date_range[0], last)
  768. if args.relative:
  769. for i in range(people.shape[1]):
  770. people[:, i] /= people[:, i].sum()
  771. pyplot.ylim(0, 1)
  772. legend_loc = 3
  773. else:
  774. legend_loc = 2
  775. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size)
  776. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  777. args.font_size, args.size)
  778. if args.mode == "all" and args.output:
  779. output = get_plot_path(args.output, "people")
  780. else:
  781. output = args.output
  782. deploy_plot("%s code ownership through time" % repo, output, args.style)
  783. IDEAL_SHARD_SIZE = 4096
  784. def train_embeddings(index, matrix, tmpdir, shard_size=IDEAL_SHARD_SIZE):
  785. try:
  786. from . import swivel
  787. except (SystemError, ImportError):
  788. import swivel
  789. import tensorflow as tf
  790. assert matrix.shape[0] == matrix.shape[1]
  791. assert len(index) <= matrix.shape[0]
  792. outlier_threshold = numpy.percentile(matrix.data, 99)
  793. matrix.data[matrix.data > outlier_threshold] = outlier_threshold
  794. nshards = len(index) // shard_size
  795. if nshards * shard_size < len(index):
  796. nshards += 1
  797. shard_size = len(index) // nshards
  798. nshards = len(index) // shard_size
  799. remainder = len(index) - nshards * shard_size
  800. if remainder > 0:
  801. lengths = matrix.indptr[1:] - matrix.indptr[:-1]
  802. filtered = sorted(numpy.argsort(lengths)[remainder:])
  803. else:
  804. filtered = list(range(len(index)))
  805. if len(filtered) < matrix.shape[0]:
  806. print("Truncating the sparse matrix...")
  807. matrix = matrix[filtered, :][:, filtered]
  808. meta_index = []
  809. for i, j in enumerate(filtered):
  810. meta_index.append((index[j], matrix[i, i]))
  811. index = [mi[0] for mi in meta_index]
  812. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  813. print("Writing Swivel metadata...")
  814. vocabulary = "\n".join(index)
  815. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  816. out.write(vocabulary)
  817. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  818. out.write(vocabulary)
  819. del vocabulary
  820. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  821. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  822. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  823. out.write(bool_sums_str)
  824. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  825. out.write(bool_sums_str)
  826. del bool_sums_str
  827. reorder = numpy.argsort(-bool_sums)
  828. print("Writing Swivel shards...")
  829. for row in range(nshards):
  830. for col in range(nshards):
  831. def _int64s(xs):
  832. return tf.train.Feature(
  833. int64_list=tf.train.Int64List(value=list(xs)))
  834. def _floats(xs):
  835. return tf.train.Feature(
  836. float_list=tf.train.FloatList(value=list(xs)))
  837. indices_row = reorder[row::nshards]
  838. indices_col = reorder[col::nshards]
  839. shard = matrix[indices_row][:, indices_col].tocoo()
  840. example = tf.train.Example(features=tf.train.Features(feature={
  841. "global_row": _int64s(indices_row),
  842. "global_col": _int64s(indices_col),
  843. "sparse_local_row": _int64s(shard.row),
  844. "sparse_local_col": _int64s(shard.col),
  845. "sparse_value": _floats(shard.data)}))
  846. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  847. out.write(example.SerializeToString())
  848. print("Training Swivel model...")
  849. swivel.FLAGS.submatrix_rows = shard_size
  850. swivel.FLAGS.submatrix_cols = shard_size
  851. if len(meta_index) <= IDEAL_SHARD_SIZE / 16:
  852. embedding_size = 50
  853. num_epochs = 100000
  854. elif len(meta_index) <= IDEAL_SHARD_SIZE:
  855. embedding_size = 50
  856. num_epochs = 50000
  857. elif len(meta_index) <= IDEAL_SHARD_SIZE * 2:
  858. embedding_size = 60
  859. num_epochs = 10000
  860. elif len(meta_index) <= IDEAL_SHARD_SIZE * 4:
  861. embedding_size = 70
  862. num_epochs = 8000
  863. elif len(meta_index) <= IDEAL_SHARD_SIZE * 10:
  864. embedding_size = 80
  865. num_epochs = 5000
  866. elif len(meta_index) <= IDEAL_SHARD_SIZE * 25:
  867. embedding_size = 100
  868. num_epochs = 1000
  869. elif len(meta_index) <= IDEAL_SHARD_SIZE * 100:
  870. embedding_size = 200
  871. num_epochs = 600
  872. else:
  873. embedding_size = 300
  874. num_epochs = 300
  875. if os.getenv("CI"):
  876. # Travis, AppVeyor etc. during the integration tests
  877. num_epochs /= 10
  878. swivel.FLAGS.embedding_size = embedding_size
  879. swivel.FLAGS.input_base_path = tmproot
  880. swivel.FLAGS.output_base_path = tmproot
  881. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  882. swivel.FLAGS.num_epochs = num_epochs
  883. # Tensorflow 1.5 parses sys.argv unconditionally *applause*
  884. argv_backup = sys.argv[1:]
  885. del sys.argv[1:]
  886. swivel.main(None)
  887. sys.argv.extend(argv_backup)
  888. print("Reading Swivel embeddings...")
  889. embeddings = []
  890. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  891. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  892. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  893. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  894. assert prow[0] == pcol[0]
  895. erow, ecol = \
  896. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  897. for p in (prow, pcol))
  898. embeddings.append((erow + ecol) / 2)
  899. return meta_index, embeddings
  900. class CORSWebServer(object):
  901. def __init__(self):
  902. self.thread = threading.Thread(target=self.serve)
  903. self.server = None
  904. def serve(self):
  905. outer = self
  906. try:
  907. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  908. except ImportError: # Python 2
  909. from BaseHTTPServer import HTTPServer, test
  910. from SimpleHTTPServer import SimpleHTTPRequestHandler
  911. class ClojureServer(HTTPServer):
  912. def __init__(self, *args, **kwargs):
  913. HTTPServer.__init__(self, *args, **kwargs)
  914. outer.server = self
  915. class CORSRequestHandler(SimpleHTTPRequestHandler):
  916. def end_headers(self):
  917. self.send_header("Access-Control-Allow-Origin", "*")
  918. SimpleHTTPRequestHandler.end_headers(self)
  919. test(CORSRequestHandler, ClojureServer)
  920. def start(self):
  921. self.thread.start()
  922. def stop(self):
  923. if self.running:
  924. self.server.shutdown()
  925. self.thread.join()
  926. @property
  927. def running(self):
  928. return self.server is not None
  929. web_server = CORSWebServer()
  930. def write_embeddings(name, output, run_server, index, embeddings):
  931. print("Writing Tensorflow Projector files...")
  932. if not output:
  933. output = "couples_" + name
  934. if output.endswith(".json"):
  935. output = os.path.join(output[:-5], "couples")
  936. run_server = False
  937. metaf = "%s_%s_meta.tsv" % (output, name)
  938. with open(metaf, "w") as fout:
  939. fout.write("name\tcommits\n")
  940. for pair in index:
  941. fout.write("%s\t%s\n" % pair)
  942. print("Wrote", metaf)
  943. dataf = "%s_%s_data.tsv" % (output, name)
  944. with open(dataf, "w") as fout:
  945. for vec in embeddings:
  946. fout.write("\t".join(str(v) for v in vec))
  947. fout.write("\n")
  948. print("Wrote", dataf)
  949. jsonf = "%s_%s.json" % (output, name)
  950. with open(jsonf, "w") as fout:
  951. fout.write("""{
  952. "embeddings": [
  953. {
  954. "tensorName": "%s %s coupling",
  955. "tensorShape": [%s, %s],
  956. "tensorPath": "http://0.0.0.0:8000/%s",
  957. "metadataPath": "http://0.0.0.0:8000/%s"
  958. }
  959. ]
  960. }
  961. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  962. print("Wrote %s" % jsonf)
  963. if run_server and not web_server.running:
  964. web_server.start()
  965. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  966. print(url)
  967. if run_server:
  968. if shutil.which("xdg-open") is not None:
  969. os.system("xdg-open " + url)
  970. else:
  971. browser = os.getenv("BROWSER", "")
  972. if browser:
  973. os.system(browser + " " + url)
  974. else:
  975. print("\t" + url)
  976. def show_shotness_stats(data):
  977. top = sorted(((r.counters[i], i) for i, r in enumerate(data)), reverse=True)
  978. for count, i in top:
  979. r = data[i]
  980. print("%8d %s:%s [%s]" % (count, r.file, r.name, r.internal_role))
  981. def show_sentiment_stats(args, name, resample, start_date, data):
  982. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  983. start_date = datetime.fromtimestamp(start_date)
  984. data = sorted(data.items())
  985. xdates = [start_date + timedelta(days=d[0]) for d in data]
  986. xpos = []
  987. ypos = []
  988. xneg = []
  989. yneg = []
  990. for x, (_, y) in zip(xdates, data):
  991. y = 0.5 - y.Value
  992. if y > 0:
  993. xpos.append(x)
  994. ypos.append(y)
  995. else:
  996. xneg.append(x)
  997. yneg.append(y)
  998. pyplot.bar(xpos, ypos, color="g", label="Positive")
  999. pyplot.bar(xneg, yneg, color="r", label="Negative")
  1000. legend = pyplot.legend(loc=1, fontsize=args.font_size)
  1001. pyplot.ylabel("Lines of code")
  1002. pyplot.xlabel("Time")
  1003. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  1004. args.font_size, args.size)
  1005. pyplot.xlim(xdates[0], xdates[-1])
  1006. locator = pyplot.gca().xaxis.get_major_locator()
  1007. # set the optimal xticks locator
  1008. if "M" not in resample:
  1009. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1010. locs = pyplot.gca().get_xticks().tolist()
  1011. if len(locs) >= 16:
  1012. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1013. locs = pyplot.gca().get_xticks().tolist()
  1014. if len(locs) >= 16:
  1015. pyplot.gca().xaxis.set_major_locator(locator)
  1016. if locs[0] < pyplot.xlim()[0]:
  1017. del locs[0]
  1018. endindex = -1
  1019. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  1020. locs.append(pyplot.xlim()[1])
  1021. endindex = len(locs) - 1
  1022. startindex = -1
  1023. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  1024. locs.append(pyplot.xlim()[0])
  1025. startindex = len(locs) - 1
  1026. pyplot.gca().set_xticks(locs)
  1027. # hacking time!
  1028. labels = pyplot.gca().get_xticklabels()
  1029. if startindex >= 0:
  1030. labels[startindex].set_text(xdates[0].date())
  1031. labels[startindex].set_text = lambda _: None
  1032. labels[startindex].set_rotation(30)
  1033. labels[startindex].set_ha("right")
  1034. if endindex >= 0:
  1035. labels[endindex].set_text(xdates[-1].date())
  1036. labels[endindex].set_text = lambda _: None
  1037. labels[endindex].set_rotation(30)
  1038. labels[endindex].set_ha("right")
  1039. overall_pos = sum(2 * (0.5 - d[1].Value) for d in data if d[1].Value < 0.5)
  1040. overall_neg = sum(2 * (d[1].Value - 0.5) for d in data if d[1].Value > 0.5)
  1041. title = "%s sentiment +%.1f -%.1f δ=%.1f" % (
  1042. name, overall_pos, overall_neg, overall_pos - overall_neg)
  1043. deploy_plot(title, args.output, args.style)
  1044. def show_devs(args, name, start_date, end_date, data):
  1045. try:
  1046. from fastdtw import fastdtw
  1047. except ImportError as e:
  1048. print("Cannot import fastdtw: %s\nInstall it from https://github.com/slaypni/fastdtw" % e)
  1049. sys.exit(1)
  1050. try:
  1051. from ortools.constraint_solver import pywrapcp, routing_enums_pb2
  1052. except ImportError as e:
  1053. print("Cannot import ortools: %s\nInstall it from "
  1054. "https://developers.google.com/optimization/install/python/" % e)
  1055. sys.exit(1)
  1056. try:
  1057. from hdbscan import HDBSCAN
  1058. except ImportError as e:
  1059. print("Cannot import ortools: %s\nInstall it from "
  1060. "https://developers.google.com/optimization/install/python/" % e)
  1061. sys.exit(1)
  1062. from scipy.signal import convolve, slepian
  1063. days, people = data
  1064. max_people = 50
  1065. if len(people) > max_people:
  1066. print("Picking top 100 developers by commit count")
  1067. # pick top N developers by commit count
  1068. commits = defaultdict(int)
  1069. for devs in days.values():
  1070. for dev, stats in devs.items():
  1071. commits[dev] += stats.Commits
  1072. commits = sorted(((v, k) for k, v in commits.items()), reverse=True)
  1073. chosen_people = {people[k] for _, k in commits[:max_people]}
  1074. else:
  1075. chosen_people = set(people)
  1076. devseries = defaultdict(list)
  1077. devstats = defaultdict(lambda: DevDay(0, 0, 0, 0))
  1078. for day, devs in sorted(days.items()):
  1079. for dev, stats in devs.items():
  1080. if people[dev] in chosen_people:
  1081. devseries[dev].append((day, stats.Commits))
  1082. devstats[dev] = devstats[dev].add(stats)
  1083. print("Calculating the distance matrix")
  1084. # max-normalize the time series using a sliding window
  1085. keys = list(devseries.keys())
  1086. series = list(devseries.values())
  1087. for i, s in enumerate(series):
  1088. arr = numpy.array(s).transpose().astype(numpy.float32)
  1089. commits = arr[1]
  1090. if len(commits) < 7:
  1091. commits /= commits.max()
  1092. else:
  1093. # 4 is sizeof(float32)
  1094. windows = numpy.lib.stride_tricks.as_strided(commits, [len(commits) - 6, 7], [4, 4])
  1095. commits = numpy.concatenate((
  1096. [windows[0, 0] / windows[0].max(),
  1097. windows[0, 1] / windows[0].max(),
  1098. windows[0, 2] / windows[0].max()],
  1099. windows[:, 3] / windows.max(axis=1),
  1100. [windows[-1, 4] / windows[-1].max(),
  1101. windows[-1, 5] / windows[-1].max(),
  1102. windows[-1, 6] / windows[-1].max()]
  1103. ))
  1104. arr[1] = commits * 7 # 7 is a pure heuristic here and is not related to window size
  1105. series[i] = list(arr.transpose())
  1106. # calculate the distance matrix using dynamic time warping metric
  1107. dists = numpy.full((len(series)+1, len(series)+1), -100500, dtype=numpy.float32)
  1108. for x in range(len(series)):
  1109. dists[x, x] = 0
  1110. for y in range(x + 1, len(series)):
  1111. # L1 norm
  1112. dist, _ = fastdtw(series[x], series[y], radius=5, dist=1)
  1113. dists[x, y] = dists[y, x] = dist
  1114. # preparation for seriation ordering
  1115. dists[len(series), :] = 0
  1116. dists[:, len(series)] = 0
  1117. assert (dists >= 0).all()
  1118. print("Ordering the series")
  1119. # solve the TSP on the distance matrix
  1120. routing = pywrapcp.RoutingModel(dists.shape[0], 1, len(series))
  1121. def dist_callback(x, y):
  1122. # ortools wants integers, so we approximate here
  1123. return int(dists[x][y] * 1000)
  1124. routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
  1125. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  1126. search_parameters.local_search_metaheuristic = (
  1127. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  1128. search_parameters.time_limit_ms = 2000
  1129. assignment = routing.SolveWithParameters(search_parameters)
  1130. index = routing.Start(0)
  1131. route = []
  1132. while not routing.IsEnd(index):
  1133. node = routing.IndexToNode(index)
  1134. if node < len(keys):
  1135. route.append(node)
  1136. index = assignment.Value(routing.NextVar(index))
  1137. route_map = {v: i for i, v in enumerate(route)}
  1138. # determine clusters
  1139. opt_dist_chain = numpy.cumsum(numpy.array(
  1140. [0] + [dists[route[i], route[i + 1]] for i in range(len(route)-1)]))
  1141. clusters = HDBSCAN(min_cluster_size=2).fit_predict(opt_dist_chain[:, numpy.newaxis])
  1142. route = [keys[node] for node in route]
  1143. print("Plotting")
  1144. # smooth time series
  1145. start_date = datetime.fromtimestamp(start_date)
  1146. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1147. end_date = datetime.fromtimestamp(end_date)
  1148. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1149. size = (end_date - start_date).days + 1
  1150. plot_x = [start_date + timedelta(days=i) for i in range(size)]
  1151. resolution = 64
  1152. window = slepian(size // resolution, 0.5)
  1153. final = numpy.zeros((len(devseries), size), dtype=numpy.float32)
  1154. for i, s in enumerate(devseries.values()):
  1155. arr = numpy.array(s).transpose()
  1156. full_history = numpy.zeros(size, dtype=numpy.float32)
  1157. mask = arr[0] < size
  1158. full_history[arr[0][mask]] = arr[1][mask]
  1159. final[route_map[i]] = convolve(full_history, window, "same")
  1160. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1161. prop_cycle = pyplot.rcParams["axes.prop_cycle"]
  1162. colors = prop_cycle.by_key()["color"]
  1163. fig, axes = pyplot.subplots(final.shape[0], 1)
  1164. backgrounds = ("#C4FFDB", "#FFD0CD") if args.background == "white" else ("#05401C", "#40110E")
  1165. for ax, series, cluster, dev_i in zip(axes, final, clusters, route):
  1166. if cluster >= 0:
  1167. color = colors[cluster % len(colors)]
  1168. else:
  1169. # outlier
  1170. color = "grey"
  1171. ax.fill_between(plot_x, series, color=color)
  1172. ax.set_axis_off()
  1173. author = people[dev_i]
  1174. ax.text(0.03, 0.5, author[:36] + (author[36:] and "..."),
  1175. horizontalalignment="right", verticalalignment="center",
  1176. transform=ax.transAxes, fontsize=14,
  1177. color="black" if args.background == "white" else "white")
  1178. ds = devstats[dev_i]
  1179. stats = "%5d %8s %8s" % (ds[0], _format_number(ds[1] - ds[2]), _format_number(ds[3]))
  1180. ax.text(0.97, 0.5, stats,
  1181. horizontalalignment="left", verticalalignment="center",
  1182. transform=ax.transAxes, fontsize=14, family="monospace",
  1183. backgroundcolor=backgrounds[ds[1] <= ds[2]],
  1184. color="black" if args.background == "white" else "white")
  1185. axes[0].text(0.97, 1.75, " cmts delta changed",
  1186. horizontalalignment="left", verticalalignment="center",
  1187. transform=axes[0].transAxes, fontsize=14, family="monospace",
  1188. color="black" if args.background == "white" else "white")
  1189. axes[-1].set_axis_on()
  1190. target_num_labels = 12
  1191. num_months = (end_date.year - start_date.year) * 12 + end_date.month - start_date.month
  1192. interval = int(numpy.ceil(num_months / target_num_labels))
  1193. if interval >= 8:
  1194. interval = int(numpy.ceil(num_months / (12 * target_num_labels)))
  1195. axes[-1].xaxis.set_major_locator(matplotlib.dates.YearLocator(interval=interval))
  1196. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
  1197. else:
  1198. axes[-1].xaxis.set_major_locator(matplotlib.dates.MonthLocator(interval=interval))
  1199. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
  1200. for tick in axes[-1].xaxis.get_major_ticks():
  1201. tick.label.set_fontsize(args.font_size)
  1202. axes[-1].spines["left"].set_visible(False)
  1203. axes[-1].spines["right"].set_visible(False)
  1204. axes[-1].spines["top"].set_visible(False)
  1205. axes[-1].get_yaxis().set_visible(False)
  1206. axes[-1].set_facecolor((1.0,) * 3 + (0.0,))
  1207. title = "%s commits" % name
  1208. deploy_plot(title, args.output, args.style)
  1209. def show_old_vs_new(args, name, start_date, end_date, data):
  1210. from scipy.signal import convolve, slepian
  1211. days, people = data
  1212. start_date = datetime.fromtimestamp(start_date)
  1213. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1214. end_date = datetime.fromtimestamp(end_date)
  1215. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1216. new_lines = numpy.zeros((end_date - start_date).days + 1)
  1217. old_lines = numpy.zeros_like(new_lines)
  1218. for day, devs in days.items():
  1219. for stats in devs.values():
  1220. new_lines[day] += stats.Added
  1221. old_lines[day] += stats.Removed + stats.Changed
  1222. resolution = 32
  1223. window = slepian(len(new_lines) // resolution, 0.5)
  1224. new_lines = convolve(new_lines, window, "same")
  1225. old_lines = convolve(old_lines, window, "same")
  1226. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1227. plot_x = [start_date + timedelta(days=i) for i in range(len(new_lines))]
  1228. pyplot.fill_between(plot_x, new_lines, color="#8DB843", label="Changed new lines")
  1229. pyplot.fill_between(plot_x, old_lines, color="#E14C35", label="Changed existing lines")
  1230. pyplot.legend(loc=2, fontsize=args.font_size)
  1231. for tick in chain(pyplot.gca().xaxis.get_major_ticks(), pyplot.gca().yaxis.get_major_ticks()):
  1232. tick.label.set_fontsize(args.font_size)
  1233. deploy_plot("Additions vs changes", args.output, args.style)
  1234. def _format_number(n):
  1235. if n == 0:
  1236. return "0"
  1237. power = int(numpy.log10(abs(n)))
  1238. if power >= 6:
  1239. n = n / 1000000
  1240. if n >= 10:
  1241. n = str(int(n))
  1242. else:
  1243. n = "%.1f" % n
  1244. if n.endswith("0"):
  1245. n = n[:-2]
  1246. suffix = "M"
  1247. elif power >= 3:
  1248. n = n / 1000
  1249. if n >= 10:
  1250. n = str(int(n))
  1251. else:
  1252. n = "%.1f" % n
  1253. if n.endswith("0"):
  1254. n = n[:-2]
  1255. suffix = "K"
  1256. else:
  1257. n = str(n)
  1258. suffix = ""
  1259. return n + suffix
  1260. def main():
  1261. args = parse_args()
  1262. reader = read_input(args)
  1263. header = reader.get_header()
  1264. name = reader.get_name()
  1265. burndown_warning = "Burndown stats were not collected. Re-run hercules with --burndown."
  1266. burndown_files_warning = \
  1267. "Burndown stats for files were not collected. Re-run hercules with " \
  1268. "--burndown --burndown-files."
  1269. burndown_people_warning = \
  1270. "Burndown stats for people were not collected. Re-run hercules with " \
  1271. "--burndown --burndown-people."
  1272. couples_warning = "Coupling stats were not collected. Re-run hercules with --couples."
  1273. shotness_warning = "Structural hotness stats were not collected. Re-run hercules with " \
  1274. "--shotness. Also check --languages - the output may be empty."
  1275. sentiment_warning = "Sentiment stats were not collected. Re-run hercules with --sentiment."
  1276. devs_warning = "Devs stats were not collected. Re-run hercules with --devs."
  1277. def run_times():
  1278. rt = reader.get_run_times()
  1279. import pandas
  1280. series = pandas.to_timedelta(pandas.Series(rt).sort_values(ascending=False), unit="s")
  1281. df = pandas.concat([series, series / series.sum()], axis=1)
  1282. df.columns = ["time", "ratio"]
  1283. print(df)
  1284. def project_burndown():
  1285. try:
  1286. full_header = header + reader.get_burndown_parameters()
  1287. except KeyError:
  1288. print("project: " + burndown_warning)
  1289. return
  1290. plot_burndown(args, "project",
  1291. *load_burndown(full_header, *reader.get_project_burndown(),
  1292. resample=args.resample))
  1293. def files_burndown():
  1294. try:
  1295. full_header = header + reader.get_burndown_parameters()
  1296. except KeyError:
  1297. print(burndown_warning)
  1298. return
  1299. try:
  1300. plot_many_burndown(args, "file", full_header, reader.get_files_burndown())
  1301. except KeyError:
  1302. print("files: " + burndown_files_warning)
  1303. def people_burndown():
  1304. try:
  1305. full_header = header + reader.get_burndown_parameters()
  1306. except KeyError:
  1307. print(burndown_warning)
  1308. return
  1309. try:
  1310. plot_many_burndown(args, "person", full_header, reader.get_people_burndown())
  1311. except KeyError:
  1312. print("people: " + burndown_people_warning)
  1313. def churn_matrix():
  1314. try:
  1315. plot_churn_matrix(args, name, *load_churn_matrix(
  1316. *reader.get_people_interaction(), max_people=args.max_people))
  1317. except KeyError:
  1318. print("churn_matrix: " + burndown_people_warning)
  1319. def ownership_burndown():
  1320. try:
  1321. full_header = header + reader.get_burndown_parameters()
  1322. except KeyError:
  1323. print(burndown_warning)
  1324. return
  1325. try:
  1326. plot_ownership(args, name, *load_ownership(
  1327. full_header, *reader.get_ownership_burndown(), max_people=args.max_people))
  1328. except KeyError:
  1329. print("ownership: " + burndown_people_warning)
  1330. def couples():
  1331. try:
  1332. write_embeddings("files", args.output, not args.disable_projector,
  1333. *train_embeddings(*reader.get_files_coocc(),
  1334. tmpdir=args.couples_tmp_dir))
  1335. write_embeddings("people", args.output, not args.disable_projector,
  1336. *train_embeddings(*reader.get_people_coocc(),
  1337. tmpdir=args.couples_tmp_dir))
  1338. except KeyError:
  1339. print(couples_warning)
  1340. try:
  1341. write_embeddings("shotness", args.output, not args.disable_projector,
  1342. *train_embeddings(*reader.get_shotness_coocc(),
  1343. tmpdir=args.couples_tmp_dir))
  1344. except KeyError:
  1345. print(shotness_warning)
  1346. def shotness():
  1347. try:
  1348. data = reader.get_shotness()
  1349. except KeyError:
  1350. print(shotness_warning)
  1351. return
  1352. show_shotness_stats(data)
  1353. def sentiment():
  1354. try:
  1355. data = reader.get_sentiment()
  1356. except KeyError:
  1357. print(sentiment_warning)
  1358. return
  1359. show_sentiment_stats(args, reader.get_name(), args.resample, reader.get_header()[0], data)
  1360. def devs():
  1361. try:
  1362. data = reader.get_devs()
  1363. except KeyError:
  1364. print(devs_warning)
  1365. return
  1366. show_devs(args, reader.get_name(), *reader.get_header(), data)
  1367. def old_vs_new():
  1368. try:
  1369. data = reader.get_devs()
  1370. except KeyError:
  1371. print(devs_warning)
  1372. return
  1373. show_old_vs_new(args, reader.get_name(), *reader.get_header(), data)
  1374. modes = {
  1375. "run-times": run_times,
  1376. "burndown-project": project_burndown,
  1377. "burndown-file": files_burndown,
  1378. "burndown-person": people_burndown,
  1379. "churn-matrix": churn_matrix,
  1380. "ownership": ownership_burndown,
  1381. "couples": couples,
  1382. "shotness": shotness,
  1383. "sentiment": sentiment,
  1384. "devs": devs,
  1385. "old-vs-new": old_vs_new,
  1386. }
  1387. try:
  1388. modes[args.mode]()
  1389. except KeyError:
  1390. assert args.mode == "all"
  1391. project_burndown()
  1392. files_burndown()
  1393. people_burndown()
  1394. churn_matrix()
  1395. ownership_burndown()
  1396. couples()
  1397. shotness()
  1398. sentiment()
  1399. devs()
  1400. if web_server.running:
  1401. secs = int(os.getenv("COUPLES_SERVER_TIME", "60"))
  1402. print("Sleeping for %d seconds, safe to Ctrl-C" % secs)
  1403. sys.stdout.flush()
  1404. try:
  1405. time.sleep(secs)
  1406. except KeyboardInterrupt:
  1407. pass
  1408. web_server.stop()
  1409. if __name__ == "__main__":
  1410. sys.exit(main())