labours.py 74 KB

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