labours.py 61 KB

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