labours.py 73 KB

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