labours.py 61 KB

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