labours.py 58 KB

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