labours.py 62 KB

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