labours.py 75 KB

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