labours.py 73 KB

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