labours.py 61 KB

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