labours.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  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. print("Writing plot to %s" % output)
  713. pyplot.savefig(output, transparent=True)
  714. pyplot.clf()
  715. def default_json(x):
  716. if hasattr(x, "tolist"):
  717. return x.tolist()
  718. if hasattr(x, "isoformat"):
  719. return x.isoformat()
  720. return x
  721. def parse_date(text, default):
  722. if not text:
  723. return default
  724. from dateutil.parser import parse
  725. return parse(text)
  726. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  727. sampling, resample):
  728. if args.output and args.output.endswith(".json"):
  729. data = locals().copy()
  730. del data["args"]
  731. data["type"] = "burndown"
  732. if args.mode == "project" and target == "project":
  733. output = args.output
  734. else:
  735. if target == "project":
  736. name = "project"
  737. output = get_plot_path(args.output, name)
  738. with open(output, "w") as fout:
  739. json.dump(data, fout, sort_keys=True, default=default_json)
  740. return
  741. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  742. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  743. if args.relative:
  744. for i in range(matrix.shape[1]):
  745. matrix[:, i] /= matrix[:, i].sum()
  746. pyplot.ylim(0, 1)
  747. legend_loc = 3
  748. else:
  749. legend_loc = 2
  750. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size)
  751. pyplot.ylabel("Lines of code")
  752. pyplot.xlabel("Time")
  753. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  754. args.font_size, args.size)
  755. pyplot.xlim(parse_date(args.start_date, date_range_sampling[0]),
  756. parse_date(args.end_date, date_range_sampling[-1]))
  757. locator = pyplot.gca().xaxis.get_major_locator()
  758. # set the optimal xticks locator
  759. if "M" not in resample:
  760. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  761. locs = pyplot.gca().get_xticks().tolist()
  762. if len(locs) >= 16:
  763. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  764. locs = pyplot.gca().get_xticks().tolist()
  765. if len(locs) >= 16:
  766. pyplot.gca().xaxis.set_major_locator(locator)
  767. if locs[0] < pyplot.xlim()[0]:
  768. del locs[0]
  769. endindex = -1
  770. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  771. locs.append(pyplot.xlim()[1])
  772. endindex = len(locs) - 1
  773. startindex = -1
  774. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  775. locs.append(pyplot.xlim()[0])
  776. startindex = len(locs) - 1
  777. pyplot.gca().set_xticks(locs)
  778. # hacking time!
  779. labels = pyplot.gca().get_xticklabels()
  780. if startindex >= 0:
  781. labels[startindex].set_text(date_range_sampling[0].date())
  782. labels[startindex].set_text = lambda _: None
  783. labels[startindex].set_rotation(30)
  784. labels[startindex].set_ha("right")
  785. if endindex >= 0:
  786. labels[endindex].set_text(date_range_sampling[-1].date())
  787. labels[endindex].set_text = lambda _: None
  788. labels[endindex].set_rotation(30)
  789. labels[endindex].set_ha("right")
  790. title = "%s %d x %d (granularity %d, sampling %d)" % \
  791. ((name,) + matrix.shape + (granularity, sampling))
  792. output = args.output
  793. if output:
  794. if args.mode == "project" and target == "project":
  795. output = args.output
  796. else:
  797. if target == "project":
  798. name = "project"
  799. output = get_plot_path(args.output, name)
  800. deploy_plot(title, output, args.background)
  801. def plot_many_burndown(args, target, header, parts):
  802. if not args.output:
  803. print("Warning: output not set, showing %d plots." % len(parts))
  804. itercnt = progress.bar(parts, expected_size=len(parts)) \
  805. if progress is not None else parts
  806. stdout = io.StringIO()
  807. for name, matrix in itercnt:
  808. backup = sys.stdout
  809. sys.stdout = stdout
  810. plot_burndown(args, target, *load_burndown(header, name, matrix, args.resample))
  811. sys.stdout = backup
  812. sys.stdout.write(stdout.getvalue())
  813. def plot_overwrites_matrix(args, repo, people, matrix):
  814. if args.output and args.output.endswith(".json"):
  815. data = locals().copy()
  816. del data["args"]
  817. data["type"] = "overwrites_matrix"
  818. if args.mode == "all":
  819. output = get_plot_path(args.output, "matrix")
  820. else:
  821. output = args.output
  822. with open(output, "w") as fout:
  823. json.dump(data, fout, sort_keys=True, default=default_json)
  824. return
  825. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  826. s = 4 + matrix.shape[1] * 0.3
  827. fig = pyplot.figure(figsize=(s, s))
  828. ax = fig.add_subplot(111)
  829. ax.xaxis.set_label_position("top")
  830. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  831. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  832. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  833. ax.set_yticklabels(people, va="center")
  834. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  835. ax.set_xticklabels(["Unidentified"] + people, rotation=45, ha="left",
  836. va="bottom", rotation_mode="anchor")
  837. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  838. ax.grid(False)
  839. ax.grid(which="minor")
  840. apply_plot_style(fig, ax, None, args.background, args.font_size, args.size)
  841. if not args.output:
  842. pos1 = ax.get_position()
  843. pos2 = (pos1.x0 + 0.15, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  844. ax.set_position(pos2)
  845. if args.mode == "all" and args.output:
  846. output = get_plot_path(args.output, "matrix")
  847. else:
  848. output = args.output
  849. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  850. if args.output:
  851. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  852. title = ""
  853. deploy_plot(title, output, args.background)
  854. def plot_ownership(args, repo, names, people, date_range, last):
  855. if args.output and args.output.endswith(".json"):
  856. data = locals().copy()
  857. del data["args"]
  858. data["type"] = "ownership"
  859. if args.mode == "all" and args.output:
  860. output = get_plot_path(args.output, "people")
  861. else:
  862. output = args.output
  863. with open(output, "w") as fout:
  864. json.dump(data, fout, sort_keys=True, default=default_json)
  865. return
  866. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  867. polys = pyplot.stackplot(date_range, people, labels=names)
  868. if names[-1] == "others":
  869. polys[-1].set_hatch("/")
  870. pyplot.xlim(parse_date(args.start_date, date_range[0]), parse_date(args.end_date, last))
  871. if args.relative:
  872. for i in range(people.shape[1]):
  873. people[:, i] /= people[:, i].sum()
  874. pyplot.ylim(0, 1)
  875. legend_loc = 3
  876. else:
  877. legend_loc = 2
  878. ncol = 1 if len(names) < 15 else 2
  879. legend = pyplot.legend(loc=legend_loc, fontsize=args.font_size, ncol=ncol)
  880. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  881. args.font_size, args.size)
  882. if args.mode == "all" and args.output:
  883. output = get_plot_path(args.output, "people")
  884. else:
  885. output = args.output
  886. deploy_plot("%s code ownership through time" % repo, output, args.background)
  887. IDEAL_SHARD_SIZE = 4096
  888. def train_embeddings(index, matrix, tmpdir, shard_size=IDEAL_SHARD_SIZE):
  889. import tensorflow as tf
  890. try:
  891. from . import swivel
  892. except (SystemError, ImportError):
  893. import swivel
  894. assert matrix.shape[0] == matrix.shape[1]
  895. assert len(index) <= matrix.shape[0]
  896. outlier_threshold = numpy.percentile(matrix.data, 99)
  897. matrix.data[matrix.data > outlier_threshold] = outlier_threshold
  898. nshards = len(index) // shard_size
  899. if nshards * shard_size < len(index):
  900. nshards += 1
  901. shard_size = len(index) // nshards
  902. nshards = len(index) // shard_size
  903. remainder = len(index) - nshards * shard_size
  904. if remainder > 0:
  905. lengths = matrix.indptr[1:] - matrix.indptr[:-1]
  906. filtered = sorted(numpy.argsort(lengths)[remainder:])
  907. else:
  908. filtered = list(range(len(index)))
  909. if len(filtered) < matrix.shape[0]:
  910. print("Truncating the sparse matrix...")
  911. matrix = matrix[filtered, :][:, filtered]
  912. meta_index = []
  913. for i, j in enumerate(filtered):
  914. meta_index.append((index[j], matrix[i, i]))
  915. index = [mi[0] for mi in meta_index]
  916. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  917. print("Writing Swivel metadata...")
  918. vocabulary = "\n".join(index)
  919. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  920. out.write(vocabulary)
  921. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  922. out.write(vocabulary)
  923. del vocabulary
  924. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  925. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  926. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  927. out.write(bool_sums_str)
  928. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  929. out.write(bool_sums_str)
  930. del bool_sums_str
  931. reorder = numpy.argsort(-bool_sums)
  932. print("Writing Swivel shards...")
  933. for row in range(nshards):
  934. for col in range(nshards):
  935. def _int64s(xs):
  936. return tf.train.Feature(
  937. int64_list=tf.train.Int64List(value=list(xs)))
  938. def _floats(xs):
  939. return tf.train.Feature(
  940. float_list=tf.train.FloatList(value=list(xs)))
  941. indices_row = reorder[row::nshards]
  942. indices_col = reorder[col::nshards]
  943. shard = matrix[indices_row][:, indices_col].tocoo()
  944. example = tf.train.Example(features=tf.train.Features(feature={
  945. "global_row": _int64s(indices_row),
  946. "global_col": _int64s(indices_col),
  947. "sparse_local_row": _int64s(shard.row),
  948. "sparse_local_col": _int64s(shard.col),
  949. "sparse_value": _floats(shard.data)}))
  950. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  951. out.write(example.SerializeToString())
  952. print("Training Swivel model...")
  953. swivel.FLAGS.submatrix_rows = shard_size
  954. swivel.FLAGS.submatrix_cols = shard_size
  955. if len(meta_index) <= IDEAL_SHARD_SIZE / 16:
  956. embedding_size = 50
  957. num_epochs = 100000
  958. elif len(meta_index) <= IDEAL_SHARD_SIZE:
  959. embedding_size = 50
  960. num_epochs = 50000
  961. elif len(meta_index) <= IDEAL_SHARD_SIZE * 2:
  962. embedding_size = 60
  963. num_epochs = 10000
  964. elif len(meta_index) <= IDEAL_SHARD_SIZE * 4:
  965. embedding_size = 70
  966. num_epochs = 8000
  967. elif len(meta_index) <= IDEAL_SHARD_SIZE * 10:
  968. embedding_size = 80
  969. num_epochs = 5000
  970. elif len(meta_index) <= IDEAL_SHARD_SIZE * 25:
  971. embedding_size = 100
  972. num_epochs = 1000
  973. elif len(meta_index) <= IDEAL_SHARD_SIZE * 100:
  974. embedding_size = 200
  975. num_epochs = 600
  976. else:
  977. embedding_size = 300
  978. num_epochs = 300
  979. if os.getenv("CI"):
  980. # Travis, AppVeyor etc. during the integration tests
  981. num_epochs /= 10
  982. swivel.FLAGS.embedding_size = embedding_size
  983. swivel.FLAGS.input_base_path = tmproot
  984. swivel.FLAGS.output_base_path = tmproot
  985. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  986. swivel.FLAGS.num_epochs = num_epochs
  987. # Tensorflow 1.5 parses sys.argv unconditionally *applause*
  988. argv_backup = sys.argv[1:]
  989. del sys.argv[1:]
  990. swivel.main(None)
  991. sys.argv.extend(argv_backup)
  992. print("Reading Swivel embeddings...")
  993. embeddings = []
  994. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  995. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  996. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  997. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  998. assert prow[0] == pcol[0]
  999. erow, ecol = \
  1000. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  1001. for p in (prow, pcol))
  1002. embeddings.append((erow + ecol) / 2)
  1003. return meta_index, embeddings
  1004. class CORSWebServer(object):
  1005. def __init__(self):
  1006. self.thread = threading.Thread(target=self.serve)
  1007. self.server = None
  1008. def serve(self):
  1009. outer = self
  1010. try:
  1011. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  1012. except ImportError: # Python 2
  1013. from BaseHTTPServer import HTTPServer, test
  1014. from SimpleHTTPServer import SimpleHTTPRequestHandler
  1015. class ClojureServer(HTTPServer):
  1016. def __init__(self, *args, **kwargs):
  1017. HTTPServer.__init__(self, *args, **kwargs)
  1018. outer.server = self
  1019. class CORSRequestHandler(SimpleHTTPRequestHandler):
  1020. def end_headers(self):
  1021. self.send_header("Access-Control-Allow-Origin", "*")
  1022. SimpleHTTPRequestHandler.end_headers(self)
  1023. test(CORSRequestHandler, ClojureServer)
  1024. def start(self):
  1025. self.thread.start()
  1026. def stop(self):
  1027. if self.running:
  1028. self.server.shutdown()
  1029. self.thread.join()
  1030. @property
  1031. def running(self):
  1032. return self.server is not None
  1033. web_server = CORSWebServer()
  1034. def write_embeddings(name, output, run_server, index, embeddings):
  1035. print("Writing Tensorflow Projector files...")
  1036. if not output:
  1037. output = "couples"
  1038. if output.endswith(".json"):
  1039. output = os.path.join(output[:-5], "couples")
  1040. run_server = False
  1041. metaf = "%s_%s_meta.tsv" % (output, name)
  1042. with open(metaf, "w") as fout:
  1043. fout.write("name\tcommits\n")
  1044. for pair in index:
  1045. fout.write("%s\t%s\n" % pair)
  1046. print("Wrote", metaf)
  1047. dataf = "%s_%s_data.tsv" % (output, name)
  1048. with open(dataf, "w") as fout:
  1049. for vec in embeddings:
  1050. fout.write("\t".join(str(v) for v in vec))
  1051. fout.write("\n")
  1052. print("Wrote", dataf)
  1053. jsonf = "%s_%s.json" % (output, name)
  1054. with open(jsonf, "w") as fout:
  1055. fout.write("""{
  1056. "embeddings": [
  1057. {
  1058. "tensorName": "%s %s coupling",
  1059. "tensorShape": [%s, %s],
  1060. "tensorPath": "http://0.0.0.0:8000/%s",
  1061. "metadataPath": "http://0.0.0.0:8000/%s"
  1062. }
  1063. ]
  1064. }
  1065. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  1066. print("Wrote %s" % jsonf)
  1067. if run_server and not web_server.running:
  1068. web_server.start()
  1069. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  1070. print(url)
  1071. if run_server:
  1072. if shutil.which("xdg-open") is not None:
  1073. os.system("xdg-open " + url)
  1074. else:
  1075. browser = os.getenv("BROWSER", "")
  1076. if browser:
  1077. os.system(browser + " " + url)
  1078. else:
  1079. print("\t" + url)
  1080. def show_shotness_stats(data):
  1081. top = sorted(((r.counters[i], i) for i, r in enumerate(data)), reverse=True)
  1082. for count, i in top:
  1083. r = data[i]
  1084. print("%8d %s:%s [%s]" % (count, r.file, r.name, r.internal_role))
  1085. def show_sentiment_stats(args, name, resample, start_date, data):
  1086. from scipy.signal import convolve, slepian
  1087. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1088. start_date = datetime.fromtimestamp(start_date)
  1089. data = sorted(data.items())
  1090. mood = numpy.zeros(data[-1][0] + 1, dtype=numpy.float32)
  1091. timeline = numpy.array([start_date + timedelta(days=i) for i in range(mood.shape[0])])
  1092. for d, val in data:
  1093. mood[d] = (0.5 - val.Value) * 2
  1094. resolution = 32
  1095. window = slepian(len(timeline) // resolution, 0.5)
  1096. window /= window.sum()
  1097. mood_smooth = convolve(mood, window, "same")
  1098. pos = mood_smooth.copy()
  1099. pos[pos < 0] = 0
  1100. neg = mood_smooth.copy()
  1101. neg[neg >= 0] = 0
  1102. resolution = 4
  1103. window = numpy.ones(len(timeline) // resolution)
  1104. window /= window.sum()
  1105. avg = convolve(mood, window, "same")
  1106. pyplot.fill_between(timeline, pos, color="#8DB843", label="Positive")
  1107. pyplot.fill_between(timeline, neg, color="#E14C35", label="Negative")
  1108. pyplot.plot(timeline, avg, color="grey", label="Average", linewidth=5)
  1109. legend = pyplot.legend(loc=1, fontsize=args.font_size)
  1110. pyplot.ylabel("Comment sentiment")
  1111. pyplot.xlabel("Time")
  1112. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  1113. args.font_size, args.size)
  1114. pyplot.xlim(parse_date(args.start_date, timeline[0]), parse_date(args.end_date, timeline[-1]))
  1115. locator = pyplot.gca().xaxis.get_major_locator()
  1116. # set the optimal xticks locator
  1117. if "M" not in resample:
  1118. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1119. locs = pyplot.gca().get_xticks().tolist()
  1120. if len(locs) >= 16:
  1121. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  1122. locs = pyplot.gca().get_xticks().tolist()
  1123. if len(locs) >= 16:
  1124. pyplot.gca().xaxis.set_major_locator(locator)
  1125. if locs[0] < pyplot.xlim()[0]:
  1126. del locs[0]
  1127. endindex = -1
  1128. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  1129. locs.append(pyplot.xlim()[1])
  1130. endindex = len(locs) - 1
  1131. startindex = -1
  1132. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  1133. locs.append(pyplot.xlim()[0])
  1134. startindex = len(locs) - 1
  1135. pyplot.gca().set_xticks(locs)
  1136. # hacking time!
  1137. labels = pyplot.gca().get_xticklabels()
  1138. if startindex >= 0:
  1139. labels[startindex].set_text(timeline[0].date())
  1140. labels[startindex].set_text = lambda _: None
  1141. labels[startindex].set_rotation(30)
  1142. labels[startindex].set_ha("right")
  1143. if endindex >= 0:
  1144. labels[endindex].set_text(timeline[-1].date())
  1145. labels[endindex].set_text = lambda _: None
  1146. labels[endindex].set_rotation(30)
  1147. labels[endindex].set_ha("right")
  1148. overall_pos = sum(2 * (0.5 - d[1].Value) for d in data if d[1].Value < 0.5)
  1149. overall_neg = sum(2 * (d[1].Value - 0.5) for d in data if d[1].Value > 0.5)
  1150. title = "%s sentiment +%.1f -%.1f δ=%.1f" % (
  1151. name, overall_pos, overall_neg, overall_pos - overall_neg)
  1152. if args.mode == "all" and args.output:
  1153. output = get_plot_path(args.output, "sentiment")
  1154. else:
  1155. output = args.output
  1156. deploy_plot(title, output, args.background)
  1157. def show_devs(args, name, start_date, end_date, people, days, max_people=50):
  1158. from scipy.signal import convolve, slepian
  1159. if len(people) > max_people:
  1160. print("Picking top %s developers by commit count" % max_people)
  1161. # pick top N developers by commit count
  1162. commits = defaultdict(int)
  1163. for devs in days.values():
  1164. for dev, stats in devs.items():
  1165. commits[dev] += stats.Commits
  1166. commits = sorted(((v, k) for k, v in commits.items()), reverse=True)
  1167. chosen_people = {people[k] for _, k in commits[:max_people]}
  1168. else:
  1169. chosen_people = set(people)
  1170. dists, devseries, devstats, route = order_commits(chosen_people, days, people)
  1171. route_map = {v: i for i, v in enumerate(route)}
  1172. # determine clusters
  1173. clusters = hdbscan_cluster_routed_series(dists, route)
  1174. keys = list(devseries.keys())
  1175. route = [keys[node] for node in route]
  1176. print("Plotting")
  1177. # smooth time series
  1178. start_date = datetime.fromtimestamp(start_date)
  1179. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1180. end_date = datetime.fromtimestamp(end_date)
  1181. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1182. size = (end_date - start_date).days + 1
  1183. plot_x = [start_date + timedelta(days=i) for i in range(size)]
  1184. resolution = 64
  1185. window = slepian(size // resolution, 0.5)
  1186. final = numpy.zeros((len(devseries), size), dtype=numpy.float32)
  1187. for i, s in enumerate(devseries.values()):
  1188. arr = numpy.array(s).transpose()
  1189. full_history = numpy.zeros(size, dtype=numpy.float32)
  1190. mask = arr[0] < size
  1191. full_history[arr[0][mask]] = arr[1][mask]
  1192. final[route_map[i]] = convolve(full_history, window, "same")
  1193. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1194. pyplot.rcParams["figure.figsize"] = (32, 16)
  1195. pyplot.rcParams["font.size"] = args.font_size
  1196. prop_cycle = pyplot.rcParams["axes.prop_cycle"]
  1197. colors = prop_cycle.by_key()["color"]
  1198. fig, axes = pyplot.subplots(final.shape[0], 1)
  1199. backgrounds = ("#C4FFDB", "#FFD0CD") if args.background == "white" else ("#05401C", "#40110E")
  1200. max_cluster = numpy.max(clusters)
  1201. for ax, series, cluster, dev_i in zip(axes, final, clusters, route):
  1202. if cluster >= 0:
  1203. color = colors[cluster % len(colors)]
  1204. i = 1
  1205. while color == "#777777":
  1206. color = colors[(max_cluster + i) % len(colors)]
  1207. i += 1
  1208. else:
  1209. # outlier
  1210. color = "#777777"
  1211. ax.fill_between(plot_x, series, color=color)
  1212. ax.set_axis_off()
  1213. author = people[dev_i]
  1214. ax.text(0.03, 0.5, author[:36] + (author[36:] and "..."),
  1215. horizontalalignment="right", verticalalignment="center",
  1216. transform=ax.transAxes, fontsize=args.font_size,
  1217. color="black" if args.background == "white" else "white")
  1218. ds = devstats[dev_i]
  1219. stats = "%5d %8s %8s" % (ds[0], _format_number(ds[1] - ds[2]), _format_number(ds[3]))
  1220. ax.text(0.97, 0.5, stats,
  1221. horizontalalignment="left", verticalalignment="center",
  1222. transform=ax.transAxes, fontsize=args.font_size, family="monospace",
  1223. backgroundcolor=backgrounds[ds[1] <= ds[2]],
  1224. color="black" if args.background == "white" else "white")
  1225. axes[0].text(0.97, 1.75, " cmts delta changed",
  1226. horizontalalignment="left", verticalalignment="center",
  1227. transform=axes[0].transAxes, fontsize=args.font_size, family="monospace",
  1228. color="black" if args.background == "white" else "white")
  1229. axes[-1].set_axis_on()
  1230. target_num_labels = 12
  1231. num_months = (end_date.year - start_date.year) * 12 + end_date.month - start_date.month
  1232. interval = int(numpy.ceil(num_months / target_num_labels))
  1233. if interval >= 8:
  1234. interval = int(numpy.ceil(num_months / (12 * target_num_labels)))
  1235. axes[-1].xaxis.set_major_locator(matplotlib.dates.YearLocator(base=max(1, interval // 12)))
  1236. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
  1237. else:
  1238. axes[-1].xaxis.set_major_locator(matplotlib.dates.MonthLocator(interval=interval))
  1239. axes[-1].xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
  1240. for tick in axes[-1].xaxis.get_major_ticks():
  1241. tick.label.set_fontsize(args.font_size)
  1242. axes[-1].spines["left"].set_visible(False)
  1243. axes[-1].spines["right"].set_visible(False)
  1244. axes[-1].spines["top"].set_visible(False)
  1245. axes[-1].get_yaxis().set_visible(False)
  1246. axes[-1].set_facecolor((1.0,) * 3 + (0.0,))
  1247. title = ("%s commits" % name) if not args.output else ""
  1248. if args.mode == "all" and args.output:
  1249. output = get_plot_path(args.output, "time_series")
  1250. else:
  1251. output = args.output
  1252. deploy_plot(title, output, args.background)
  1253. def order_commits(chosen_people, days, people):
  1254. from seriate import seriate
  1255. try:
  1256. from fastdtw import fastdtw
  1257. except ImportError as e:
  1258. print("Cannot import fastdtw: %s\nInstall it from https://github.com/slaypni/fastdtw" % e)
  1259. sys.exit(1)
  1260. # FIXME(vmarkovtsev): remove once https://github.com/slaypni/fastdtw/pull/28 is merged&released
  1261. try:
  1262. sys.modules["fastdtw.fastdtw"].__norm = lambda p: lambda a, b: numpy.linalg.norm(
  1263. numpy.atleast_1d(a) - numpy.atleast_1d(b), p)
  1264. except KeyError:
  1265. # the native extension does not have this bug
  1266. pass
  1267. devseries = defaultdict(list)
  1268. devstats = defaultdict(lambda: DevDay(0, 0, 0, 0, {}))
  1269. for day, devs in sorted(days.items()):
  1270. for dev, stats in devs.items():
  1271. if people[dev] in chosen_people:
  1272. devseries[dev].append((day, stats.Commits))
  1273. devstats[dev] = devstats[dev].add(stats)
  1274. print("Calculating the distance matrix")
  1275. # max-normalize the time series using a sliding window
  1276. series = list(devseries.values())
  1277. for i, s in enumerate(series):
  1278. arr = numpy.array(s).transpose().astype(numpy.float32)
  1279. arr[1] /= arr[1].sum()
  1280. series[i] = arr.transpose()
  1281. # calculate the distance matrix using dynamic time warping
  1282. dists = numpy.full((len(series),) * 2, -100500, dtype=numpy.float32)
  1283. for x, serx in enumerate(series):
  1284. dists[x, x] = 0
  1285. for y, sery in enumerate(series[x + 1:], start=x + 1):
  1286. min_day = int(min(serx[0][0], sery[0][0]))
  1287. max_day = int(max(serx[-1][0], sery[-1][0]))
  1288. arrx = numpy.zeros(max_day - min_day + 1, dtype=numpy.float32)
  1289. arry = numpy.zeros_like(arrx)
  1290. arrx[serx[:, 0].astype(int) - min_day] = serx[:, 1]
  1291. arry[sery[:, 0].astype(int) - min_day] = sery[:, 1]
  1292. # L1 norm
  1293. dist, _ = fastdtw(arrx, arry, radius=5, dist=1)
  1294. dists[x, y] = dists[y, x] = dist
  1295. print("Ordering the series")
  1296. route = seriate(dists)
  1297. return dists, devseries, devstats, route
  1298. def hdbscan_cluster_routed_series(dists, route):
  1299. try:
  1300. from hdbscan import HDBSCAN
  1301. except ImportError as e:
  1302. print("Cannot import hdbscan: %s" % e)
  1303. sys.exit(1)
  1304. opt_dist_chain = numpy.cumsum(numpy.array(
  1305. [0] + [dists[route[i], route[i + 1]] for i in range(len(route) - 1)]))
  1306. clusters = HDBSCAN(min_cluster_size=2).fit_predict(opt_dist_chain[:, numpy.newaxis])
  1307. return clusters
  1308. def show_devs_efforts(args, name, start_date, end_date, people, days, max_people):
  1309. from scipy.signal import convolve, slepian
  1310. start_date = datetime.fromtimestamp(start_date)
  1311. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1312. end_date = datetime.fromtimestamp(end_date)
  1313. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1314. efforts_by_dev = defaultdict(int)
  1315. for day, devs in days.items():
  1316. for dev, stats in devs.items():
  1317. efforts_by_dev[dev] += stats.Added + stats.Removed + stats.Changed
  1318. if len(efforts_by_dev) > max_people:
  1319. chosen = {v for k, v in sorted(
  1320. ((v, k) for k, v in efforts_by_dev.items()), reverse=True)[:max_people]}
  1321. print("Warning: truncated people to the most active %d" % max_people)
  1322. else:
  1323. chosen = set(efforts_by_dev)
  1324. chosen_efforts = sorted(((efforts_by_dev[k], k) for k in chosen), reverse=True)
  1325. chosen_order = {k: i for i, (_, k) in enumerate(chosen_efforts)}
  1326. efforts = numpy.zeros((len(chosen) + 1, (end_date - start_date).days + 1), dtype=numpy.float32)
  1327. for day, devs in days.items():
  1328. if day < efforts.shape[1]:
  1329. for dev, stats in devs.items():
  1330. dev = chosen_order.get(dev, len(chosen_order))
  1331. efforts[dev][day] += stats.Added + stats.Removed + stats.Changed
  1332. efforts_cum = numpy.cumsum(efforts, axis=1)
  1333. window = slepian(10, 0.5)
  1334. window /= window.sum()
  1335. for e in (efforts, efforts_cum):
  1336. for i in range(e.shape[0]):
  1337. ending = e[i][-len(window) * 2:].copy()
  1338. e[i] = convolve(e[i], window, "same")
  1339. e[i][-len(ending):] = ending
  1340. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1341. plot_x = [start_date + timedelta(days=i) for i in range(efforts.shape[1])]
  1342. people = [people[k] for _, k in chosen_efforts] + ["others"]
  1343. for i, name in enumerate(people):
  1344. if len(name) > 40:
  1345. people[i] = name[:37] + "..."
  1346. polys = pyplot.stackplot(plot_x, efforts_cum, labels=people)
  1347. if len(polys) == max_people + 1:
  1348. polys[-1].set_hatch("/")
  1349. polys = pyplot.stackplot(plot_x, -efforts * efforts_cum.max() / efforts.max())
  1350. if len(polys) == max_people + 1:
  1351. polys[-1].set_hatch("/")
  1352. yticks = []
  1353. for tick in pyplot.gca().yaxis.iter_ticks():
  1354. if tick[1] >= 0:
  1355. yticks.append(tick[1])
  1356. pyplot.gca().yaxis.set_ticks(yticks)
  1357. legend = pyplot.legend(loc=2, ncol=2, fontsize=args.font_size)
  1358. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.background,
  1359. args.font_size, args.size or "16,10")
  1360. if args.mode == "all" and args.output:
  1361. output = get_plot_path(args.output, "efforts")
  1362. else:
  1363. output = args.output
  1364. deploy_plot("Efforts through time (changed lines of code)", output, args.background)
  1365. def show_old_vs_new(args, name, start_date, end_date, people, days):
  1366. from scipy.signal import convolve, slepian
  1367. start_date = datetime.fromtimestamp(start_date)
  1368. start_date = datetime(start_date.year, start_date.month, start_date.day)
  1369. end_date = datetime.fromtimestamp(end_date)
  1370. end_date = datetime(end_date.year, end_date.month, end_date.day)
  1371. new_lines = numpy.zeros((end_date - start_date).days + 2)
  1372. old_lines = numpy.zeros_like(new_lines)
  1373. for day, devs in days.items():
  1374. for stats in devs.values():
  1375. new_lines[day] += stats.Added
  1376. old_lines[day] += stats.Removed + stats.Changed
  1377. resolution = 32
  1378. window = slepian(max(len(new_lines) // resolution, 1), 0.5)
  1379. new_lines = convolve(new_lines, window, "same")
  1380. old_lines = convolve(old_lines, window, "same")
  1381. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1382. plot_x = [start_date + timedelta(days=i) for i in range(len(new_lines))]
  1383. pyplot.fill_between(plot_x, new_lines, color="#8DB843", label="Changed new lines")
  1384. pyplot.fill_between(plot_x, old_lines, color="#E14C35", label="Changed existing lines")
  1385. pyplot.legend(loc=2, fontsize=args.font_size)
  1386. for tick in chain(pyplot.gca().xaxis.get_major_ticks(), pyplot.gca().yaxis.get_major_ticks()):
  1387. tick.label.set_fontsize(args.font_size)
  1388. if args.mode == "all" and args.output:
  1389. output = get_plot_path(args.output, "old_vs_new")
  1390. else:
  1391. output = args.output
  1392. deploy_plot("Additions vs changes", output, args.background)
  1393. def show_languages(args, name, start_date, end_date, people, days):
  1394. devlangs = defaultdict(lambda: defaultdict(lambda: numpy.zeros(3, dtype=int)))
  1395. for day, devs in days.items():
  1396. for dev, stats in devs.items():
  1397. for lang, vals in stats.Languages.items():
  1398. devlangs[dev][lang] += vals
  1399. devlangs = sorted(devlangs.items(), key=lambda p: -sum(x.sum() for x in p[1].values()))
  1400. for dev, ls in devlangs:
  1401. print()
  1402. print("#", people[dev])
  1403. ls = sorted(((vals.sum(), lang) for lang, vals in ls.items()), reverse=True)
  1404. for vals, lang in ls:
  1405. if lang:
  1406. print("%s: %d" % (lang, vals))
  1407. class ParallelDevData:
  1408. def __init__(self):
  1409. self.commits_rank = -1
  1410. self.commits = -1
  1411. self.lines_rank = -1
  1412. self.lines = -1
  1413. self.ownership_rank = -1
  1414. self.ownership = -1
  1415. self.couples_index = -1
  1416. self.couples_cluster = -1
  1417. self.commit_coocc_index = -1
  1418. self.commit_coocc_cluster = -1
  1419. def __str__(self):
  1420. return str(self.__dict__)
  1421. def __repr__(self):
  1422. return str(self)
  1423. def load_devs_parallel(ownership, couples, devs, max_people):
  1424. from seriate import seriate
  1425. try:
  1426. from hdbscan import HDBSCAN
  1427. except ImportError as e:
  1428. print("Cannot import ortools: %s\nInstall it from "
  1429. "https://developers.google.com/optimization/install/python/" % e)
  1430. sys.exit(1)
  1431. people, owned = ownership
  1432. _, cmatrix = couples
  1433. _, days = devs
  1434. print("calculating - commits")
  1435. commits = defaultdict(int)
  1436. for day, devs in days.items():
  1437. for dev, stats in devs.items():
  1438. commits[people[dev]] += stats.Commits
  1439. chosen = [k for v, k in sorted(((v, k) for k, v in commits.items()),
  1440. reverse=True)[:max_people]]
  1441. result = {k: ParallelDevData() for k in chosen}
  1442. for k, v in result.items():
  1443. v.commits_rank = chosen.index(k)
  1444. v.commits = commits[k]
  1445. print("calculating - lines")
  1446. lines = defaultdict(int)
  1447. for day, devs in days.items():
  1448. for dev, stats in devs.items():
  1449. lines[people[dev]] += stats.Added + stats.Removed + stats.Changed
  1450. lines_index = {k: i for i, (_, k) in enumerate(sorted(
  1451. ((v, k) for k, v in lines.items() if k in chosen), reverse=True))}
  1452. for k, v in result.items():
  1453. v.lines_rank = lines_index[k]
  1454. v.lines = lines[k]
  1455. print("calculating - ownership")
  1456. owned_index = {k: i for i, (_, k) in enumerate(sorted(
  1457. ((owned[k][-1].sum(), k) for k in chosen), reverse=True))}
  1458. for k, v in result.items():
  1459. v.ownership_rank = owned_index[k]
  1460. v.ownership = owned[k][-1].sum()
  1461. print("calculating - couples")
  1462. embeddings = numpy.genfromtxt(fname="couples_people_data.tsv", delimiter="\t")[
  1463. [people.index(k) for k in chosen]]
  1464. embeddings /= numpy.linalg.norm(embeddings, axis=1)[:, None]
  1465. cos = embeddings.dot(embeddings.T)
  1466. cos[cos > 1] = 1 # tiny precision faults
  1467. dists = numpy.arccos(cos)
  1468. clusters = HDBSCAN(min_cluster_size=2, metric="precomputed").fit_predict(dists)
  1469. for k, v in result.items():
  1470. v.couples_cluster = clusters[chosen.index(k)]
  1471. couples_order = seriate(dists)
  1472. roll_options = []
  1473. for i in range(len(couples_order)):
  1474. loss = 0
  1475. for k, v in result.items():
  1476. loss += abs(
  1477. v.ownership_rank - (couples_order.index(chosen.index(k)) + i) % len(chosen))
  1478. roll_options.append(loss)
  1479. best_roll = numpy.argmin(roll_options)
  1480. couples_order = list(numpy.roll(couples_order, best_roll))
  1481. for k, v in result.items():
  1482. v.couples_index = couples_order.index(chosen.index(k))
  1483. print("calculating - commit series")
  1484. dists, devseries, _, orig_route = order_commits(chosen, days, people)
  1485. keys = list(devseries.keys())
  1486. route = [keys[node] for node in orig_route]
  1487. for roll in range(len(route)):
  1488. loss = 0
  1489. for k, v in result.items():
  1490. i = route.index(people.index(k))
  1491. loss += abs(v.couples_index - ((i + roll) % len(route)))
  1492. roll_options[roll] = loss
  1493. best_roll = numpy.argmin(roll_options)
  1494. route = list(numpy.roll(route, best_roll))
  1495. orig_route = list(numpy.roll(orig_route, best_roll))
  1496. clusters = hdbscan_cluster_routed_series(dists, orig_route)
  1497. for k, v in result.items():
  1498. v.commit_coocc_index = route.index(people.index(k))
  1499. v.commit_coocc_cluster = clusters[v.commit_coocc_index]
  1500. return result
  1501. def show_devs_parallel(args, name, start_date, end_date, devs):
  1502. matplotlib, pyplot = import_pyplot(args.backend, args.style)
  1503. from matplotlib.collections import LineCollection
  1504. def solve_equations(x1, y1, x2, y2):
  1505. xcube = (x1 - x2) ** 3
  1506. a = 2 * (y2 - y1) / xcube
  1507. b = 3 * (y1 - y2) * (x1 + x2) / xcube
  1508. c = 6 * (y2 - y1) * x1 * x2 / xcube
  1509. d = y1 - a * x1 ** 3 - b * x1 ** 2 - c * x1
  1510. return a, b, c, d
  1511. # biggest = {k: max(getattr(d, k) for d in devs.values())
  1512. # for k in ("commits", "lines", "ownership")}
  1513. for k, dev in devs.items():
  1514. points = numpy.array([
  1515. (1, dev.commits_rank),
  1516. (2, dev.lines_rank),
  1517. (3, dev.ownership_rank),
  1518. (4, dev.couples_index),
  1519. (5, dev.commit_coocc_index)],
  1520. dtype=float)
  1521. points[:, 1] = points[:, 1] / len(devs)
  1522. splines = []
  1523. for i in range(len(points) - 1):
  1524. a, b, c, d = solve_equations(*points[i], *points[i + 1])
  1525. x = numpy.linspace(i + 1, i + 2, 100)
  1526. smooth_points = numpy.array(
  1527. [x, a * x ** 3 + b * x ** 2 + c * x + d]).T.reshape(-1, 1, 2)
  1528. splines.append(smooth_points)
  1529. points = numpy.concatenate(splines)
  1530. segments = numpy.concatenate([points[:-1], points[1:]], axis=1)
  1531. lc = LineCollection(segments)
  1532. lc.set_array(numpy.linspace(0, 0.1, segments.shape[0]))
  1533. pyplot.gca().add_collection(lc)
  1534. pyplot.xlim(0, 6)
  1535. pyplot.ylim(-0.1, 1.1)
  1536. deploy_plot("Developers", args.output, args.background)
  1537. def _format_number(n):
  1538. if n == 0:
  1539. return "0"
  1540. power = int(numpy.log10(abs(n)))
  1541. if power >= 6:
  1542. n = n / 1000000
  1543. if n >= 10:
  1544. n = str(int(n))
  1545. else:
  1546. n = "%.1f" % n
  1547. if n.endswith("0"):
  1548. n = n[:-2]
  1549. suffix = "M"
  1550. elif power >= 3:
  1551. n = n / 1000
  1552. if n >= 10:
  1553. n = str(int(n))
  1554. else:
  1555. n = "%.1f" % n
  1556. if n.endswith("0"):
  1557. n = n[:-2]
  1558. suffix = "K"
  1559. else:
  1560. n = str(n)
  1561. suffix = ""
  1562. return n + suffix
  1563. def main():
  1564. args = parse_args()
  1565. reader = read_input(args)
  1566. header = reader.get_header()
  1567. name = reader.get_name()
  1568. burndown_warning = "Burndown stats were not collected. Re-run hercules with --burndown."
  1569. burndown_files_warning = \
  1570. "Burndown stats for files were not collected. Re-run hercules with " \
  1571. "--burndown --burndown-files."
  1572. burndown_people_warning = \
  1573. "Burndown stats for people were not collected. Re-run hercules with " \
  1574. "--burndown --burndown-people."
  1575. couples_warning = "Coupling stats were not collected. Re-run hercules with --couples."
  1576. shotness_warning = "Structural hotness stats were not collected. Re-run hercules with " \
  1577. "--shotness. Also check --languages - the output may be empty."
  1578. sentiment_warning = "Sentiment stats were not collected. Re-run hercules with --sentiment."
  1579. devs_warning = "Devs stats were not collected. Re-run hercules with --devs."
  1580. def run_times():
  1581. rt = reader.get_run_times()
  1582. pandas = import_pandas()
  1583. series = pandas.to_timedelta(pandas.Series(rt).sort_values(ascending=False), unit="s")
  1584. df = pandas.concat([series, series / series.sum()], axis=1)
  1585. df.columns = ["time", "ratio"]
  1586. print(df)
  1587. def project_burndown():
  1588. try:
  1589. full_header = header + reader.get_burndown_parameters()
  1590. except KeyError:
  1591. print("project: " + burndown_warning)
  1592. return
  1593. plot_burndown(args, "project",
  1594. *load_burndown(full_header, *reader.get_project_burndown(),
  1595. resample=args.resample))
  1596. def files_burndown():
  1597. try:
  1598. full_header = header + reader.get_burndown_parameters()
  1599. except KeyError:
  1600. print(burndown_warning)
  1601. return
  1602. try:
  1603. plot_many_burndown(args, "file", full_header, reader.get_files_burndown())
  1604. except KeyError:
  1605. print("files: " + burndown_files_warning)
  1606. def people_burndown():
  1607. try:
  1608. full_header = header + reader.get_burndown_parameters()
  1609. except KeyError:
  1610. print(burndown_warning)
  1611. return
  1612. try:
  1613. plot_many_burndown(args, "person", full_header, reader.get_people_burndown())
  1614. except KeyError:
  1615. print("people: " + burndown_people_warning)
  1616. def overwrites_matrix():
  1617. try:
  1618. plot_overwrites_matrix(args, name, *load_overwrites_matrix(
  1619. *reader.get_people_interaction(), max_people=args.max_people))
  1620. people, matrix = load_overwrites_matrix(
  1621. *reader.get_people_interaction(), max_people=1000000, normalize=False)
  1622. from scipy.sparse import csr_matrix
  1623. matrix = matrix[:, 1:]
  1624. matrix = numpy.triu(matrix) + numpy.tril(matrix).T
  1625. matrix = matrix + matrix.T
  1626. matrix = csr_matrix(matrix)
  1627. try:
  1628. write_embeddings("overwrites", args.output, not args.disable_projector,
  1629. *train_embeddings(people, matrix, tmpdir=args.tmpdir))
  1630. except AttributeError as e:
  1631. print("Training the embeddings is not possible: %s: %s", type(e).__name__, e)
  1632. except KeyError:
  1633. print("overwrites_matrix: " + burndown_people_warning)
  1634. def ownership_burndown():
  1635. try:
  1636. full_header = header + reader.get_burndown_parameters()
  1637. except KeyError:
  1638. print(burndown_warning)
  1639. return
  1640. try:
  1641. plot_ownership(args, name, *load_ownership(
  1642. full_header, *reader.get_ownership_burndown(), max_people=args.max_people,
  1643. order_by_time=args.order_ownership_by_time))
  1644. except KeyError:
  1645. print("ownership: " + burndown_people_warning)
  1646. def couples_files():
  1647. try:
  1648. write_embeddings("files", args.output, not args.disable_projector,
  1649. *train_embeddings(*reader.get_files_coocc(),
  1650. tmpdir=args.tmpdir))
  1651. except KeyError:
  1652. print(couples_warning)
  1653. def couples_people():
  1654. try:
  1655. write_embeddings("people", args.output, not args.disable_projector,
  1656. *train_embeddings(*reader.get_people_coocc(),
  1657. tmpdir=args.tmpdir))
  1658. except KeyError:
  1659. print(couples_warning)
  1660. def couples_shotness():
  1661. try:
  1662. write_embeddings("shotness", args.output, not args.disable_projector,
  1663. *train_embeddings(*reader.get_shotness_coocc(),
  1664. tmpdir=args.tmpdir))
  1665. except KeyError:
  1666. print(shotness_warning)
  1667. def shotness():
  1668. try:
  1669. data = reader.get_shotness()
  1670. except KeyError:
  1671. print(shotness_warning)
  1672. return
  1673. show_shotness_stats(data)
  1674. def sentiment():
  1675. try:
  1676. data = reader.get_sentiment()
  1677. except KeyError:
  1678. print(sentiment_warning)
  1679. return
  1680. show_sentiment_stats(args, reader.get_name(), args.resample, reader.get_header()[0], data)
  1681. def devs():
  1682. try:
  1683. data = reader.get_devs()
  1684. except KeyError:
  1685. print(devs_warning)
  1686. return
  1687. show_devs(args, reader.get_name(), *reader.get_header(), *data,
  1688. max_people=args.max_people)
  1689. def devs_efforts():
  1690. try:
  1691. data = reader.get_devs()
  1692. except KeyError:
  1693. print(devs_warning)
  1694. return
  1695. show_devs_efforts(args, reader.get_name(), *reader.get_header(), *data,
  1696. max_people=args.max_people)
  1697. def old_vs_new():
  1698. try:
  1699. data = reader.get_devs()
  1700. except KeyError:
  1701. print(devs_warning)
  1702. return
  1703. show_old_vs_new(args, reader.get_name(), *reader.get_header(), *data)
  1704. def languages():
  1705. try:
  1706. data = reader.get_devs()
  1707. except KeyError:
  1708. print(devs_warning)
  1709. return
  1710. show_languages(args, reader.get_name(), *reader.get_header(), *data)
  1711. def devs_parallel():
  1712. try:
  1713. ownership = reader.get_ownership_burndown()
  1714. except KeyError:
  1715. print(burndown_people_warning)
  1716. return
  1717. try:
  1718. couples = reader.get_people_coocc()
  1719. except KeyError:
  1720. print(couples_warning)
  1721. return
  1722. try:
  1723. devs = reader.get_devs()
  1724. except KeyError:
  1725. print(devs_warning)
  1726. return
  1727. show_devs_parallel(args, reader.get_name(), *reader.get_header(),
  1728. load_devs_parallel(ownership, couples, devs, args.max_people))
  1729. modes = {
  1730. "run-times": run_times,
  1731. "burndown-project": project_burndown,
  1732. "burndown-file": files_burndown,
  1733. "burndown-person": people_burndown,
  1734. "overwrites-matrix": overwrites_matrix,
  1735. "ownership": ownership_burndown,
  1736. "couples-files": couples_files,
  1737. "couples-people": couples_people,
  1738. "couples-shotness": couples_shotness,
  1739. "shotness": shotness,
  1740. "sentiment": sentiment,
  1741. "devs": devs,
  1742. "devs-efforts": devs_efforts,
  1743. "old-vs-new": old_vs_new,
  1744. "languages": languages,
  1745. "devs-parallel": devs_parallel,
  1746. }
  1747. if "all" in args.modes:
  1748. all_mode = True
  1749. args.modes = [
  1750. "burndown-project",
  1751. "overwrites-matrix",
  1752. "ownership",
  1753. "couples-files",
  1754. "couples-people",
  1755. "couples-shotness",
  1756. "shotness",
  1757. "devs",
  1758. "devs-efforts",
  1759. ]
  1760. else:
  1761. all_mode = False
  1762. for mode in args.modes:
  1763. if mode not in modes:
  1764. print("Unknown mode: %s" % mode)
  1765. continue
  1766. print("Running: %s" % mode)
  1767. # `args.mode` is required for path determination in the mode functions
  1768. args.mode = ("all" if all_mode else mode)
  1769. try:
  1770. modes[mode]()
  1771. except ImportError as ie:
  1772. print("A module required by the %s mode was not found: %s" % (mode, ie))
  1773. if not all_mode:
  1774. raise
  1775. if web_server.running:
  1776. secs = int(os.getenv("COUPLES_SERVER_TIME", "60"))
  1777. print("Sleeping for %d seconds, safe to Ctrl-C" % secs)
  1778. sys.stdout.flush()
  1779. try:
  1780. time.sleep(secs)
  1781. except KeyboardInterrupt:
  1782. pass
  1783. web_server.stop()
  1784. if __name__ == "__main__":
  1785. sys.exit(main())