labours.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  1. #!/usr/bin/env python3
  2. import argparse
  3. import contextlib
  4. from collections import defaultdict, namedtuple
  5. from datetime import datetime, timedelta
  6. from importlib import import_module
  7. import io
  8. from itertools import chain
  9. import json
  10. import os
  11. import re
  12. import shutil
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import threading
  17. import time
  18. import warnings
  19. import tqdm
  20. import numpy
  21. import yaml
  22. if sys.version_info[0] < 3:
  23. # OK, ancients, I will support Python 2, but you owe me a beer
  24. input = raw_input # noqa: F821
  25. def list_matplotlib_styles():
  26. script = "import sys; from matplotlib import pyplot; " \
  27. "sys.stdout.write(repr(pyplot.style.available))"
  28. styles = eval(subprocess.check_output([sys.executable, "-c", script]))
  29. styles.remove("classic")
  30. return ["default", "classic"] + styles
  31. def parse_args():
  32. parser = argparse.ArgumentParser()
  33. parser.add_argument("-o", "--output", default="",
  34. help="Path to the output file/directory (empty for display). "
  35. "If the extension is JSON, the data is saved instead of "
  36. "the real image.")
  37. parser.add_argument("-i", "--input", default="-",
  38. help="Path to the input file (- for stdin).")
  39. parser.add_argument("-f", "--input-format", default="auto", choices=["yaml", "pb", "auto"])
  40. parser.add_argument("--font-size", default=12, type=int,
  41. help="Size of the labels and legend.")
  42. parser.add_argument("--style", default="ggplot", choices=list_matplotlib_styles(),
  43. help="Plot style to use.")
  44. parser.add_argument("--backend", help="Matplotlib backend to use.")
  45. parser.add_argument("--background", choices=["black", "white"], default="white",
  46. help="Plot's general color scheme.")
  47. parser.add_argument("--size", help="Axes' size in inches, for example \"12,9\"")
  48. parser.add_argument("--relative", action="store_true",
  49. help="Occupy 100%% height for every measurement.")
  50. parser.add_argument("--tmpdir", help="Temporary directory for intermediate files.")
  51. parser.add_argument("-m", "--mode", dest="modes", default=[], action="append",
  52. choices=["burndown-project", "burndown-file", "burndown-person",
  53. "overwrites-matrix", "ownership", "couples-files",
  54. "couples-people", "couples-shotness", "shotness", "sentiment",
  55. "devs", "devs-efforts", "old-vs-new", "run-times",
  56. "languages", "devs-parallel", "all"],
  57. help="What to plot. Can be repeated, e.g. "
  58. "-m burndown-project -m run-times")
  59. parser.add_argument(
  60. "--resample", default="year",
  61. help="The way to resample the time series. Possible values are: "
  62. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  63. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  64. "#offset-aliases).")
  65. dateutil_url = "https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse"
  66. parser.add_argument("--start-date",
  67. help="Start date of time-based plots. Any format is accepted which is "
  68. "supported by %s" % dateutil_url)
  69. parser.add_argument("--end-date",
  70. help="End date of time-based plots. Any format is accepted which is "
  71. "supported by %s" % dateutil_url)
  72. parser.add_argument("--disable-projector", action="store_true",
  73. help="Do not run Tensorflow Projector on couples.")
  74. parser.add_argument("--max-people", default=20, type=int,
  75. help="Maximum number of developers in overwrites matrix and people plots.")
  76. parser.add_argument("--order-ownership-by-time", action="store_true",
  77. help="Sort developers in the ownership plot according to their first "
  78. "appearance in the history. The default is sorting by the number of "
  79. "commits.")
  80. args = parser.parse_args()
  81. return args
  82. class Reader(object):
  83. def read(self, file):
  84. raise NotImplementedError
  85. def get_name(self):
  86. raise NotImplementedError
  87. def get_header(self):
  88. raise NotImplementedError
  89. def get_burndown_parameters(self):
  90. raise NotImplementedError
  91. def get_project_burndown(self):
  92. raise NotImplementedError
  93. def get_files_burndown(self):
  94. raise NotImplementedError
  95. def get_people_burndown(self):
  96. raise NotImplementedError
  97. def get_ownership_burndown(self):
  98. raise NotImplementedError
  99. def get_people_interaction(self):
  100. raise NotImplementedError
  101. def get_files_coocc(self):
  102. raise NotImplementedError
  103. def get_people_coocc(self):
  104. raise NotImplementedError
  105. def get_shotness_coocc(self):
  106. raise NotImplementedError
  107. def get_shotness(self):
  108. raise NotImplementedError
  109. def get_sentiment(self):
  110. raise NotImplementedError
  111. def get_devs(self):
  112. raise NotImplementedError
  113. class YamlReader(Reader):
  114. def read(self, file):
  115. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  116. try:
  117. loader = yaml.CLoader
  118. except AttributeError:
  119. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  120. loader = yaml.Loader
  121. try:
  122. if file != "-":
  123. with open(file) as fin:
  124. data = yaml.load(fin, Loader=loader)
  125. else:
  126. data = yaml.load(sys.stdin, Loader=loader)
  127. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  128. print("\nInvalid unicode in the input: %s\nPlease filter it through "
  129. "fix_yaml_unicode.py" % e)
  130. sys.exit(1)
  131. if data is None:
  132. print("\nNo data has been read - has Hercules crashed?")
  133. sys.exit(1)
  134. self.data = data
  135. def get_run_times(self):
  136. return {}
  137. def get_name(self):
  138. return self.data["hercules"]["repository"]
  139. def get_header(self):
  140. header = self.data["hercules"]
  141. return header["begin_unix_time"], header["end_unix_time"]
  142. def get_burndown_parameters(self):
  143. header = self.data["Burndown"]
  144. return header["sampling"], header["granularity"], header["tick_size"]
  145. def get_project_burndown(self):
  146. return self.data["hercules"]["repository"], \
  147. self._parse_burndown_matrix(self.data["Burndown"]["project"]).T
  148. def get_files_burndown(self):
  149. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  150. for p in self.data["Burndown"]["files"].items()]
  151. def get_people_burndown(self):
  152. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  153. for p in self.data["Burndown"]["people"].items()]
  154. def get_ownership_burndown(self):
  155. return self.data["Burndown"]["people_sequence"].copy(), \
  156. {p[0]: self._parse_burndown_matrix(p[1])
  157. for p in self.data["Burndown"]["people"].items()}
  158. def get_people_interaction(self):
  159. return self.data["Burndown"]["people_sequence"].copy(), \
  160. self._parse_burndown_matrix(self.data["Burndown"]["people_interaction"])
  161. def get_files_coocc(self):
  162. coocc = self.data["Couples"]["files_coocc"]
  163. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  164. def get_people_coocc(self):
  165. coocc = self.data["Couples"]["people_coocc"]
  166. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  167. def get_shotness_coocc(self):
  168. shotness = self.data["Shotness"]
  169. index = ["%s:%s" % (i["file"], i["name"]) for i in shotness]
  170. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int64)
  171. indices = []
  172. data = []
  173. for i, record in enumerate(shotness):
  174. pairs = [(int(k), v) for k, v in record["counters"].items()]
  175. pairs.sort()
  176. indptr[i + 1] = indptr[i] + len(pairs)
  177. for k, v in pairs:
  178. indices.append(k)
  179. data.append(v)
  180. indices = numpy.array(indices, dtype=numpy.int32)
  181. data = numpy.array(data, dtype=numpy.int32)
  182. from scipy.sparse import csr_matrix
  183. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  184. def get_shotness(self):
  185. from munch import munchify
  186. obj = munchify(self.data["Shotness"])
  187. # turn strings into ints
  188. for item in obj:
  189. item.counters = {int(k): v for k, v in item.counters.items()}
  190. if len(obj) == 0:
  191. raise KeyError
  192. return obj
  193. def get_sentiment(self):
  194. from munch import munchify
  195. return munchify({int(key): {
  196. "Comments": vals[2].split("|"),
  197. "Commits": vals[1],
  198. "Value": float(vals[0])
  199. } for key, vals in self.data["Sentiment"].items()})
  200. def get_devs(self):
  201. people = self.data["Devs"]["people"]
  202. days = {int(d): {int(dev): DevDay(*(int(x) for x in day[:-1]), day[-1])
  203. for dev, day in devs.items()}
  204. for d, devs in self.data["Devs"]["ticks"].items()}
  205. return people, days
  206. def _parse_burndown_matrix(self, matrix):
  207. return numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  208. for line in matrix.split("\n")])
  209. def _parse_coocc_matrix(self, matrix):
  210. from scipy.sparse import csr_matrix
  211. data = []
  212. indices = []
  213. indptr = [0]
  214. for row in matrix:
  215. for k, v in sorted(row.items()):
  216. data.append(v)
  217. indices.append(k)
  218. indptr.append(indptr[-1] + len(row))
  219. return csr_matrix((data, indices, indptr), shape=(len(matrix),) * 2)
  220. class ProtobufReader(Reader):
  221. def read(self, file):
  222. try:
  223. from labours.pb_pb2 import AnalysisResults
  224. except ImportError as e:
  225. print("\n\n>>> You need to generate python/hercules/pb/pb_pb2.py - run \"make\"\n",
  226. file=sys.stderr)
  227. raise e from None
  228. self.data = AnalysisResults()
  229. if file != "-":
  230. with open(file, "rb") as fin:
  231. bytes = fin.read()
  232. else:
  233. bytes = sys.stdin.buffer.read()
  234. if not bytes:
  235. raise ValueError("empty input")
  236. self.data.ParseFromString(bytes)
  237. self.contents = {}
  238. for key, val in self.data.contents.items():
  239. try:
  240. mod, name = PB_MESSAGES[key].rsplit(".", 1)
  241. except KeyError:
  242. sys.stderr.write("Warning: there is no registered PB decoder for %s\n" % key)
  243. continue
  244. cls = getattr(import_module(mod), name)
  245. self.contents[key] = msg = cls()
  246. msg.ParseFromString(val)
  247. def get_run_times(self):
  248. return {key: val for key, val in self.data.header.run_time_per_item.items()}
  249. def get_name(self):
  250. return self.data.header.repository
  251. def get_header(self):
  252. header = self.data.header
  253. return header.begin_unix_time, header.end_unix_time
  254. def get_burndown_parameters(self):
  255. burndown = self.contents["Burndown"]
  256. return burndown.sampling, burndown.granularity, burndown.tick_size / 1000000000
  257. def get_project_burndown(self):
  258. return self._parse_burndown_matrix(self.contents["Burndown"].project)
  259. def get_files_burndown(self):
  260. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].files]
  261. def get_people_burndown(self):
  262. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].people]
  263. def get_ownership_burndown(self):
  264. people = self.get_people_burndown()
  265. return [p[0] for p in people], {p[0]: p[1].T for p in people}
  266. def get_people_interaction(self):
  267. burndown = self.contents["Burndown"]
  268. return [i.name for i in burndown.people], \
  269. self._parse_sparse_matrix(burndown.people_interaction).toarray()
  270. def get_files_coocc(self):
  271. node = self.contents["Couples"].file_couples
  272. return list(node.index), self._parse_sparse_matrix(node.matrix)
  273. def get_people_coocc(self):
  274. node = self.contents["Couples"].people_couples
  275. return list(node.index), self._parse_sparse_matrix(node.matrix)
  276. def get_shotness_coocc(self):
  277. shotness = self.get_shotness()
  278. index = ["%s:%s" % (i.file, i.name) for i in shotness]
  279. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int32)
  280. indices = []
  281. data = []
  282. for i, record in enumerate(shotness):
  283. pairs = list(record.counters.items())
  284. pairs.sort()
  285. indptr[i + 1] = indptr[i] + len(pairs)
  286. for k, v in pairs:
  287. indices.append(k)
  288. data.append(v)
  289. indices = numpy.array(indices, dtype=numpy.int32)
  290. data = numpy.array(data, dtype=numpy.int32)
  291. from scipy.sparse import csr_matrix
  292. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  293. def get_shotness(self):
  294. records = self.contents["Shotness"].records
  295. if len(records) == 0:
  296. raise KeyError
  297. return records
  298. def get_sentiment(self):
  299. byday = self.contents["Sentiment"].SentimentByDay
  300. if len(byday) == 0:
  301. raise KeyError
  302. return byday
  303. def get_devs(self):
  304. people = list(self.contents["Devs"].dev_index)
  305. days = {d: {dev: DevDay(stats.commits, stats.stats.added, stats.stats.removed,
  306. stats.stats.changed, {k: [v.added, v.removed, v.changed]
  307. for k, v in stats.languages.items()})
  308. for dev, stats in day.devs.items()}
  309. for d, day in self.contents["Devs"].ticks.items()}
  310. return people, days
  311. def _parse_burndown_matrix(self, matrix):
  312. dense = numpy.zeros((matrix.number_of_rows, matrix.number_of_columns), dtype=int)
  313. for y, row in enumerate(matrix.rows):
  314. for x, col in enumerate(row.columns):
  315. dense[y, x] = col
  316. return matrix.name, dense.T
  317. def _parse_sparse_matrix(self, matrix):
  318. from scipy.sparse import csr_matrix
  319. return csr_matrix((list(matrix.data), list(matrix.indices), list(matrix.indptr)),
  320. shape=(matrix.number_of_rows, matrix.number_of_columns))
  321. READERS = {"yaml": YamlReader, "yml": YamlReader, "pb": ProtobufReader}
  322. PB_MESSAGES = {
  323. "Burndown": "labours.pb_pb2.BurndownAnalysisResults",
  324. "Couples": "labours.pb_pb2.CouplesAnalysisResults",
  325. "Shotness": "labours.pb_pb2.ShotnessAnalysisResults",
  326. "Devs": "labours.pb_pb2.DevsAnalysisResults",
  327. }
  328. def read_input(args):
  329. sys.stdout.write("Reading the input... ")
  330. sys.stdout.flush()
  331. if args.input != "-":
  332. if args.input_format == "auto":
  333. try:
  334. args.input_format = args.input.rsplit(".", 1)[1]
  335. except IndexError:
  336. try:
  337. with open(args.input) as f:
  338. f.read(1 << 16)
  339. args.input_format = "yaml"
  340. except UnicodeDecodeError:
  341. args.input_format = "pb"
  342. elif args.input_format == "auto":
  343. args.input_format = "yaml"
  344. reader = READERS[args.input_format]()
  345. reader.read(args.input)
  346. print("done")
  347. return reader
  348. class DevDay(namedtuple("DevDay", ("Commits", "Added", "Removed", "Changed", "Languages"))):
  349. def add(self, dd):
  350. langs = defaultdict(lambda: [0] * 3)
  351. for key, val in self.Languages.items():
  352. for i in range(3):
  353. langs[key][i] += val[i]
  354. for key, val in dd.Languages.items():
  355. for i in range(3):
  356. langs[key][i] += val[i]
  357. return DevDay(Commits=self.Commits + dd.Commits,
  358. Added=self.Added + dd.Added,
  359. Removed=self.Removed + dd.Removed,
  360. Changed=self.Changed + dd.Changed,
  361. Languages=dict(langs))
  362. def fit_kaplan_meier(matrix):
  363. from lifelines import KaplanMeierFitter
  364. T = []
  365. W = []
  366. indexes = numpy.arange(matrix.shape[0], dtype=int)
  367. entries = numpy.zeros(matrix.shape[0], int)
  368. dead = set()
  369. for i in range(1, matrix.shape[1]):
  370. diff = matrix[:, i - 1] - matrix[:, i]
  371. entries[diff < 0] = i
  372. mask = diff > 0
  373. deaths = diff[mask]
  374. T.append(numpy.full(len(deaths), i) - entries[indexes[mask]])
  375. W.append(deaths)
  376. entered = entries > 0
  377. entered[0] = True
  378. dead = dead.union(set(numpy.where((matrix[:, i] == 0) & entered)[0]))
  379. # add the survivors as censored
  380. nnzind = entries != 0
  381. nnzind[0] = True
  382. nnzind[sorted(dead)] = False
  383. T.append(numpy.full(nnzind.sum(), matrix.shape[1]) - entries[nnzind])
  384. W.append(matrix[nnzind, -1])
  385. T = numpy.concatenate(T)
  386. E = numpy.ones(len(T), bool)
  387. E[-nnzind.sum():] = 0
  388. W = numpy.concatenate(W)
  389. if T.size == 0:
  390. return None
  391. kmf = KaplanMeierFitter().fit(T, E, weights=W)
  392. return kmf
  393. def print_survival_function(kmf, sampling):
  394. sf = kmf.survival_function_
  395. sf.index = [timedelta(days=d) for d in sf.index * sampling]
  396. sf.columns = ["Ratio of survived lines"]
  397. try:
  398. print(sf[len(sf) // 6::len(sf) // 6].append(sf.tail(1)))
  399. except ValueError:
  400. pass
  401. def interpolate_burndown_matrix(matrix, granularity, sampling, progress=False):
  402. daily = numpy.zeros(
  403. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  404. dtype=numpy.float32)
  405. """
  406. ----------> samples, x
  407. |
  408. |
  409. |
  410. bands, y
  411. """
  412. for y in tqdm.tqdm(range(matrix.shape[0]), disable=(not progress)):
  413. for x in range(matrix.shape[1]):
  414. if y * granularity > (x + 1) * sampling:
  415. # the future is zeros
  416. continue
  417. def decay(start_index: int, start_val: float):
  418. if start_val == 0:
  419. return
  420. k = matrix[y][x] / start_val # <= 1
  421. scale = (x + 1) * sampling - start_index
  422. for i in range(y * granularity, (y + 1) * granularity):
  423. initial = daily[i][start_index - 1]
  424. for j in range(start_index, (x + 1) * sampling):
  425. daily[i][j] = initial * (
  426. 1 + (k - 1) * (j - start_index + 1) / scale)
  427. def grow(finish_index: int, finish_val: float):
  428. initial = matrix[y][x - 1] if x > 0 else 0
  429. start_index = x * sampling
  430. if start_index < y * granularity:
  431. start_index = y * granularity
  432. if finish_index == start_index:
  433. return
  434. avg = (finish_val - initial) / (finish_index - start_index)
  435. for j in range(x * sampling, finish_index):
  436. for i in range(start_index, j + 1):
  437. daily[i][j] = avg
  438. # copy [x*g..y*s)
  439. for j in range(x * sampling, finish_index):
  440. for i in range(y * granularity, x * sampling):
  441. daily[i][j] = daily[i][j - 1]
  442. if (y + 1) * granularity >= (x + 1) * sampling:
  443. # x*granularity <= (y+1)*sampling
  444. # 1. x*granularity <= y*sampling
  445. # y*sampling..(y+1)sampling
  446. #
  447. # x+1
  448. # /
  449. # /
  450. # / y+1 -|
  451. # / |
  452. # / y -|
  453. # /
  454. # / x
  455. #
  456. # 2. x*granularity > y*sampling
  457. # x*granularity..(y+1)sampling
  458. #
  459. # x+1
  460. # /
  461. # /
  462. # / y+1 -|
  463. # / |
  464. # / x -|
  465. # /
  466. # / y
  467. if y * granularity <= x * sampling:
  468. grow((x + 1) * sampling, matrix[y][x])
  469. elif (x + 1) * sampling > y * granularity:
  470. grow((x + 1) * sampling, matrix[y][x])
  471. avg = matrix[y][x] / ((x + 1) * sampling - y * granularity)
  472. for j in range(y * granularity, (x + 1) * sampling):
  473. for i in range(y * granularity, j + 1):
  474. daily[i][j] = avg
  475. elif (y + 1) * granularity >= x * sampling:
  476. # y*sampling <= (x+1)*granularity < (y+1)sampling
  477. # y*sampling..(x+1)*granularity
  478. # (x+1)*granularity..(y+1)sampling
  479. # x+1
  480. # /\
  481. # / \
  482. # / \
  483. # / y+1
  484. # /
  485. # y
  486. v1 = matrix[y][x - 1]
  487. v2 = matrix[y][x]
  488. delta = (y + 1) * granularity - x * sampling
  489. previous = 0
  490. if x > 0 and (x - 1) * sampling >= y * granularity:
  491. # x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  492. # |________|.......^
  493. if x > 1:
  494. previous = matrix[y][x - 2]
  495. scale = sampling
  496. else:
  497. # (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  498. # |______|.......^
  499. scale = sampling if x == 0 else x * sampling - y * granularity
  500. peak = v1 + (v1 - previous) / scale * delta
  501. if v2 > peak:
  502. # we need to adjust the peak, it may not be less than the decayed value
  503. if x < matrix.shape[1] - 1:
  504. # y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  505. # ^.........|_________|
  506. k = (v2 - matrix[y][x + 1]) / sampling # > 0
  507. peak = matrix[y][x] + k * ((x + 1) * sampling - (y + 1) * granularity)
  508. # peak > v2 > v1
  509. else:
  510. peak = v2
  511. # not enough data to interpolate; this is at least not restricted
  512. grow((y + 1) * granularity, peak)
  513. decay((y + 1) * granularity, peak)
  514. else:
  515. # (x+1)*granularity < y*sampling
  516. # y*sampling..(y+1)sampling
  517. decay(x * sampling, matrix[y][x - 1])
  518. return daily
  519. def import_pandas():
  520. import pandas
  521. try:
  522. from pandas.plotting import register_matplotlib_converters
  523. register_matplotlib_converters()
  524. except ImportError:
  525. pass
  526. return pandas
  527. def floor_datetime(dt, duration):
  528. return datetime.fromtimestamp(dt.timestamp() - dt.timestamp() % duration)
  529. def load_burndown(
  530. header,
  531. name,
  532. matrix,
  533. resample,
  534. report_survival=True,
  535. interpolation_progress=False
  536. ):
  537. pandas = import_pandas()
  538. start, last, sampling, granularity, tick = header
  539. assert sampling > 0
  540. assert granularity > 0
  541. start = floor_datetime(datetime.fromtimestamp(start), tick)
  542. last = datetime.fromtimestamp(last)
  543. if report_survival:
  544. kmf = fit_kaplan_meier(matrix)
  545. if kmf is not None:
  546. print_survival_function(kmf, sampling)
  547. finish = start + timedelta(seconds=matrix.shape[1] * sampling * tick)
  548. if resample not in ("no", "raw"):
  549. print("resampling to %s, please wait..." % resample)
  550. # Interpolate the day x day matrix.
  551. # Each day brings equal weight in the granularity.
  552. # Sampling's interpolation is linear.
  553. daily = interpolate_burndown_matrix(
  554. matrix=matrix,
  555. granularity=granularity,
  556. sampling=sampling,
  557. progress=interpolation_progress,
  558. )
  559. daily[(last - start).days:] = 0
  560. # Resample the bands
  561. aliases = {
  562. "year": "A",
  563. "month": "M"
  564. }
  565. resample = aliases.get(resample, resample)
  566. periods = 0
  567. date_granularity_sampling = [start]
  568. while date_granularity_sampling[-1] < finish:
  569. periods += 1
  570. date_granularity_sampling = pandas.date_range(
  571. start, periods=periods, freq=resample)
  572. if date_granularity_sampling[0] > finish:
  573. if resample == "A":
  574. print("too loose resampling - by year, trying by month")
  575. return load_burndown(header, name, matrix, "month", report_survival=False)
  576. else:
  577. raise ValueError("Too loose resampling: %s. Try finer." % resample)
  578. date_range_sampling = pandas.date_range(
  579. date_granularity_sampling[0],
  580. periods=(finish - date_granularity_sampling[0]).days,
  581. freq="1D")
  582. # Fill the new square matrix
  583. matrix = numpy.zeros(
  584. (len(date_granularity_sampling), len(date_range_sampling)),
  585. dtype=numpy.float32)
  586. for i, gdt in enumerate(date_granularity_sampling):
  587. istart = (date_granularity_sampling[i - 1] - start).days \
  588. if i > 0 else 0
  589. ifinish = (gdt - start).days
  590. for j, sdt in enumerate(date_range_sampling):
  591. if (sdt - start).days >= istart:
  592. break
  593. matrix[i, j:] = \
  594. daily[istart:ifinish, (sdt - start).days:].sum(axis=0)
  595. # Hardcode some cases to improve labels' readability
  596. if resample in ("year", "A"):
  597. labels = [dt.year for dt in date_granularity_sampling]
  598. elif resample in ("month", "M"):
  599. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  600. else:
  601. labels = [dt.date() for dt in date_granularity_sampling]
  602. else:
  603. labels = [
  604. "%s - %s" % ((start + timedelta(seconds=i * granularity * tick)).date(),
  605. (
  606. start + timedelta(seconds=(i + 1) * granularity * tick)).date())
  607. for i in range(matrix.shape[0])]
  608. if len(labels) > 18:
  609. warnings.warn("Too many labels - consider resampling.")
  610. resample = "M" # fake resampling type is checked while plotting
  611. date_range_sampling = pandas.date_range(
  612. start + timedelta(seconds=sampling * tick), periods=matrix.shape[1],
  613. freq="%dD" % sampling)
  614. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  615. def load_ownership(header, sequence, contents, max_people, order_by_time):
  616. pandas = import_pandas()
  617. start, last, sampling, _, tick = header
  618. start = datetime.fromtimestamp(start)
  619. start = floor_datetime(start, tick)
  620. last = datetime.fromtimestamp(last)
  621. people = []
  622. for name in sequence:
  623. people.append(contents[name].sum(axis=1))
  624. people = numpy.array(people)
  625. date_range_sampling = pandas.date_range(
  626. start + timedelta(seconds=sampling * tick), periods=people[0].shape[0],
  627. freq="%dD" % sampling)
  628. if people.shape[0] > max_people:
  629. chosen = numpy.argpartition(-numpy.sum(people, axis=1), max_people)
  630. others = people[chosen[max_people:]].sum(axis=0)
  631. people = people[chosen[:max_people + 1]]
  632. people[max_people] = others
  633. sequence = [sequence[i] for i in chosen[:max_people]] + ["others"]
  634. print("Warning: truncated people to the most owning %d" % max_people)
  635. if order_by_time:
  636. appearances = numpy.argmax(people > 0, axis=1)
  637. if people.shape[0] > max_people:
  638. appearances[-1] = people.shape[1]
  639. else:
  640. appearances = -people.sum(axis=1)
  641. if people.shape[0] > max_people:
  642. appearances[-1] = 0
  643. order = numpy.argsort(appearances)
  644. people = people[order]
  645. sequence = [sequence[i] for i in order]
  646. for i, name in enumerate(sequence):
  647. if len(name) > 40:
  648. sequence[i] = name[:37] + "..."
  649. return sequence, people, date_range_sampling, last
  650. def load_overwrites_matrix(people, matrix, max_people, normalize=True):
  651. matrix = matrix.astype(float)
  652. if matrix.shape[0] > max_people:
  653. order = numpy.argsort(-matrix[:, 0])
  654. matrix = matrix[order[:max_people]][:, [0, 1] + list(2 + order[:max_people])]
  655. people = [people[i] for i in order[:max_people]]
  656. print("Warning: truncated people to most productive %d" % max_people)
  657. if normalize:
  658. zeros = matrix[:, 0] == 0
  659. matrix[zeros, :] = 1
  660. matrix /= matrix[:, 0][:, None]
  661. matrix[zeros, :] = 0
  662. matrix = -matrix[:, 1:]
  663. for i, name in enumerate(people):
  664. if len(name) > 40:
  665. people[i] = name[:37] + "..."
  666. return people, matrix
  667. def import_pyplot(backend, style):
  668. import matplotlib
  669. if backend:
  670. matplotlib.use(backend)
  671. from matplotlib import pyplot
  672. pyplot.style.use(style)
  673. print("matplotlib: backend is", matplotlib.get_backend())
  674. return matplotlib, pyplot
  675. def apply_plot_style(figure, axes, legend, background, font_size, axes_size):
  676. foreground = "black" if background == "white" else "white"
  677. if axes_size is None:
  678. axes_size = (16, 12)
  679. else:
  680. axes_size = tuple(float(p) for p in axes_size.split(","))
  681. figure.set_size_inches(*axes_size)
  682. for side in ("bottom", "top", "left", "right"):
  683. axes.spines[side].set_color(foreground)
  684. for axis in (axes.xaxis, axes.yaxis):
  685. axis.label.update(dict(fontsize=font_size, color=foreground))
  686. for axis in ("x", "y"):
  687. getattr(axes, axis + "axis").get_offset_text().set_size(font_size)
  688. axes.tick_params(axis=axis, colors=foreground, labelsize=font_size)
  689. try:
  690. axes.ticklabel_format(axis="y", style="sci", scilimits=(0, 3))
  691. except AttributeError:
  692. pass
  693. figure.patch.set_facecolor(background)
  694. axes.set_facecolor(background)
  695. if legend is not None:
  696. frame = legend.get_frame()
  697. for setter in (frame.set_facecolor, frame.set_edgecolor):
  698. setter(background)
  699. for text in legend.get_texts():
  700. text.set_color(foreground)
  701. def get_plot_path(base, name):
  702. root, ext = os.path.splitext(base)
  703. if not ext:
  704. ext = ".png"
  705. output = os.path.join(root, name + ext)
  706. os.makedirs(os.path.dirname(output), exist_ok=True)
  707. return output
  708. def deploy_plot(title, output, background, tight=True):
  709. import matplotlib.pyplot as pyplot
  710. if not output:
  711. pyplot.gcf().canvas.set_window_title(title)
  712. pyplot.show()
  713. else:
  714. if title:
  715. pyplot.title(title, color="black" if background == "white" else "white")
  716. if tight:
  717. try:
  718. pyplot.tight_layout()
  719. except: # noqa: E722
  720. print("Warning: failed to set the tight layout")
  721. print("Writing plot to %s" % output)
  722. pyplot.savefig(output, transparent=True)
  723. pyplot.clf()
  724. def default_json(x):
  725. if hasattr(x, "tolist"):
  726. return x.tolist()
  727. if hasattr(x, "isoformat"):
  728. return x.isoformat()
  729. return x
  730. def parse_date(text, default):
  731. if not text:
  732. return default
  733. from dateutil.parser import parse
  734. return parse(text)
  735. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  736. sampling, resample):
  737. if args.output and args.output.endswith(".json"):
  738. data = locals().copy()
  739. del data["args"]
  740. data["type"] = "burndown"
  741. if args.mode == "project" and target == "project":
  742. output = args.output
  743. else:
  744. if target == "project":
  745. name = "project"
  746. output = get_plot_path(args.output, name)
  747. with open(output, "w") as fout:
  748. json.dump(data, fout, sort_keys=True, default=default_json)
  749. return
  750. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  751. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  752. if args.relative:
  753. for i in range(matrix.shape[1]):
  754. matrix[:, i] /= matrix[:, i].sum()
  755. pyplot.ylim(0, 1)
  756. legend_loc = 3
  757. else:
  758. legend_loc = 2
  759. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size)
  760. pyplot.ylabel("Lines of code")
  761. pyplot.xlabel("Time")
  762. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  763. args.font_size, args.size)
  764. pyplot.xlim(parse_date(args.start_date, date_range_sampling[0]),
  765. parse_date(args.end_date, date_range_sampling[-1]))
  766. locator = pyplot.gca().xaxis.get_major_locator()
  767. # set the optimal xticks locator
  768. if "M" not in resample:
  769. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  770. locs = pyplot.gca().get_xticks().tolist()
  771. if len(locs) >= 16:
  772. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  773. locs = pyplot.gca().get_xticks().tolist()
  774. if len(locs) >= 16:
  775. pyplot.gca().xaxis.set_major_locator(locator)
  776. if locs[0] < pyplot.xlim()[0]:
  777. del locs[0]
  778. endindex = -1
  779. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  780. locs.append(pyplot.xlim()[1])
  781. endindex = len(locs) - 1
  782. startindex = -1
  783. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  784. locs.append(pyplot.xlim()[0])
  785. startindex = len(locs) - 1
  786. pyplot.gca().set_xticks(locs)
  787. # hacking time!
  788. labels = pyplot.gca().get_xticklabels()
  789. if startindex >= 0:
  790. labels[startindex].set_text(date_range_sampling[0].date())
  791. labels[startindex].set_text = lambda _: None
  792. labels[startindex].set_rotation(30)
  793. labels[startindex].set_ha("right")
  794. if endindex >= 0:
  795. labels[endindex].set_text(date_range_sampling[-1].date())
  796. labels[endindex].set_text = lambda _: None
  797. labels[endindex].set_rotation(30)
  798. labels[endindex].set_ha("right")
  799. title = "%s %d x %d (granularity %d, sampling %d)" % \
  800. ((name,) + matrix.shape + (granularity, sampling))
  801. output = args.output
  802. if output:
  803. if args.mode == "project" and target == "project":
  804. output = args.output
  805. else:
  806. if target == "project":
  807. name = "project"
  808. output = get_plot_path(args.output, name)
  809. deploy_plot(title, output, args.background)
  810. def plot_many_burndown(args, target, header, parts):
  811. if not args.output:
  812. print("Warning: output not set, showing %d plots." % len(parts))
  813. stdout = io.StringIO()
  814. for name, matrix in tqdm.tqdm(parts):
  815. with contextlib.redirect_stdout(stdout):
  816. plot_burndown(args, target, *load_burndown(header, name, matrix, args.resample))
  817. sys.stdout.write(stdout.getvalue())
  818. def plot_overwrites_matrix(args, repo, people, matrix):
  819. if args.output and args.output.endswith(".json"):
  820. data = locals().copy()
  821. del data["args"]
  822. data["type"] = "overwrites_matrix"
  823. if args.mode == "all":
  824. output = get_plot_path(args.output, "matrix")
  825. else:
  826. output = args.output
  827. with open(output, "w") as fout:
  828. json.dump(data, fout, sort_keys=True, default=default_json)
  829. return
  830. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  831. s = 4 + matrix.shape[1] * 0.3
  832. fig = pyplot.figure(figsize=(s, s))
  833. ax = fig.add_subplot(111)
  834. ax.xaxis.set_label_position("top")
  835. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  836. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  837. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  838. ax.set_yticklabels(people, va="center")
  839. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  840. ax.set_xticklabels(["Unidentified"] + people, rotation=45, ha="left",
  841. va="bottom", rotation_mode="anchor")
  842. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  843. ax.grid(False)
  844. ax.grid(which="minor")
  845. apply_plot_style(fig, ax, None, args.background, args.font_size, args.size)
  846. if not args.output:
  847. pos1 = ax.get_position()
  848. pos2 = (pos1.x0 + 0.15, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  849. ax.set_position(pos2)
  850. if args.mode == "all" and args.output:
  851. output = get_plot_path(args.output, "matrix")
  852. else:
  853. output = args.output
  854. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  855. if args.output:
  856. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  857. title = ""
  858. deploy_plot(title, output, args.background)
  859. def plot_ownership(args, repo, names, people, date_range, last):
  860. if args.output and args.output.endswith(".json"):
  861. data = locals().copy()
  862. del data["args"]
  863. data["type"] = "ownership"
  864. if args.mode == "all" and args.output:
  865. output = get_plot_path(args.output, "people")
  866. else:
  867. output = args.output
  868. with open(output, "w") as fout:
  869. json.dump(data, fout, sort_keys=True, default=default_json)
  870. return
  871. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  872. polys = pyplot.stackplot(date_range, people, labels=names)
  873. if names[-1] == "others":
  874. polys[-1].set_hatch("/")
  875. pyplot.xlim(parse_date(args.start_date, date_range[0]), parse_date(args.end_date, last))
  876. if args.relative:
  877. for i in range(people.shape[1]):
  878. people[:, i] /= people[:, i].sum()
  879. pyplot.ylim(0, 1)
  880. legend_loc = 3
  881. else:
  882. legend_loc = 2
  883. ncol = 1 if len(names) < 15 else 2
  884. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size, ncol=ncol)
  885. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  886. args.font_size, args.size)
  887. if args.mode == "all" and args.output:
  888. output = get_plot_path(args.output, "people")
  889. else:
  890. output = args.output
  891. deploy_plot("%s code ownership through time" % repo, output, args.background)
  892. IDEAL_SHARD_SIZE = 4096
  893. def train_embeddings(index, matrix, tmpdir, shard_size=IDEAL_SHARD_SIZE):
  894. import tensorflow as tf
  895. try:
  896. from . import swivel
  897. except (SystemError, ImportError):
  898. import swivel
  899. assert matrix.shape[0] == matrix.shape[1]
  900. assert len(index) <= matrix.shape[0]
  901. outlier_threshold = numpy.percentile(matrix.data, 99)
  902. matrix.data[matrix.data > outlier_threshold] = outlier_threshold
  903. nshards = len(index) // shard_size
  904. if nshards * shard_size < len(index):
  905. nshards += 1
  906. shard_size = len(index) // nshards
  907. nshards = len(index) // shard_size
  908. remainder = len(index) - nshards * shard_size
  909. if remainder > 0:
  910. lengths = matrix.indptr[1:] - matrix.indptr[:-1]
  911. filtered = sorted(numpy.argsort(lengths)[remainder:])
  912. else:
  913. filtered = list(range(len(index)))
  914. if len(filtered) < matrix.shape[0]:
  915. print("Truncating the sparse matrix...")
  916. matrix = matrix[filtered, :][:, filtered]
  917. meta_index = []
  918. for i, j in enumerate(filtered):
  919. meta_index.append((index[j], matrix[i, i]))
  920. index = [mi[0] for mi in meta_index]
  921. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  922. print("Writing Swivel metadata...")
  923. vocabulary = "\n".join(index)
  924. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  925. out.write(vocabulary)
  926. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  927. out.write(vocabulary)
  928. del vocabulary
  929. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  930. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  931. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  932. out.write(bool_sums_str)
  933. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  934. out.write(bool_sums_str)
  935. del bool_sums_str
  936. reorder = numpy.argsort(-bool_sums)
  937. print("Writing Swivel shards...")
  938. for row in range(nshards):
  939. for col in range(nshards):
  940. def _int64s(xs):
  941. return tf.train.Feature(
  942. int64_list=tf.train.Int64List(value=list(xs)))
  943. def _floats(xs):
  944. return tf.train.Feature(
  945. float_list=tf.train.FloatList(value=list(xs)))
  946. indices_row = reorder[row::nshards]
  947. indices_col = reorder[col::nshards]
  948. shard = matrix[indices_row][:, indices_col].tocoo()
  949. example = tf.train.Example(features=tf.train.Features(feature={
  950. "global_row": _int64s(indices_row),
  951. "global_col": _int64s(indices_col),
  952. "sparse_local_row": _int64s(shard.row),
  953. "sparse_local_col": _int64s(shard.col),
  954. "sparse_value": _floats(shard.data)}))
  955. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  956. out.write(example.SerializeToString())
  957. print("Training Swivel model...")
  958. swivel.FLAGS.submatrix_rows = shard_size
  959. swivel.FLAGS.submatrix_cols = shard_size
  960. if len(meta_index) <= IDEAL_SHARD_SIZE / 16:
  961. embedding_size = 50
  962. num_epochs = 100000
  963. elif len(meta_index) <= IDEAL_SHARD_SIZE:
  964. embedding_size = 50
  965. num_epochs = 50000
  966. elif len(meta_index) <= IDEAL_SHARD_SIZE * 2:
  967. embedding_size = 60
  968. num_epochs = 10000
  969. elif len(meta_index) <= IDEAL_SHARD_SIZE * 4:
  970. embedding_size = 70
  971. num_epochs = 8000
  972. elif len(meta_index) <= IDEAL_SHARD_SIZE * 10:
  973. embedding_size = 80
  974. num_epochs = 5000
  975. elif len(meta_index) <= IDEAL_SHARD_SIZE * 25:
  976. embedding_size = 100
  977. num_epochs = 1000
  978. elif len(meta_index) <= IDEAL_SHARD_SIZE * 100:
  979. embedding_size = 200
  980. num_epochs = 600
  981. else:
  982. embedding_size = 300
  983. num_epochs = 300
  984. if os.getenv("CI"):
  985. # Travis, AppVeyor etc. during the integration tests
  986. num_epochs /= 10
  987. swivel.FLAGS.embedding_size = embedding_size
  988. swivel.FLAGS.input_base_path = tmproot
  989. swivel.FLAGS.output_base_path = tmproot
  990. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  991. swivel.FLAGS.num_epochs = num_epochs
  992. # Tensorflow 1.5 parses sys.argv unconditionally *applause*
  993. argv_backup = sys.argv[1:]
  994. del sys.argv[1:]
  995. swivel.main(None)
  996. sys.argv.extend(argv_backup)
  997. print("Reading Swivel embeddings...")
  998. embeddings = []
  999. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  1000. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  1001. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  1002. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  1003. assert prow[0] == pcol[0]
  1004. erow, ecol = \
  1005. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  1006. for p in (prow, pcol))
  1007. embeddings.append((erow + ecol) / 2)
  1008. return meta_index, embeddings
  1009. class CORSWebServer(object):
  1010. def __init__(self):
  1011. self.thread = threading.Thread(target=self.serve)
  1012. self.server = None
  1013. def serve(self):
  1014. outer = self
  1015. try:
  1016. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  1017. except ImportError: # Python 2
  1018. from BaseHTTPServer import HTTPServer, test
  1019. from SimpleHTTPServer import SimpleHTTPRequestHandler
  1020. class ClojureServer(HTTPServer):
  1021. def __init__(self, *args, **kwargs):
  1022. HTTPServer.__init__(self, *args, **kwargs)
  1023. outer.server = self
  1024. class CORSRequestHandler(SimpleHTTPRequestHandler):
  1025. def end_headers(self):
  1026. self.send_header("Access-Control-Allow-Origin", "*")
  1027. SimpleHTTPRequestHandler.end_headers(self)
  1028. test(CORSRequestHandler, ClojureServer)
  1029. def start(self):
  1030. self.thread.start()
  1031. def stop(self):
  1032. if self.running:
  1033. self.server.shutdown()
  1034. self.thread.join()
  1035. @property
  1036. def running(self):
  1037. return self.server is not None
  1038. web_server = CORSWebServer()
  1039. def write_embeddings(name, output, run_server, index, embeddings):
  1040. print("Writing Tensorflow Projector files...")
  1041. if not output:
  1042. output = "couples"
  1043. if output.endswith(".json"):
  1044. output = os.path.join(output[:-5], "couples")
  1045. run_server = False
  1046. metaf = "%s_%s_meta.tsv" % (output, name)
  1047. with open(metaf, "w") as fout:
  1048. fout.write("name\tcommits\n")
  1049. for pair in index:
  1050. fout.write("%s\t%s\n" % pair)
  1051. print("Wrote", metaf)
  1052. dataf = "%s_%s_data.tsv" % (output, name)
  1053. with open(dataf, "w") as fout:
  1054. for vec in embeddings:
  1055. fout.write("\t".join(str(v) for v in vec))
  1056. fout.write("\n")
  1057. print("Wrote", dataf)
  1058. jsonf = "%s_%s.json" % (output, name)
  1059. with open(jsonf, "w") as fout:
  1060. fout.write("""{
  1061. "embeddings": [
  1062. {
  1063. "tensorName": "%s %s coupling",
  1064. "tensorShape": [%s, %s],
  1065. "tensorPath": "http://0.0.0.0:8000/%s",
  1066. "metadataPath": "http://0.0.0.0:8000/%s"
  1067. }
  1068. ]
  1069. }
  1070. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  1071. print("Wrote %s" % jsonf)
  1072. if run_server and not web_server.running:
  1073. web_server.start()
  1074. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  1075. print(url)
  1076. if run_server:
  1077. if shutil.which("xdg-open") is not None:
  1078. os.system("xdg-open " + url)
  1079. else:
  1080. browser = os.getenv("BROWSER", "")
  1081. if browser:
  1082. os.system(browser + " " + url)
  1083. else:
  1084. print("\t" + url)
  1085. def show_shotness_stats(data):
  1086. top = sorted(((r.counters[i], i) for i, r in enumerate(data)), reverse=True)
  1087. for count, i in top:
  1088. r = data[i]
  1089. print("%8d %s:%s [%s]" % (count, r.file, r.name, r.internal_role))
  1090. def show_sentiment_stats(args, name, resample, start_date, data):
  1091. from scipy.signal import convolve, slepian
  1092. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1093. start_date = datetime.fromtimestamp(start_date)
  1094. data = sorted(data.items())
  1095. mood = numpy.zeros(data[-1][0] + 1, dtype=numpy.float32)
  1096. timeline = numpy.array([start_date + timedelta(days=i) for i in range(mood.shape[0])])
  1097. for d, val in data:
  1098. mood[d] = (0.5 - val.Value) * 2
  1099. resolution = 32
  1100. window = slepian(len(timeline) // resolution, 0.5)
  1101. window /= window.sum()
  1102. mood_smooth = convolve(mood, window, "same")
  1103. pos = mood_smooth.copy()
  1104. pos[pos < 0] = 0
  1105. neg = mood_smooth.copy()
  1106. neg[neg >= 0] = 0
  1107. resolution = 4
  1108. window = numpy.ones(len(timeline) // resolution)
  1109. window /= window.sum()
  1110. avg = convolve(mood, window, "same")
  1111. pyplot.fill_between(timeline, pos, color="#8DB843", label="Positive")
  1112. pyplot.fill_between(timeline, neg, color="#E14C35", label="Negative")
  1113. pyplot.plot(timeline, avg, color="grey", label="Average", linewidth=5)
  1114. legend = pyplot.legend(loc=1, fontsize=args.font_size)
  1115. pyplot.ylabel("Comment sentiment")
  1116. pyplot.xlabel("Time")
  1117. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  1118. args.font_size, args.size)
  1119. pyplot.xlim(parse_date(args.start_date, timeline[0]), parse_date(args.end_date, timeline[-1]))
  1120. locator = pyplot.gca().xaxis.get_major_locator()
  1121. # set the optimal xticks locator
  1122. if "M" not in resample:
  1123. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1124. locs = pyplot.gca().get_xticks().tolist()
  1125. if len(locs) >= 16:
  1126. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1127. locs = pyplot.gca().get_xticks().tolist()
  1128. if len(locs) >= 16:
  1129. pyplot.gca().xaxis.set_major_locator(locator)
  1130. if locs[0] < pyplot.xlim()[0]:
  1131. del locs[0]
  1132. endindex = -1
  1133. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  1134. locs.append(pyplot.xlim()[1])
  1135. endindex = len(locs) - 1
  1136. startindex = -1
  1137. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  1138. locs.append(pyplot.xlim()[0])
  1139. startindex = len(locs) - 1
  1140. pyplot.gca().set_xticks(locs)
  1141. # hacking time!
  1142. labels = pyplot.gca().get_xticklabels()
  1143. if startindex >= 0:
  1144. labels[startindex].set_text(timeline[0].date())
  1145. labels[startindex].set_text = lambda _: None
  1146. labels[startindex].set_rotation(30)
  1147. labels[startindex].set_ha("right")
  1148. if endindex >= 0:
  1149. labels[endindex].set_text(timeline[-1].date())
  1150. labels[endindex].set_text = lambda _: None
  1151. labels[endindex].set_rotation(30)
  1152. labels[endindex].set_ha("right")
  1153. overall_pos = sum(2 * (0.5 - d[1].Value) for d in data if d[1].Value < 0.5)
  1154. overall_neg = sum(2 * (d[1].Value - 0.5) for d in data if d[1].Value > 0.5)
  1155. title = "%s sentiment +%.1f -%.1f δ=%.1f" % (
  1156. name, overall_pos, overall_neg, overall_pos - overall_neg)
  1157. if args.mode == "all" and args.output:
  1158. output = get_plot_path(args.output, "sentiment")
  1159. else:
  1160. output = args.output
  1161. deploy_plot(title, output, args.background)
  1162. def show_devs(args, name, start_date, end_date, people, days, max_people=50):
  1163. from scipy.signal import convolve, slepian
  1164. if len(people) > max_people:
  1165. print("Picking top %s developers by commit count" % max_people)
  1166. # pick top N developers by commit count
  1167. commits = defaultdict(int)
  1168. for devs in days.values():
  1169. for dev, stats in devs.items():
  1170. commits[dev] += stats.Commits
  1171. commits = sorted(((v, k) for k, v in commits.items()), reverse=True)
  1172. chosen_people = {people[k] for _, k in commits[:max_people]}
  1173. else:
  1174. chosen_people = set(people)
  1175. dists, devseries, devstats, route = order_commits(chosen_people, days, people)
  1176. route_map = {v: i for i, v in enumerate(route)}
  1177. # determine clusters
  1178. clusters = hdbscan_cluster_routed_series(dists, route)
  1179. keys = list(devseries.keys())
  1180. route = [keys[node] for node in route]
  1181. print("Plotting")
  1182. # smooth time series
  1183. start_date = datetime.fromtimestamp(start_date)
  1184. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1185. end_date = datetime.fromtimestamp(end_date)
  1186. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1187. size = (end_date - start_date).days + 1
  1188. plot_x = [start_date + timedelta(days=i) for i in range(size)]
  1189. resolution = 64
  1190. window = slepian(size // resolution, 0.5)
  1191. final = numpy.zeros((len(devseries), size), dtype=numpy.float32)
  1192. for i, s in enumerate(devseries.values()):
  1193. arr = numpy.array(s).transpose()
  1194. full_history = numpy.zeros(size, dtype=numpy.float32)
  1195. mask = arr[0] < size
  1196. full_history[arr[0][mask]] = arr[1][mask]
  1197. final[route_map[i]] = convolve(full_history, window, "same")
  1198. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1199. pyplot.rcParams["figure.figsize"] = (32, 16)
  1200. pyplot.rcParams["font.size"] = args.font_size
  1201. prop_cycle = pyplot.rcParams["axes.prop_cycle"]
  1202. colors = prop_cycle.by_key()["color"]
  1203. fig, axes = pyplot.subplots(final.shape[0], 1)
  1204. backgrounds = ("#C4FFDB", "#FFD0CD") if args.background == "white" else ("#05401C", "#40110E")
  1205. max_cluster = numpy.max(clusters)
  1206. for ax, series, cluster, dev_i in zip(axes, final, clusters, route):
  1207. if cluster >= 0:
  1208. color = colors[cluster % len(colors)]
  1209. i = 1
  1210. while color == "#777777":
  1211. color = colors[(max_cluster + i) % len(colors)]
  1212. i += 1
  1213. else:
  1214. # outlier
  1215. color = "#777777"
  1216. ax.fill_between(plot_x, series, color=color)
  1217. ax.set_axis_off()
  1218. author = people[dev_i]
  1219. ax.text(0.03, 0.5, author[:36] + (author[36:] and "..."),
  1220. horizontalalignment="right", verticalalignment="center",
  1221. transform=ax.transAxes, fontsize=args.font_size,
  1222. color="black" if args.background == "white" else "white")
  1223. ds = devstats[dev_i]
  1224. stats = "%5d %8s %8s" % (ds[0], _format_number(ds[1] - ds[2]), _format_number(ds[3]))
  1225. ax.text(0.97, 0.5, stats,
  1226. horizontalalignment="left", verticalalignment="center",
  1227. transform=ax.transAxes, fontsize=args.font_size, family="monospace",
  1228. backgroundcolor=backgrounds[ds[1] <= ds[2]],
  1229. color="black" if args.background == "white" else "white")
  1230. axes[0].text(0.97, 1.75, " cmts delta changed",
  1231. horizontalalignment="left", verticalalignment="center",
  1232. transform=axes[0].transAxes, fontsize=args.font_size, family="monospace",
  1233. color="black" if args.background == "white" else "white")
  1234. axes[-1].set_axis_on()
  1235. target_num_labels = 12
  1236. num_months = (end_date.year - start_date.year) * 12 + end_date.month - start_date.month
  1237. interval = int(numpy.ceil(num_months / target_num_labels))
  1238. if interval >= 8:
  1239. interval = int(numpy.ceil(num_months / (12 * target_num_labels)))
  1240. axes[-1].xaxis.set_major_locator(matplotlib.dates.YearLocator(base=max(1, interval // 12)))
  1241. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
  1242. else:
  1243. axes[-1].xaxis.set_major_locator(matplotlib.dates.MonthLocator(interval=interval))
  1244. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
  1245. for tick in axes[-1].xaxis.get_major_ticks():
  1246. tick.label.set_fontsize(args.font_size)
  1247. axes[-1].spines["left"].set_visible(False)
  1248. axes[-1].spines["right"].set_visible(False)
  1249. axes[-1].spines["top"].set_visible(False)
  1250. axes[-1].get_yaxis().set_visible(False)
  1251. axes[-1].set_facecolor((1.0,) * 3 + (0.0,))
  1252. title = ("%s commits" % name) if not args.output else ""
  1253. if args.mode == "all" and args.output:
  1254. output = get_plot_path(args.output, "time_series")
  1255. else:
  1256. output = args.output
  1257. deploy_plot(title, output, args.background)
  1258. def order_commits(chosen_people, days, people):
  1259. from seriate import seriate
  1260. try:
  1261. from fastdtw import fastdtw
  1262. except ImportError as e:
  1263. print("Cannot import fastdtw: %s\nInstall it from https://github.com/slaypni/fastdtw" % e)
  1264. sys.exit(1)
  1265. # FIXME(vmarkovtsev): remove once https://github.com/slaypni/fastdtw/pull/28 is merged&released
  1266. try:
  1267. sys.modules["fastdtw.fastdtw"].__norm = lambda p: lambda a, b: numpy.linalg.norm(
  1268. numpy.atleast_1d(a) - numpy.atleast_1d(b), p)
  1269. except KeyError:
  1270. # the native extension does not have this bug
  1271. pass
  1272. devseries = defaultdict(list)
  1273. devstats = defaultdict(lambda: DevDay(0, 0, 0, 0, {}))
  1274. for day, devs in sorted(days.items()):
  1275. for dev, stats in devs.items():
  1276. if people[dev] in chosen_people:
  1277. devseries[dev].append((day, stats.Commits))
  1278. devstats[dev] = devstats[dev].add(stats)
  1279. print("Calculating the distance matrix")
  1280. # max-normalize the time series using a sliding window
  1281. series = list(devseries.values())
  1282. for i, s in enumerate(series):
  1283. arr = numpy.array(s).transpose().astype(numpy.float32)
  1284. arr[1] /= arr[1].sum()
  1285. series[i] = arr.transpose()
  1286. # calculate the distance matrix using dynamic time warping
  1287. dists = numpy.full((len(series),) * 2, -100500, dtype=numpy.float32)
  1288. # TODO: what's the total for this progress bar?
  1289. with tqdm.tqdm() as pb:
  1290. for x, serx in enumerate(series):
  1291. dists[x, x] = 0
  1292. for y, sery in enumerate(series[x + 1:], start=x + 1):
  1293. min_day = int(min(serx[0][0], sery[0][0]))
  1294. max_day = int(max(serx[-1][0], sery[-1][0]))
  1295. arrx = numpy.zeros(max_day - min_day + 1, dtype=numpy.float32)
  1296. arry = numpy.zeros_like(arrx)
  1297. arrx[serx[:, 0].astype(int) - min_day] = serx[:, 1]
  1298. arry[sery[:, 0].astype(int) - min_day] = sery[:, 1]
  1299. # L1 norm
  1300. dist, _ = fastdtw(arrx, arry, radius=5, dist=1)
  1301. dists[x, y] = dists[y, x] = dist
  1302. pb.update()
  1303. print("Ordering the series")
  1304. route = seriate(dists)
  1305. return dists, devseries, devstats, route
  1306. def hdbscan_cluster_routed_series(dists, route):
  1307. try:
  1308. from hdbscan import HDBSCAN
  1309. except ImportError as e:
  1310. print("Cannot import hdbscan: %s" % e)
  1311. sys.exit(1)
  1312. opt_dist_chain = numpy.cumsum(numpy.array(
  1313. [0] + [dists[route[i], route[i + 1]] for i in range(len(route) - 1)]))
  1314. clusters = HDBSCAN(min_cluster_size=2).fit_predict(opt_dist_chain[:, numpy.newaxis])
  1315. return clusters
  1316. def show_devs_efforts(args, name, start_date, end_date, people, days, max_people):
  1317. from scipy.signal import convolve, slepian
  1318. start_date = datetime.fromtimestamp(start_date)
  1319. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1320. end_date = datetime.fromtimestamp(end_date)
  1321. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1322. efforts_by_dev = defaultdict(int)
  1323. for day, devs in days.items():
  1324. for dev, stats in devs.items():
  1325. efforts_by_dev[dev] += stats.Added + stats.Removed + stats.Changed
  1326. if len(efforts_by_dev) > max_people:
  1327. chosen = {v for k, v in sorted(
  1328. ((v, k) for k, v in efforts_by_dev.items()), reverse=True)[:max_people]}
  1329. print("Warning: truncated people to the most active %d" % max_people)
  1330. else:
  1331. chosen = set(efforts_by_dev)
  1332. chosen_efforts = sorted(((efforts_by_dev[k], k) for k in chosen), reverse=True)
  1333. chosen_order = {k: i for i, (_, k) in enumerate(chosen_efforts)}
  1334. efforts = numpy.zeros((len(chosen) + 1, (end_date - start_date).days + 1), dtype=numpy.float32)
  1335. for day, devs in days.items():
  1336. if day < efforts.shape[1]:
  1337. for dev, stats in devs.items():
  1338. dev = chosen_order.get(dev, len(chosen_order))
  1339. efforts[dev][day] += stats.Added + stats.Removed + stats.Changed
  1340. efforts_cum = numpy.cumsum(efforts, axis=1)
  1341. window = slepian(10, 0.5)
  1342. window /= window.sum()
  1343. for e in (efforts, efforts_cum):
  1344. for i in range(e.shape[0]):
  1345. ending = e[i][-len(window) * 2:].copy()
  1346. e[i] = convolve(e[i], window, "same")
  1347. e[i][-len(ending):] = ending
  1348. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1349. plot_x = [start_date + timedelta(days=i) for i in range(efforts.shape[1])]
  1350. people = [people[k] for _, k in chosen_efforts] + ["others"]
  1351. for i, name in enumerate(people):
  1352. if len(name) > 40:
  1353. people[i] = name[:37] + "..."
  1354. polys = pyplot.stackplot(plot_x, efforts_cum, labels=people)
  1355. if len(polys) == max_people + 1:
  1356. polys[-1].set_hatch("/")
  1357. polys = pyplot.stackplot(plot_x, -efforts * efforts_cum.max() / efforts.max())
  1358. if len(polys) == max_people + 1:
  1359. polys[-1].set_hatch("/")
  1360. yticks = []
  1361. for tick in pyplot.gca().yaxis.iter_ticks():
  1362. if tick[1] >= 0:
  1363. yticks.append(tick[1])
  1364. pyplot.gca().yaxis.set_ticks(yticks)
  1365. legend = pyplot.legend(loc=2, ncol=2, fontsize=args.font_size)
  1366. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  1367. args.font_size, args.size or "16,10")
  1368. if args.mode == "all" and args.output:
  1369. output = get_plot_path(args.output, "efforts")
  1370. else:
  1371. output = args.output
  1372. deploy_plot("Efforts through time (changed lines of code)", output, args.background)
  1373. def show_old_vs_new(args, name, start_date, end_date, people, days):
  1374. from scipy.signal import convolve, slepian
  1375. start_date = datetime.fromtimestamp(start_date)
  1376. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1377. end_date = datetime.fromtimestamp(end_date)
  1378. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1379. new_lines = numpy.zeros((end_date - start_date).days + 2)
  1380. old_lines = numpy.zeros_like(new_lines)
  1381. for day, devs in days.items():
  1382. for stats in devs.values():
  1383. new_lines[day] += stats.Added
  1384. old_lines[day] += stats.Removed + stats.Changed
  1385. resolution = 32
  1386. window = slepian(max(len(new_lines) // resolution, 1), 0.5)
  1387. new_lines = convolve(new_lines, window, "same")
  1388. old_lines = convolve(old_lines, window, "same")
  1389. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1390. plot_x = [start_date + timedelta(days=i) for i in range(len(new_lines))]
  1391. pyplot.fill_between(plot_x, new_lines, color="#8DB843", label="Changed new lines")
  1392. pyplot.fill_between(plot_x, old_lines, color="#E14C35", label="Changed existing lines")
  1393. pyplot.legend(loc=2, fontsize=args.font_size)
  1394. for tick in chain(pyplot.gca().xaxis.get_major_ticks(), pyplot.gca().yaxis.get_major_ticks()):
  1395. tick.label.set_fontsize(args.font_size)
  1396. if args.mode == "all" and args.output:
  1397. output = get_plot_path(args.output, "old_vs_new")
  1398. else:
  1399. output = args.output
  1400. deploy_plot("Additions vs changes", output, args.background)
  1401. def show_languages(args, name, start_date, end_date, people, days):
  1402. devlangs = defaultdict(lambda: defaultdict(lambda: numpy.zeros(3, dtype=int)))
  1403. for day, devs in days.items():
  1404. for dev, stats in devs.items():
  1405. for lang, vals in stats.Languages.items():
  1406. devlangs[dev][lang] += vals
  1407. devlangs = sorted(devlangs.items(), key=lambda p: -sum(x.sum() for x in p[1].values()))
  1408. for dev, ls in devlangs:
  1409. print()
  1410. print("#", people[dev])
  1411. ls = sorted(((vals.sum(), lang) for lang, vals in ls.items()), reverse=True)
  1412. for vals, lang in ls:
  1413. if lang:
  1414. print("%s: %d" % (lang, vals))
  1415. class ParallelDevData:
  1416. def __init__(self):
  1417. self.commits_rank = -1
  1418. self.commits = -1
  1419. self.lines_rank = -1
  1420. self.lines = -1
  1421. self.ownership_rank = -1
  1422. self.ownership = -1
  1423. self.couples_index = -1
  1424. self.couples_cluster = -1
  1425. self.commit_coocc_index = -1
  1426. self.commit_coocc_cluster = -1
  1427. def __str__(self):
  1428. return str(self.__dict__)
  1429. def __repr__(self):
  1430. return str(self)
  1431. def load_devs_parallel(ownership, couples, devs, max_people):
  1432. from seriate import seriate
  1433. try:
  1434. from hdbscan import HDBSCAN
  1435. except ImportError as e:
  1436. print("Cannot import ortools: %s\nInstall it from "
  1437. "https://developers.google.com/optimization/install/python/" % e)
  1438. sys.exit(1)
  1439. people, owned = ownership
  1440. _, cmatrix = couples
  1441. _, days = devs
  1442. print("calculating - commits")
  1443. commits = defaultdict(int)
  1444. for day, devs in days.items():
  1445. for dev, stats in devs.items():
  1446. commits[people[dev]] += stats.Commits
  1447. chosen = [k for v, k in sorted(((v, k) for k, v in commits.items()),
  1448. reverse=True)[:max_people]]
  1449. result = {k: ParallelDevData() for k in chosen}
  1450. for k, v in result.items():
  1451. v.commits_rank = chosen.index(k)
  1452. v.commits = commits[k]
  1453. print("calculating - lines")
  1454. lines = defaultdict(int)
  1455. for day, devs in days.items():
  1456. for dev, stats in devs.items():
  1457. lines[people[dev]] += stats.Added + stats.Removed + stats.Changed
  1458. lines_index = {k: i for i, (_, k) in enumerate(sorted(
  1459. ((v, k) for k, v in lines.items() if k in chosen), reverse=True))}
  1460. for k, v in result.items():
  1461. v.lines_rank = lines_index[k]
  1462. v.lines = lines[k]
  1463. print("calculating - ownership")
  1464. owned_index = {k: i for i, (_, k) in enumerate(sorted(
  1465. ((owned[k][-1].sum(), k) for k in chosen), reverse=True))}
  1466. for k, v in result.items():
  1467. v.ownership_rank = owned_index[k]
  1468. v.ownership = owned[k][-1].sum()
  1469. print("calculating - couples")
  1470. embeddings = numpy.genfromtxt(fname="couples_people_data.tsv", delimiter="\t")[
  1471. [people.index(k) for k in chosen]]
  1472. embeddings /= numpy.linalg.norm(embeddings, axis=1)[:, None]
  1473. cos = embeddings.dot(embeddings.T)
  1474. cos[cos > 1] = 1 # tiny precision faults
  1475. dists = numpy.arccos(cos)
  1476. clusters = HDBSCAN(min_cluster_size=2, metric="precomputed").fit_predict(dists)
  1477. for k, v in result.items():
  1478. v.couples_cluster = clusters[chosen.index(k)]
  1479. couples_order = seriate(dists)
  1480. roll_options = []
  1481. for i in range(len(couples_order)):
  1482. loss = 0
  1483. for k, v in result.items():
  1484. loss += abs(
  1485. v.ownership_rank - (couples_order.index(chosen.index(k)) + i) % len(chosen))
  1486. roll_options.append(loss)
  1487. best_roll = numpy.argmin(roll_options)
  1488. couples_order = list(numpy.roll(couples_order, best_roll))
  1489. for k, v in result.items():
  1490. v.couples_index = couples_order.index(chosen.index(k))
  1491. print("calculating - commit series")
  1492. dists, devseries, _, orig_route = order_commits(chosen, days, people)
  1493. keys = list(devseries.keys())
  1494. route = [keys[node] for node in orig_route]
  1495. for roll in range(len(route)):
  1496. loss = 0
  1497. for k, v in result.items():
  1498. i = route.index(people.index(k))
  1499. loss += abs(v.couples_index - ((i + roll) % len(route)))
  1500. roll_options[roll] = loss
  1501. best_roll = numpy.argmin(roll_options)
  1502. route = list(numpy.roll(route, best_roll))
  1503. orig_route = list(numpy.roll(orig_route, best_roll))
  1504. clusters = hdbscan_cluster_routed_series(dists, orig_route)
  1505. for k, v in result.items():
  1506. v.commit_coocc_index = route.index(people.index(k))
  1507. v.commit_coocc_cluster = clusters[v.commit_coocc_index]
  1508. return result
  1509. def show_devs_parallel(args, name, start_date, end_date, devs):
  1510. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1511. from matplotlib.collections import LineCollection
  1512. def solve_equations(x1, y1, x2, y2):
  1513. xcube = (x1 - x2) ** 3
  1514. a = 2 * (y2 - y1) / xcube
  1515. b = 3 * (y1 - y2) * (x1 + x2) / xcube
  1516. c = 6 * (y2 - y1) * x1 * x2 / xcube
  1517. d = y1 - a * x1 ** 3 - b * x1 ** 2 - c * x1
  1518. return a, b, c, d
  1519. # biggest = {k: max(getattr(d, k) for d in devs.values())
  1520. # for k in ("commits", "lines", "ownership")}
  1521. for k, dev in devs.items():
  1522. points = numpy.array([
  1523. (1, dev.commits_rank),
  1524. (2, dev.lines_rank),
  1525. (3, dev.ownership_rank),
  1526. (4, dev.couples_index),
  1527. (5, dev.commit_coocc_index)],
  1528. dtype=float)
  1529. points[:, 1] = points[:, 1] / len(devs)
  1530. splines = []
  1531. for i in range(len(points) - 1):
  1532. a, b, c, d = solve_equations(*points[i], *points[i + 1])
  1533. x = numpy.linspace(i + 1, i + 2, 100)
  1534. smooth_points = numpy.array(
  1535. [x, a * x ** 3 + b * x ** 2 + c * x + d]).T.reshape(-1, 1, 2)
  1536. splines.append(smooth_points)
  1537. points = numpy.concatenate(splines)
  1538. segments = numpy.concatenate([points[:-1], points[1:]], axis=1)
  1539. lc = LineCollection(segments)
  1540. lc.set_array(numpy.linspace(0, 0.1, segments.shape[0]))
  1541. pyplot.gca().add_collection(lc)
  1542. pyplot.xlim(0, 6)
  1543. pyplot.ylim(-0.1, 1.1)
  1544. deploy_plot("Developers", args.output, args.background)
  1545. def _format_number(n):
  1546. if n == 0:
  1547. return "0"
  1548. power = int(numpy.log10(abs(n)))
  1549. if power >= 6:
  1550. n = n / 1000000
  1551. if n >= 10:
  1552. n = str(int(n))
  1553. else:
  1554. n = "%.1f" % n
  1555. if n.endswith("0"):
  1556. n = n[:-2]
  1557. suffix = "M"
  1558. elif power >= 3:
  1559. n = n / 1000
  1560. if n >= 10:
  1561. n = str(int(n))
  1562. else:
  1563. n = "%.1f" % n
  1564. if n.endswith("0"):
  1565. n = n[:-2]
  1566. suffix = "K"
  1567. else:
  1568. n = str(n)
  1569. suffix = ""
  1570. return n + suffix
  1571. def main():
  1572. args = parse_args()
  1573. reader = read_input(args)
  1574. header = reader.get_header()
  1575. name = reader.get_name()
  1576. burndown_warning = "Burndown stats were not collected. Re-run hercules with --burndown."
  1577. burndown_files_warning = \
  1578. "Burndown stats for files were not collected. Re-run hercules with " \
  1579. "--burndown --burndown-files."
  1580. burndown_people_warning = \
  1581. "Burndown stats for people were not collected. Re-run hercules with " \
  1582. "--burndown --burndown-people."
  1583. couples_warning = "Coupling stats were not collected. Re-run hercules with --couples."
  1584. shotness_warning = "Structural hotness stats were not collected. Re-run hercules with " \
  1585. "--shotness. Also check --languages - the output may be empty."
  1586. sentiment_warning = "Sentiment stats were not collected. Re-run hercules with --sentiment."
  1587. devs_warning = "Devs stats were not collected. Re-run hercules with --devs."
  1588. def run_times():
  1589. rt = reader.get_run_times()
  1590. pandas = import_pandas()
  1591. series = pandas.to_timedelta(pandas.Series(rt).sort_values(ascending=False), unit="s")
  1592. df = pandas.concat([series, series / series.sum()], axis=1)
  1593. df.columns = ["time", "ratio"]
  1594. print(df)
  1595. def project_burndown():
  1596. try:
  1597. full_header = header + reader.get_burndown_parameters()
  1598. except KeyError:
  1599. print("project: " + burndown_warning)
  1600. return
  1601. plot_burndown(args, "project",
  1602. *load_burndown(full_header, *reader.get_project_burndown(),
  1603. resample=args.resample, interpolation_progress=True))
  1604. def files_burndown():
  1605. try:
  1606. full_header = header + reader.get_burndown_parameters()
  1607. except KeyError:
  1608. print(burndown_warning)
  1609. return
  1610. try:
  1611. plot_many_burndown(args, "file", full_header, reader.get_files_burndown())
  1612. except KeyError:
  1613. print("files: " + burndown_files_warning)
  1614. def people_burndown():
  1615. try:
  1616. full_header = header + reader.get_burndown_parameters()
  1617. except KeyError:
  1618. print(burndown_warning)
  1619. return
  1620. try:
  1621. plot_many_burndown(args, "person", full_header, reader.get_people_burndown())
  1622. except KeyError:
  1623. print("people: " + burndown_people_warning)
  1624. def overwrites_matrix():
  1625. try:
  1626. plot_overwrites_matrix(args, name, *load_overwrites_matrix(
  1627. *reader.get_people_interaction(), max_people=args.max_people))
  1628. people, matrix = load_overwrites_matrix(
  1629. *reader.get_people_interaction(), max_people=1000000, normalize=False)
  1630. from scipy.sparse import csr_matrix
  1631. matrix = matrix[:, 1:]
  1632. matrix = numpy.triu(matrix) + numpy.tril(matrix).T
  1633. matrix = matrix + matrix.T
  1634. matrix = csr_matrix(matrix)
  1635. try:
  1636. write_embeddings("overwrites", args.output, not args.disable_projector,
  1637. *train_embeddings(people, matrix, tmpdir=args.tmpdir))
  1638. except AttributeError as e:
  1639. print("Training the embeddings is not possible: %s: %s", type(e).__name__, e)
  1640. except KeyError:
  1641. print("overwrites_matrix: " + burndown_people_warning)
  1642. def ownership_burndown():
  1643. try:
  1644. full_header = header + reader.get_burndown_parameters()
  1645. except KeyError:
  1646. print(burndown_warning)
  1647. return
  1648. try:
  1649. plot_ownership(args, name, *load_ownership(
  1650. full_header, *reader.get_ownership_burndown(), max_people=args.max_people,
  1651. order_by_time=args.order_ownership_by_time))
  1652. except KeyError:
  1653. print("ownership: " + burndown_people_warning)
  1654. def couples_files():
  1655. try:
  1656. write_embeddings("files", args.output, not args.disable_projector,
  1657. *train_embeddings(*reader.get_files_coocc(),
  1658. tmpdir=args.tmpdir))
  1659. except KeyError:
  1660. print(couples_warning)
  1661. def couples_people():
  1662. try:
  1663. write_embeddings("people", args.output, not args.disable_projector,
  1664. *train_embeddings(*reader.get_people_coocc(),
  1665. tmpdir=args.tmpdir))
  1666. except KeyError:
  1667. print(couples_warning)
  1668. def couples_shotness():
  1669. try:
  1670. write_embeddings("shotness", args.output, not args.disable_projector,
  1671. *train_embeddings(*reader.get_shotness_coocc(),
  1672. tmpdir=args.tmpdir))
  1673. except KeyError:
  1674. print(shotness_warning)
  1675. def shotness():
  1676. try:
  1677. data = reader.get_shotness()
  1678. except KeyError:
  1679. print(shotness_warning)
  1680. return
  1681. show_shotness_stats(data)
  1682. def sentiment():
  1683. try:
  1684. data = reader.get_sentiment()
  1685. except KeyError:
  1686. print(sentiment_warning)
  1687. return
  1688. show_sentiment_stats(args, reader.get_name(), args.resample, reader.get_header()[0], data)
  1689. def devs():
  1690. try:
  1691. data = reader.get_devs()
  1692. except KeyError:
  1693. print(devs_warning)
  1694. return
  1695. show_devs(args, reader.get_name(), *reader.get_header(), *data,
  1696. max_people=args.max_people)
  1697. def devs_efforts():
  1698. try:
  1699. data = reader.get_devs()
  1700. except KeyError:
  1701. print(devs_warning)
  1702. return
  1703. show_devs_efforts(args, reader.get_name(), *reader.get_header(), *data,
  1704. max_people=args.max_people)
  1705. def old_vs_new():
  1706. try:
  1707. data = reader.get_devs()
  1708. except KeyError:
  1709. print(devs_warning)
  1710. return
  1711. show_old_vs_new(args, reader.get_name(), *reader.get_header(), *data)
  1712. def languages():
  1713. try:
  1714. data = reader.get_devs()
  1715. except KeyError:
  1716. print(devs_warning)
  1717. return
  1718. show_languages(args, reader.get_name(), *reader.get_header(), *data)
  1719. def devs_parallel():
  1720. try:
  1721. ownership = reader.get_ownership_burndown()
  1722. except KeyError:
  1723. print(burndown_people_warning)
  1724. return
  1725. try:
  1726. couples = reader.get_people_coocc()
  1727. except KeyError:
  1728. print(couples_warning)
  1729. return
  1730. try:
  1731. devs = reader.get_devs()
  1732. except KeyError:
  1733. print(devs_warning)
  1734. return
  1735. show_devs_parallel(args, reader.get_name(), *reader.get_header(),
  1736. load_devs_parallel(ownership, couples, devs, args.max_people))
  1737. modes = {
  1738. "run-times": run_times,
  1739. "burndown-project": project_burndown,
  1740. "burndown-file": files_burndown,
  1741. "burndown-person": people_burndown,
  1742. "overwrites-matrix": overwrites_matrix,
  1743. "ownership": ownership_burndown,
  1744. "couples-files": couples_files,
  1745. "couples-people": couples_people,
  1746. "couples-shotness": couples_shotness,
  1747. "shotness": shotness,
  1748. "sentiment": sentiment,
  1749. "devs": devs,
  1750. "devs-efforts": devs_efforts,
  1751. "old-vs-new": old_vs_new,
  1752. "languages": languages,
  1753. "devs-parallel": devs_parallel,
  1754. }
  1755. if "all" in args.modes:
  1756. all_mode = True
  1757. args.modes = [
  1758. "burndown-project",
  1759. "overwrites-matrix",
  1760. "ownership",
  1761. "couples-files",
  1762. "couples-people",
  1763. "couples-shotness",
  1764. "shotness",
  1765. "devs",
  1766. "devs-efforts",
  1767. ]
  1768. else:
  1769. all_mode = False
  1770. for mode in args.modes:
  1771. if mode not in modes:
  1772. print("Unknown mode: %s" % mode)
  1773. continue
  1774. print("Running: %s" % mode)
  1775. # `args.mode` is required for path determination in the mode functions
  1776. args.mode = ("all" if all_mode else mode)
  1777. try:
  1778. modes[mode]()
  1779. except ImportError as ie:
  1780. print("A module required by the %s mode was not found: %s" % (mode, ie))
  1781. if not all_mode:
  1782. raise
  1783. if web_server.running:
  1784. secs = int(os.getenv("COUPLES_SERVER_TIME", "60"))
  1785. print("Sleeping for %d seconds, safe to Ctrl-C" % secs)
  1786. sys.stdout.flush()
  1787. try:
  1788. time.sleep(secs)
  1789. except KeyboardInterrupt:
  1790. pass
  1791. web_server.stop()
  1792. if __name__ == "__main__":
  1793. sys.exit(main())