labours.py 76 KB

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