labours.py 59 KB

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