labours.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. #!/usr/bin/env python3
  2. import argparse
  3. from datetime import datetime, timedelta
  4. from importlib import import_module
  5. import io
  6. import json
  7. import os
  8. import re
  9. import shutil
  10. import sys
  11. import tempfile
  12. import threading
  13. import time
  14. import warnings
  15. try:
  16. from clint.textui import progress
  17. except ImportError:
  18. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  19. progress = None
  20. import numpy
  21. import yaml
  22. if sys.version_info[0] < 3:
  23. # OK, ancients, I will support Python 2, but you owe me a beer
  24. input = raw_input
  25. PB_MESSAGES = {
  26. "Burndown": "internal.pb.pb_pb2.BurndownAnalysisResults",
  27. "Couples": "internal.pb.pb_pb2.CouplesAnalysisResults",
  28. "Shotness": "internal.pb.pb_pb2.ShotnessAnalysisResults",
  29. }
  30. def parse_args():
  31. parser = argparse.ArgumentParser()
  32. parser.add_argument("-o", "--output", default="",
  33. help="Path to the output file/directory (empty for display). "
  34. "If the extension is JSON, the data is saved instead of "
  35. "the real image.")
  36. parser.add_argument("-i", "--input", default="-",
  37. help="Path to the input file (- for stdin).")
  38. parser.add_argument("-f", "--input-format", default="auto", choices=["yaml", "pb", "auto"])
  39. parser.add_argument("--text-size", default=12, type=int,
  40. help="Size of the labels and legend.")
  41. parser.add_argument("--backend", help="Matplotlib backend to use.")
  42. parser.add_argument("--style", choices=["black", "white"], default="black",
  43. help="Plot's general color scheme.")
  44. parser.add_argument("--size", help="Axes' size in inches, for example \"12,9\"")
  45. parser.add_argument("--relative", action="store_true",
  46. help="Occupy 100%% height for every measurement.")
  47. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  48. parser.add_argument("-m", "--mode",
  49. choices=["project", "file", "person", "churn_matrix", "ownership",
  50. "couples", "shotness", "sentiment", "all", "run_times"],
  51. help="What to plot.")
  52. parser.add_argument(
  53. "--resample", default="year",
  54. help="The way to resample the time series. Possible values are: "
  55. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  56. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  57. "#offset-aliases).")
  58. parser.add_argument("--disable-projector", action="store_true",
  59. help="Do not run Tensorflow Projector on couples.")
  60. parser.add_argument("--max-people", default=20, type=int,
  61. help="Maximum number of developers in churn matrix and people plots.")
  62. args = parser.parse_args()
  63. return args
  64. class Reader(object):
  65. def read(self, file):
  66. raise NotImplementedError
  67. def get_name(self):
  68. raise NotImplementedError
  69. def get_header(self):
  70. raise NotImplementedError
  71. def get_burndown_parameters(self):
  72. raise NotImplementedError
  73. def get_project_burndown(self):
  74. raise NotImplementedError
  75. def get_files_burndown(self):
  76. raise NotImplementedError
  77. def get_people_burndown(self):
  78. raise NotImplementedError
  79. def get_ownership_burndown(self):
  80. raise NotImplementedError
  81. def get_people_interaction(self):
  82. raise NotImplementedError
  83. def get_files_coocc(self):
  84. raise NotImplementedError
  85. def get_people_coocc(self):
  86. raise NotImplementedError
  87. def get_shotness_coocc(self):
  88. raise NotImplementedError
  89. def get_shotness(self):
  90. raise NotImplementedError
  91. class YamlReader(Reader):
  92. def read(self, file):
  93. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  94. try:
  95. loader = yaml.CLoader
  96. except AttributeError:
  97. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  98. loader = yaml.Loader
  99. try:
  100. if file != "-":
  101. with open(file) as fin:
  102. data = yaml.load(fin, Loader=loader)
  103. else:
  104. data = yaml.load(sys.stdin, Loader=loader)
  105. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  106. print("\nInvalid unicode in the input: %s\nPlease filter it through "
  107. "fix_yaml_unicode.py" % e)
  108. sys.exit(1)
  109. self.data = data
  110. def get_run_times(self):
  111. return {}
  112. def get_name(self):
  113. return self.data["hercules"]["repository"]
  114. def get_header(self):
  115. header = self.data["hercules"]
  116. return header["begin_unix_time"], header["end_unix_time"]
  117. def get_burndown_parameters(self):
  118. header = self.data["Burndown"]
  119. return header["sampling"], header["granularity"]
  120. def get_project_burndown(self):
  121. return self.data["hercules"]["repository"], \
  122. self._parse_burndown_matrix(self.data["Burndown"]["project"]).T
  123. def get_files_burndown(self):
  124. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  125. for p in self.data["Burndown"]["files"].items()]
  126. def get_people_burndown(self):
  127. return [(p[0], self._parse_burndown_matrix(p[1]).T)
  128. for p in self.data["Burndown"]["people"].items()]
  129. def get_ownership_burndown(self):
  130. return self.data["Burndown"]["people_sequence"].copy(),\
  131. {p[0]: self._parse_burndown_matrix(p[1])
  132. for p in self.data["Burndown"]["people"].items()}
  133. def get_people_interaction(self):
  134. return self.data["Burndown"]["people_sequence"].copy(), \
  135. self._parse_burndown_matrix(self.data["Burndown"]["people_interaction"])
  136. def get_files_coocc(self):
  137. coocc = self.data["Couples"]["files_coocc"]
  138. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  139. def get_people_coocc(self):
  140. coocc = self.data["Couples"]["people_coocc"]
  141. return coocc["index"], self._parse_coocc_matrix(coocc["matrix"])
  142. def get_shotness_coocc(self):
  143. shotness = self.data["Shotness"]
  144. index = ["%s:%s" % (i["file"], i["name"]) for i in shotness]
  145. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int64)
  146. indices = []
  147. data = []
  148. for i, record in enumerate(shotness):
  149. pairs = [(int(k), v) for k, v in record["counters"].items()]
  150. pairs.sort()
  151. indptr[i + 1] = indptr[i] + len(pairs)
  152. for k, v in pairs:
  153. indices.append(k)
  154. data.append(v)
  155. indices = numpy.array(indices, dtype=numpy.int32)
  156. data = numpy.array(data, dtype=numpy.int32)
  157. from scipy.sparse import csr_matrix
  158. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  159. def get_shotness(self):
  160. from munch import munchify
  161. obj = munchify(self.data["Shotness"])
  162. # turn strings into ints
  163. for item in obj:
  164. item.counters = {int(k): v for k, v in item.counters.items()}
  165. if len(obj) == 0:
  166. raise KeyError
  167. return obj
  168. def get_sentiment(self):
  169. from munch import munchify
  170. return munchify({int(key): {
  171. "Comments": vals[2].split("|"),
  172. "Commits": vals[1],
  173. "Value": float(vals[0])
  174. } for key, vals in self.data["Sentiment"].items()})
  175. def _parse_burndown_matrix(self, matrix):
  176. return numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  177. for line in matrix.split("\n")])
  178. def _parse_coocc_matrix(self, matrix):
  179. from scipy.sparse import csr_matrix
  180. data = []
  181. indices = []
  182. indptr = [0]
  183. for row in matrix:
  184. for k, v in sorted(row.items()):
  185. data.append(v)
  186. indices.append(k)
  187. indptr.append(indptr[-1] + len(row))
  188. return csr_matrix((data, indices, indptr), shape=(len(matrix),) * 2)
  189. class ProtobufReader(Reader):
  190. def read(self, file):
  191. try:
  192. from internal.pb.pb_pb2 import AnalysisResults
  193. except ImportError as e:
  194. print("\n\n>>> You need to generate internal/pb/pb_pb2.py - run \"make\"\n",
  195. file=sys.stderr)
  196. raise e from None
  197. self.data = AnalysisResults()
  198. if file != "-":
  199. with open(file, "rb") as fin:
  200. self.data.ParseFromString(fin.read())
  201. else:
  202. self.data.ParseFromString(sys.stdin.buffer.read())
  203. self.contents = {}
  204. for key, val in self.data.contents.items():
  205. try:
  206. mod, name = PB_MESSAGES[key].rsplit(".", 1)
  207. except KeyError:
  208. sys.stderr.write("Warning: there is no registered PB decoder for %s\n" % key)
  209. continue
  210. cls = getattr(import_module(mod), name)
  211. self.contents[key] = msg = cls()
  212. msg.ParseFromString(val)
  213. def get_run_times(self):
  214. return {key: val for key, val in self.data.header.run_time_per_item.items()}
  215. def get_name(self):
  216. return self.data.header.repository
  217. def get_header(self):
  218. header = self.data.header
  219. return header.begin_unix_time, header.end_unix_time
  220. def get_burndown_parameters(self):
  221. burndown = self.contents["Burndown"]
  222. return burndown.sampling, burndown.granularity
  223. def get_project_burndown(self):
  224. return self._parse_burndown_matrix(self.contents["Burndown"].project)
  225. def get_files_burndown(self):
  226. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].files]
  227. def get_people_burndown(self):
  228. return [self._parse_burndown_matrix(i) for i in self.contents["Burndown"].people]
  229. def get_ownership_burndown(self):
  230. people = self.get_people_burndown()
  231. return [p[0] for p in people], {p[0]: p[1].T for p in people}
  232. def get_people_interaction(self):
  233. burndown = self.contents["Burndown"]
  234. return [i.name for i in burndown.people], \
  235. self._parse_sparse_matrix(burndown.people_interaction).toarray()
  236. def get_files_coocc(self):
  237. node = self.contents["Couples"].file_couples
  238. return list(node.index), self._parse_sparse_matrix(node.matrix)
  239. def get_people_coocc(self):
  240. node = self.contents["Couples"].people_couples
  241. return list(node.index), self._parse_sparse_matrix(node.matrix)
  242. def get_shotness_coocc(self):
  243. shotness = self.get_shotness()
  244. index = ["%s:%s" % (i.file, i.name) for i in shotness]
  245. indptr = numpy.zeros(len(shotness) + 1, dtype=numpy.int32)
  246. indices = []
  247. data = []
  248. for i, record in enumerate(shotness):
  249. pairs = list(record.counters.items())
  250. pairs.sort()
  251. indptr[i + 1] = indptr[i] + len(pairs)
  252. for k, v in pairs:
  253. indices.append(k)
  254. data.append(v)
  255. indices = numpy.array(indices, dtype=numpy.int32)
  256. data = numpy.array(data, dtype=numpy.int32)
  257. from scipy.sparse import csr_matrix
  258. return index, csr_matrix((data, indices, indptr), shape=(len(shotness),) * 2)
  259. def get_shotness(self):
  260. records = self.contents["Shotness"].records
  261. if len(records) == 0:
  262. raise KeyError
  263. return records
  264. def get_sentiment(self):
  265. byday = self.contents["Sentiment"].SentimentByDay
  266. if len(byday) == 0:
  267. raise KeyError
  268. return byday
  269. def _parse_burndown_matrix(self, matrix):
  270. dense = numpy.zeros((matrix.number_of_rows, matrix.number_of_columns), dtype=int)
  271. for y, row in enumerate(matrix.rows):
  272. for x, col in enumerate(row.columns):
  273. dense[y, x] = col
  274. return matrix.name, dense.T
  275. def _parse_sparse_matrix(self, matrix):
  276. from scipy.sparse import csr_matrix
  277. return csr_matrix((list(matrix.data), list(matrix.indices), list(matrix.indptr)),
  278. shape=(matrix.number_of_rows, matrix.number_of_columns))
  279. READERS = {"yaml": YamlReader, "yml": YamlReader, "pb": ProtobufReader}
  280. def read_input(args):
  281. sys.stdout.write("Reading the input... ")
  282. sys.stdout.flush()
  283. if args.input != "-":
  284. if args.input_format == "auto":
  285. args.input_format = args.input.rsplit(".", 1)[1]
  286. elif args.input_format == "auto":
  287. args.input_format = "yaml"
  288. reader = READERS[args.input_format]()
  289. reader.read(args.input)
  290. print("done")
  291. return reader
  292. def calculate_average_lifetime(matrix):
  293. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  294. for band in matrix:
  295. start = 0
  296. for i, line in enumerate(band):
  297. if i == 0 or band[i - 1] == 0:
  298. start += 1
  299. continue
  300. lifetimes[i - start] = band[i - 1] - line
  301. lifetimes[i - start] = band[i - 1]
  302. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  303. / (lifetimes.sum() * matrix.shape[1]))
  304. def interpolate_burndown_matrix(matrix, granularity, sampling):
  305. daily = numpy.zeros(
  306. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  307. dtype=numpy.float32)
  308. """
  309. ----------> samples, x
  310. |
  311. |
  312. |
  313. bands, y
  314. """
  315. for y in range(matrix.shape[0]):
  316. for x in range(matrix.shape[1]):
  317. if y * granularity > (x + 1) * sampling:
  318. # the future is zeros
  319. continue
  320. def decay(start_index: int, start_val: float):
  321. if start_val == 0:
  322. return
  323. k = matrix[y][x] / start_val # <= 1
  324. scale = (x + 1) * sampling - start_index
  325. for i in range(y * granularity, (y + 1) * granularity):
  326. initial = daily[i][start_index - 1]
  327. for j in range(start_index, (x + 1) * sampling):
  328. daily[i][j] = initial * (
  329. 1 + (k - 1) * (j - start_index + 1) / scale)
  330. def grow(finish_index: int, finish_val: float):
  331. initial = matrix[y][x - 1] if x > 0 else 0
  332. start_index = x * sampling
  333. if start_index < y * granularity:
  334. start_index = y * granularity
  335. if finish_index == start_index:
  336. return
  337. avg = (finish_val - initial) / (finish_index - start_index)
  338. for j in range(x * sampling, finish_index):
  339. for i in range(start_index, j + 1):
  340. daily[i][j] = avg
  341. # copy [x*g..y*s)
  342. for j in range(x * sampling, finish_index):
  343. for i in range(y * granularity, x * sampling):
  344. daily[i][j] = daily[i][j - 1]
  345. if (y + 1) * granularity >= (x + 1) * sampling:
  346. # x*granularity <= (y+1)*sampling
  347. # 1. x*granularity <= y*sampling
  348. # y*sampling..(y+1)sampling
  349. #
  350. # x+1
  351. # /
  352. # /
  353. # / y+1 -|
  354. # / |
  355. # / y -|
  356. # /
  357. # / x
  358. #
  359. # 2. x*granularity > y*sampling
  360. # x*granularity..(y+1)sampling
  361. #
  362. # x+1
  363. # /
  364. # /
  365. # / y+1 -|
  366. # / |
  367. # / x -|
  368. # /
  369. # / y
  370. if y * granularity <= x * sampling:
  371. grow((x + 1) * sampling, matrix[y][x])
  372. elif (x + 1) * sampling > y * granularity:
  373. grow((x + 1) * sampling, matrix[y][x])
  374. avg = matrix[y][x] / ((x + 1) * sampling - y * granularity)
  375. for j in range(y * granularity, (x + 1) * sampling):
  376. for i in range(y * granularity, j + 1):
  377. daily[i][j] = avg
  378. elif (y + 1) * granularity >= x * sampling:
  379. # y*sampling <= (x+1)*granularity < (y+1)sampling
  380. # y*sampling..(x+1)*granularity
  381. # (x+1)*granularity..(y+1)sampling
  382. # x+1
  383. # /\
  384. # / \
  385. # / \
  386. # / y+1
  387. # /
  388. # y
  389. v1 = matrix[y][x - 1]
  390. v2 = matrix[y][x]
  391. delta = (y + 1) * granularity - x * sampling
  392. previous = 0
  393. if x > 0 and (x - 1) * sampling >= y * granularity:
  394. # x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  395. # |________|.......^
  396. if x > 1:
  397. previous = matrix[y][x - 2]
  398. scale = sampling
  399. else:
  400. # (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  401. # |______|.......^
  402. scale = sampling if x == 0 else x * sampling - y * granularity
  403. peak = v1 + (v1 - previous) / scale * delta
  404. if v2 > peak:
  405. # we need to adjust the peak, it may not be less than the decayed value
  406. if x < matrix.shape[1] - 1:
  407. # y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  408. # ^.........|_________|
  409. k = (v2 - matrix[y][x + 1]) / sampling # > 0
  410. peak = matrix[y][x] + k * ((x + 1) * sampling - (y + 1) * granularity)
  411. # peak > v2 > v1
  412. else:
  413. peak = v2
  414. # not enough data to interpolate; this is at least not restricted
  415. grow((y + 1) * granularity, peak)
  416. decay((y + 1) * granularity, peak)
  417. else:
  418. # (x+1)*granularity < y*sampling
  419. # y*sampling..(y+1)sampling
  420. decay(x * sampling, matrix[y][x - 1])
  421. return daily
  422. def load_burndown(header, name, matrix, resample):
  423. import pandas
  424. start, last, sampling, granularity = header
  425. assert sampling > 0
  426. assert granularity >= sampling
  427. start = datetime.fromtimestamp(start)
  428. last = datetime.fromtimestamp(last)
  429. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  430. finish = start + timedelta(days=matrix.shape[1] * sampling)
  431. if resample not in ("no", "raw"):
  432. print("resampling to %s, please wait..." % resample)
  433. # Interpolate the day x day matrix.
  434. # Each day brings equal weight in the granularity.
  435. # Sampling's interpolation is linear.
  436. daily = interpolate_burndown_matrix(matrix, granularity, sampling)
  437. daily[(last - start).days:] = 0
  438. # Resample the bands
  439. aliases = {
  440. "year": "A",
  441. "month": "M"
  442. }
  443. resample = aliases.get(resample, resample)
  444. periods = 0
  445. date_granularity_sampling = [start]
  446. while date_granularity_sampling[-1] < finish:
  447. periods += 1
  448. date_granularity_sampling = pandas.date_range(
  449. start, periods=periods, freq=resample)
  450. date_range_sampling = pandas.date_range(
  451. date_granularity_sampling[0],
  452. periods=(finish - date_granularity_sampling[0]).days,
  453. freq="1D")
  454. # Fill the new square matrix
  455. matrix = numpy.zeros(
  456. (len(date_granularity_sampling), len(date_range_sampling)),
  457. dtype=numpy.float32)
  458. for i, gdt in enumerate(date_granularity_sampling):
  459. istart = (date_granularity_sampling[i - 1] - start).days \
  460. if i > 0 else 0
  461. ifinish = (gdt - start).days
  462. for j, sdt in enumerate(date_range_sampling):
  463. if (sdt - start).days >= istart:
  464. break
  465. matrix[i, j:] = \
  466. daily[istart:ifinish, (sdt - start).days:].sum(axis=0)
  467. # Hardcode some cases to improve labels' readability
  468. if resample in ("year", "A"):
  469. labels = [dt.year for dt in date_granularity_sampling]
  470. elif resample in ("month", "M"):
  471. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  472. else:
  473. labels = [dt.date() for dt in date_granularity_sampling]
  474. else:
  475. labels = [
  476. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  477. (
  478. start + timedelta(days=(i + 1) * granularity)).date())
  479. for i in range(matrix.shape[0])]
  480. if len(labels) > 18:
  481. warnings.warn("Too many labels - consider resampling.")
  482. resample = "M" # fake resampling type is checked while plotting
  483. date_range_sampling = pandas.date_range(
  484. start + timedelta(days=sampling), periods=matrix.shape[1],
  485. freq="%dD" % sampling)
  486. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  487. def load_ownership(header, sequence, contents, max_people):
  488. import pandas
  489. start, last, sampling, _ = header
  490. start = datetime.fromtimestamp(start)
  491. last = datetime.fromtimestamp(last)
  492. people = []
  493. for name in sequence:
  494. people.append(contents[name].sum(axis=1))
  495. people = numpy.array(people)
  496. date_range_sampling = pandas.date_range(
  497. start + timedelta(days=sampling), periods=people[0].shape[0],
  498. freq="%dD" % sampling)
  499. if people.shape[0] > max_people:
  500. order = numpy.argsort(-people.sum(axis=1))
  501. people = people[order[:max_people]]
  502. sequence = [sequence[i] for i in order[:max_people]]
  503. print("Warning: truncated people to most owning %d" % max_people)
  504. for i, name in enumerate(sequence):
  505. if len(name) > 40:
  506. sequence[i] = name[:37] + "..."
  507. return sequence, people, date_range_sampling, last
  508. def load_churn_matrix(people, matrix, max_people):
  509. matrix = matrix.astype(float)
  510. if matrix.shape[0] > max_people:
  511. order = numpy.argsort(-matrix[:, 0])
  512. matrix = matrix[order[:max_people]][:, [0, 1] + list(2 + order[:max_people])]
  513. people = [people[i] for i in order[:max_people]]
  514. print("Warning: truncated people to most productive %d" % max_people)
  515. zeros = matrix[:, 0] == 0
  516. matrix[zeros, :] = 1
  517. matrix /= matrix[:, 0][:, None]
  518. matrix = -matrix[:, 1:]
  519. matrix[zeros, :] = 0
  520. for i, name in enumerate(people):
  521. if len(name) > 40:
  522. people[i] = name[:37] + "..."
  523. return people, matrix
  524. def apply_plot_style(figure, axes, legend, style, text_size, axes_size):
  525. if axes_size is None:
  526. axes_size = (12, 9)
  527. else:
  528. axes_size = tuple(float(p) for p in axes_size.split(","))
  529. figure.set_size_inches(*axes_size)
  530. for side in ("bottom", "top", "left", "right"):
  531. axes.spines[side].set_color(style)
  532. for axis in (axes.xaxis, axes.yaxis):
  533. axis.label.update(dict(fontsize=text_size, color=style))
  534. for axis in ("x", "y"):
  535. getattr(axes, axis + "axis").get_offset_text().set_size(text_size)
  536. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  537. try:
  538. axes.ticklabel_format(axis="y", style="sci", scilimits=(0, 3))
  539. except AttributeError:
  540. pass
  541. if legend is not None:
  542. frame = legend.get_frame()
  543. for setter in (frame.set_facecolor, frame.set_edgecolor):
  544. setter("black" if style == "white" else "white")
  545. for text in legend.get_texts():
  546. text.set_color(style)
  547. def get_plot_path(base, name):
  548. root, ext = os.path.splitext(base)
  549. if not ext:
  550. ext = ".png"
  551. output = os.path.join(root, name + ext)
  552. os.makedirs(os.path.dirname(output), exist_ok=True)
  553. return output
  554. def deploy_plot(title, output, style):
  555. import matplotlib.pyplot as pyplot
  556. if not output:
  557. pyplot.gcf().canvas.set_window_title(title)
  558. pyplot.show()
  559. else:
  560. if title:
  561. pyplot.title(title, color=style)
  562. try:
  563. pyplot.tight_layout()
  564. except:
  565. print("Warning: failed to set the tight layout")
  566. pyplot.savefig(output, transparent=True)
  567. pyplot.clf()
  568. def default_json(x):
  569. if hasattr(x, "tolist"):
  570. return x.tolist()
  571. if hasattr(x, "isoformat"):
  572. return x.isoformat()
  573. return x
  574. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  575. sampling, resample):
  576. if args.output and args.output.endswith(".json"):
  577. data = locals().copy()
  578. del data["args"]
  579. data["type"] = "burndown"
  580. if args.mode == "project" and target == "project":
  581. output = args.output
  582. else:
  583. if target == "project":
  584. name = "project"
  585. output = get_plot_path(args.output, name)
  586. with open(output, "w") as fout:
  587. json.dump(data, fout, sort_keys=True, default=default_json)
  588. return
  589. import matplotlib
  590. if args.backend:
  591. matplotlib.use(args.backend)
  592. import matplotlib.pyplot as pyplot
  593. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  594. if args.relative:
  595. for i in range(matrix.shape[1]):
  596. matrix[:, i] /= matrix[:, i].sum()
  597. pyplot.ylim(0, 1)
  598. legend_loc = 3
  599. else:
  600. legend_loc = 2
  601. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  602. pyplot.ylabel("Lines of code")
  603. pyplot.xlabel("Time")
  604. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size, args.size)
  605. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  606. locator = pyplot.gca().xaxis.get_major_locator()
  607. # set the optimal xticks locator
  608. if "M" not in resample:
  609. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  610. locs = pyplot.gca().get_xticks().tolist()
  611. if len(locs) >= 16:
  612. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  613. locs = pyplot.gca().get_xticks().tolist()
  614. if len(locs) >= 16:
  615. pyplot.gca().xaxis.set_major_locator(locator)
  616. if locs[0] < pyplot.xlim()[0]:
  617. del locs[0]
  618. endindex = -1
  619. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  620. locs.append(pyplot.xlim()[1])
  621. endindex = len(locs) - 1
  622. startindex = -1
  623. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  624. locs.append(pyplot.xlim()[0])
  625. startindex = len(locs) - 1
  626. pyplot.gca().set_xticks(locs)
  627. # hacking time!
  628. labels = pyplot.gca().get_xticklabels()
  629. if startindex >= 0:
  630. labels[startindex].set_text(date_range_sampling[0].date())
  631. labels[startindex].set_text = lambda _: None
  632. labels[startindex].set_rotation(30)
  633. labels[startindex].set_ha("right")
  634. if endindex >= 0:
  635. labels[endindex].set_text(date_range_sampling[-1].date())
  636. labels[endindex].set_text = lambda _: None
  637. labels[endindex].set_rotation(30)
  638. labels[endindex].set_ha("right")
  639. title = "%s %d x %d (granularity %d, sampling %d)" % \
  640. ((name,) + matrix.shape + (granularity, sampling))
  641. output = args.output
  642. if output:
  643. if args.mode == "project" and target == "project":
  644. output = args.output
  645. else:
  646. if target == "project":
  647. name = "project"
  648. output = get_plot_path(args.output, name)
  649. deploy_plot(title, output, args.style)
  650. def plot_many_burndown(args, target, header, parts):
  651. if not args.output:
  652. print("Warning: output not set, showing %d plots." % len(parts))
  653. itercnt = progress.bar(parts, expected_size=len(parts)) \
  654. if progress is not None else parts
  655. stdout = io.StringIO()
  656. for name, matrix in itercnt:
  657. backup = sys.stdout
  658. sys.stdout = stdout
  659. plot_burndown(args, target, *load_burndown(header, name, matrix, args.resample))
  660. sys.stdout = backup
  661. sys.stdout.write(stdout.getvalue())
  662. def plot_churn_matrix(args, repo, people, matrix):
  663. if args.output and args.output.endswith(".json"):
  664. data = locals().copy()
  665. del data["args"]
  666. data["type"] = "churn_matrix"
  667. if args.mode == "all":
  668. output = get_plot_path(args.output, "matrix")
  669. else:
  670. output = args.output
  671. with open(output, "w") as fout:
  672. json.dump(data, fout, sort_keys=True, default=default_json)
  673. return
  674. import matplotlib
  675. if args.backend:
  676. matplotlib.use(args.backend)
  677. import matplotlib.pyplot as pyplot
  678. s = 4 + matrix.shape[1] * 0.3
  679. fig = pyplot.figure(figsize=(s, s))
  680. ax = fig.add_subplot(111)
  681. ax.xaxis.set_label_position("top")
  682. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  683. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  684. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  685. ax.set_yticklabels(people, va="center")
  686. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  687. ax.set_xticklabels(["Unidentified"] + people, rotation=45, ha="left",
  688. va="bottom", rotation_mode="anchor")
  689. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  690. ax.grid(which="minor")
  691. apply_plot_style(fig, ax, None, args.style, args.text_size, args.size)
  692. if not args.output:
  693. pos1 = ax.get_position()
  694. pos2 = (pos1.x0 + 0.15, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  695. ax.set_position(pos2)
  696. if args.mode == "all":
  697. output = get_plot_path(args.output, "matrix")
  698. else:
  699. output = args.output
  700. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  701. if args.output:
  702. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  703. title = ""
  704. deploy_plot(title, output, args.style)
  705. def plot_ownership(args, repo, names, people, date_range, last):
  706. if args.output and args.output.endswith(".json"):
  707. data = locals().copy()
  708. del data["args"]
  709. data["type"] = "ownership"
  710. if args.mode == "all":
  711. output = get_plot_path(args.output, "people")
  712. else:
  713. output = args.output
  714. with open(output, "w") as fout:
  715. json.dump(data, fout, sort_keys=True, default=default_json)
  716. return
  717. import matplotlib
  718. if args.backend:
  719. matplotlib.use(args.backend)
  720. import matplotlib.pyplot as pyplot
  721. pyplot.stackplot(date_range, people, labels=names)
  722. pyplot.xlim(date_range[0], last)
  723. if args.relative:
  724. for i in range(people.shape[1]):
  725. people[:, i] /= people[:, i].sum()
  726. pyplot.ylim(0, 1)
  727. legend_loc = 3
  728. else:
  729. legend_loc = 2
  730. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  731. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size, args.size)
  732. if args.mode == "all":
  733. output = get_plot_path(args.output, "people")
  734. else:
  735. output = args.output
  736. deploy_plot("%s code ownership through time" % repo, output, args.style)
  737. IDEAL_SHARD_SIZE = 4096
  738. def train_embeddings(index, matrix, tmpdir, shard_size=IDEAL_SHARD_SIZE):
  739. try:
  740. from . import swivel
  741. except (SystemError, ImportError):
  742. import swivel
  743. import tensorflow as tf
  744. assert matrix.shape[0] == matrix.shape[1]
  745. assert len(index) <= matrix.shape[0]
  746. outlier_threshold = numpy.percentile(matrix.data, 99)
  747. matrix.data[matrix.data > outlier_threshold] = outlier_threshold
  748. nshards = len(index) // shard_size
  749. if nshards * shard_size < len(index):
  750. nshards += 1
  751. shard_size = len(index) // nshards
  752. nshards = len(index) // shard_size
  753. remainder = len(index) - nshards * shard_size
  754. if remainder > 0:
  755. lengths = matrix.indptr[1:] - matrix.indptr[:-1]
  756. filtered = sorted(numpy.argsort(lengths)[remainder:])
  757. else:
  758. filtered = list(range(len(index)))
  759. if len(filtered) < matrix.shape[0]:
  760. print("Truncating the sparse matrix...")
  761. matrix = matrix[filtered, :][:, filtered]
  762. meta_index = []
  763. for i, j in enumerate(filtered):
  764. meta_index.append((index[j], matrix[i, i]))
  765. index = [mi[0] for mi in meta_index]
  766. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  767. print("Writing Swivel metadata...")
  768. vocabulary = "\n".join(index)
  769. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  770. out.write(vocabulary)
  771. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  772. out.write(vocabulary)
  773. del vocabulary
  774. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  775. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  776. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  777. out.write(bool_sums_str)
  778. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  779. out.write(bool_sums_str)
  780. del bool_sums_str
  781. reorder = numpy.argsort(-bool_sums)
  782. print("Writing Swivel shards...")
  783. for row in range(nshards):
  784. for col in range(nshards):
  785. def _int64s(xs):
  786. return tf.train.Feature(
  787. int64_list=tf.train.Int64List(value=list(xs)))
  788. def _floats(xs):
  789. return tf.train.Feature(
  790. float_list=tf.train.FloatList(value=list(xs)))
  791. indices_row = reorder[row::nshards]
  792. indices_col = reorder[col::nshards]
  793. shard = matrix[indices_row][:, indices_col].tocoo()
  794. example = tf.train.Example(features=tf.train.Features(feature={
  795. "global_row": _int64s(indices_row),
  796. "global_col": _int64s(indices_col),
  797. "sparse_local_row": _int64s(shard.row),
  798. "sparse_local_col": _int64s(shard.col),
  799. "sparse_value": _floats(shard.data)}))
  800. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  801. out.write(example.SerializeToString())
  802. print("Training Swivel model...")
  803. swivel.FLAGS.submatrix_rows = shard_size
  804. swivel.FLAGS.submatrix_cols = shard_size
  805. if len(meta_index) <= IDEAL_SHARD_SIZE / 16:
  806. embedding_size = 50
  807. num_epochs = 20000
  808. elif len(meta_index) <= IDEAL_SHARD_SIZE:
  809. embedding_size = 50
  810. num_epochs = 10000
  811. elif len(meta_index) <= IDEAL_SHARD_SIZE * 2:
  812. embedding_size = 60
  813. num_epochs = 5000
  814. elif len(meta_index) <= IDEAL_SHARD_SIZE * 4:
  815. embedding_size = 70
  816. num_epochs = 4000
  817. elif len(meta_index) <= IDEAL_SHARD_SIZE * 10:
  818. embedding_size = 80
  819. num_epochs = 2500
  820. elif len(meta_index) <= IDEAL_SHARD_SIZE * 25:
  821. embedding_size = 100
  822. num_epochs = 500
  823. elif len(meta_index) <= IDEAL_SHARD_SIZE * 100:
  824. embedding_size = 200
  825. num_epochs = 300
  826. else:
  827. embedding_size = 300
  828. num_epochs = 200
  829. swivel.FLAGS.embedding_size = embedding_size
  830. swivel.FLAGS.input_base_path = tmproot
  831. swivel.FLAGS.output_base_path = tmproot
  832. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  833. swivel.FLAGS.num_epochs = num_epochs
  834. # Tensorflow 1.5 parses sys.argv unconditionally *applause*
  835. argv_backup = sys.argv[1:]
  836. del sys.argv[1:]
  837. swivel.main(None)
  838. sys.argv.extend(argv_backup)
  839. print("Reading Swivel embeddings...")
  840. embeddings = []
  841. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  842. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  843. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  844. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  845. assert prow[0] == pcol[0]
  846. erow, ecol = \
  847. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  848. for p in (prow, pcol))
  849. embeddings.append((erow + ecol) / 2)
  850. return meta_index, embeddings
  851. class CORSWebServer(object):
  852. def __init__(self):
  853. self.thread = threading.Thread(target=self.serve)
  854. self.server = None
  855. def serve(self):
  856. outer = self
  857. try:
  858. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  859. except ImportError: # Python 2
  860. from BaseHTTPServer import HTTPServer, test
  861. from SimpleHTTPServer import SimpleHTTPRequestHandler
  862. class ClojureServer(HTTPServer):
  863. def __init__(self, *args, **kwargs):
  864. HTTPServer.__init__(self, *args, **kwargs)
  865. outer.server = self
  866. class CORSRequestHandler(SimpleHTTPRequestHandler):
  867. def end_headers (self):
  868. self.send_header("Access-Control-Allow-Origin", "*")
  869. SimpleHTTPRequestHandler.end_headers(self)
  870. test(CORSRequestHandler, ClojureServer)
  871. def start(self):
  872. self.thread.start()
  873. def stop(self):
  874. if self.running:
  875. self.server.shutdown()
  876. self.thread.join()
  877. @property
  878. def running(self):
  879. return self.server is not None
  880. web_server = CORSWebServer()
  881. def write_embeddings(name, output, run_server, index, embeddings):
  882. print("Writing Tensorflow Projector files...")
  883. if not output:
  884. output = "couples_" + name
  885. if output.endswith(".json"):
  886. output = os.path.join(output[:-5], "couples")
  887. run_server = False
  888. metaf = "%s_%s_meta.tsv" % (output, name)
  889. with open(metaf, "w") as fout:
  890. fout.write("name\tcommits\n")
  891. for pair in index:
  892. fout.write("%s\t%s\n" % pair)
  893. print("Wrote", metaf)
  894. dataf = "%s_%s_data.tsv" % (output, name)
  895. with open(dataf, "w") as fout:
  896. for vec in embeddings:
  897. fout.write("\t".join(str(v) for v in vec))
  898. fout.write("\n")
  899. print("Wrote", dataf)
  900. jsonf = "%s_%s.json" % (output, name)
  901. with open(jsonf, "w") as fout:
  902. fout.write("""{
  903. "embeddings": [
  904. {
  905. "tensorName": "%s %s coupling",
  906. "tensorShape": [%s, %s],
  907. "tensorPath": "http://0.0.0.0:8000/%s",
  908. "metadataPath": "http://0.0.0.0:8000/%s"
  909. }
  910. ]
  911. }
  912. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  913. print("Wrote %s" % jsonf)
  914. if run_server and not web_server.running:
  915. web_server.start()
  916. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  917. print(url)
  918. if run_server:
  919. if shutil.which("xdg-open") is not None:
  920. os.system("xdg-open " + url)
  921. else:
  922. browser = os.getenv("BROWSER", "")
  923. if browser:
  924. os.system(browser + " " + url)
  925. else:
  926. print("\t" + url)
  927. def show_shotness_stats(data):
  928. top = sorted(((r.counters[i], i) for i, r in enumerate(data)), reverse=True)
  929. for count, i in top:
  930. r = data[i]
  931. print("%8d %s:%s [%s]" % (count, r.file, r.name, r.internal_role))
  932. def show_sentiment_stats(args, name, resample, start, data):
  933. import matplotlib
  934. if args.backend:
  935. matplotlib.use(args.backend)
  936. import matplotlib.pyplot as pyplot
  937. start = datetime.fromtimestamp(start)
  938. data = sorted(data.items())
  939. xdates = [start + timedelta(days=d[0]) for d in data]
  940. xpos = []
  941. ypos = []
  942. xneg = []
  943. yneg = []
  944. for x, (_, y) in zip(xdates, data):
  945. y = 0.5 - y.Value
  946. if y > 0:
  947. xpos.append(x)
  948. ypos.append(y)
  949. else:
  950. xneg.append(x)
  951. yneg.append(y)
  952. pyplot.bar(xpos, ypos, color="g", label="Positive")
  953. pyplot.bar(xneg, yneg, color="r", label="Negative")
  954. legend = pyplot.legend(loc=1, fontsize=args.text_size)
  955. pyplot.ylabel("Lines of code")
  956. pyplot.xlabel("Time")
  957. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size, args.size)
  958. pyplot.xlim(xdates[0], xdates[-1])
  959. locator = pyplot.gca().xaxis.get_major_locator()
  960. # set the optimal xticks locator
  961. if "M" not in resample:
  962. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  963. locs = pyplot.gca().get_xticks().tolist()
  964. if len(locs) >= 16:
  965. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  966. locs = pyplot.gca().get_xticks().tolist()
  967. if len(locs) >= 16:
  968. pyplot.gca().xaxis.set_major_locator(locator)
  969. if locs[0] < pyplot.xlim()[0]:
  970. del locs[0]
  971. endindex = -1
  972. if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  973. locs.append(pyplot.xlim()[1])
  974. endindex = len(locs) - 1
  975. startindex = -1
  976. if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  977. locs.append(pyplot.xlim()[0])
  978. startindex = len(locs) - 1
  979. pyplot.gca().set_xticks(locs)
  980. # hacking time!
  981. labels = pyplot.gca().get_xticklabels()
  982. if startindex >= 0:
  983. labels[startindex].set_text(xdates[0].date())
  984. labels[startindex].set_text = lambda _: None
  985. labels[startindex].set_rotation(30)
  986. labels[startindex].set_ha("right")
  987. if endindex >= 0:
  988. labels[endindex].set_text(xdates[-1].date())
  989. labels[endindex].set_text = lambda _: None
  990. labels[endindex].set_rotation(30)
  991. labels[endindex].set_ha("right")
  992. overall_pos = sum(2 * (0.5 - d[1].Value) for d in data if d[1].Value < 0.5)
  993. overall_neg = sum(2 * (d[1].Value - 0.5) for d in data if d[1].Value > 0.5)
  994. title = "%s sentiment +%.1f -%.1f δ=%.1f" % (
  995. name, overall_pos, overall_neg, overall_pos - overall_neg)
  996. deploy_plot(title, args.output, args.style)
  997. def main():
  998. args = parse_args()
  999. reader = read_input(args)
  1000. header = reader.get_header()
  1001. name = reader.get_name()
  1002. burndown_warning = "Burndown stats were not collected. Re-run hercules with --burndown."
  1003. burndown_files_warning = \
  1004. "Burndown stats for files were not collected. Re-run hercules with " \
  1005. "--burndown --burndown-files."
  1006. burndown_people_warning = \
  1007. "Burndown stats for people were not collected. Re-run hercules with " \
  1008. "--burndown --burndown-people."
  1009. couples_warning = "Coupling stats were not collected. Re-run hercules with --couples."
  1010. shotness_warning = "Structural hotness stats were not collected. Re-run hercules with " \
  1011. "--shotness. Also check --languages - the output may be empty."
  1012. sentiment_warning = "Sentiment stats were not collected. Re-run hercules with --sentiment."
  1013. def run_times():
  1014. rt = reader.get_run_times()
  1015. import pandas
  1016. print(pandas.to_timedelta(pandas.Series(rt).sort_values(ascending=False), unit="s"))
  1017. def project_burndown():
  1018. try:
  1019. full_header = header + reader.get_burndown_parameters()
  1020. except KeyError:
  1021. print("project: " + burndown_warning)
  1022. return
  1023. plot_burndown(args, "project",
  1024. *load_burndown(full_header, *reader.get_project_burndown(),
  1025. resample=args.resample))
  1026. def files_burndown():
  1027. try:
  1028. full_header = header + reader.get_burndown_parameters()
  1029. except KeyError:
  1030. print(burndown_warning)
  1031. return
  1032. try:
  1033. plot_many_burndown(args, "file", full_header, reader.get_files_burndown())
  1034. except KeyError:
  1035. print("files: " + burndown_files_warning)
  1036. def people_burndown():
  1037. try:
  1038. full_header = header + reader.get_burndown_parameters()
  1039. except KeyError:
  1040. print(burndown_warning)
  1041. return
  1042. try:
  1043. plot_many_burndown(args, "person", full_header, reader.get_people_burndown())
  1044. except KeyError:
  1045. print("people: " + burndown_people_warning)
  1046. def churn_matrix():
  1047. try:
  1048. plot_churn_matrix(args, name, *load_churn_matrix(
  1049. *reader.get_people_interaction(), max_people=args.max_people))
  1050. except KeyError:
  1051. print("churn_matrix: " + burndown_people_warning)
  1052. def ownership_burndown():
  1053. try:
  1054. full_header = header + reader.get_burndown_parameters()
  1055. except KeyError:
  1056. print(burndown_warning)
  1057. return
  1058. try:
  1059. plot_ownership(args, name, *load_ownership(
  1060. full_header, *reader.get_ownership_burndown(), max_people=args.max_people))
  1061. except KeyError:
  1062. print("ownership: " + burndown_people_warning)
  1063. def couples():
  1064. try:
  1065. write_embeddings("files", args.output, not args.disable_projector,
  1066. *train_embeddings(*reader.get_files_coocc(),
  1067. tmpdir=args.couples_tmp_dir))
  1068. write_embeddings("people", args.output, not args.disable_projector,
  1069. *train_embeddings(*reader.get_people_coocc(),
  1070. tmpdir=args.couples_tmp_dir))
  1071. except KeyError:
  1072. print(couples_warning)
  1073. try:
  1074. write_embeddings("shotness", args.output, not args.disable_projector,
  1075. *train_embeddings(*reader.get_shotness_coocc(),
  1076. tmpdir=args.couples_tmp_dir))
  1077. except KeyError:
  1078. print(shotness_warning)
  1079. def shotness():
  1080. try:
  1081. data = reader.get_shotness()
  1082. except KeyError:
  1083. print(shotness_warning)
  1084. return
  1085. show_shotness_stats(data)
  1086. def sentiment():
  1087. try:
  1088. data = reader.get_sentiment()
  1089. except KeyError:
  1090. print(sentiment_warning)
  1091. return
  1092. show_sentiment_stats(args, reader.get_name(), args.resample, reader.get_header()[0], data)
  1093. if args.mode == "run_times":
  1094. run_times()
  1095. elif args.mode == "project":
  1096. project_burndown()
  1097. elif args.mode == "file":
  1098. files_burndown()
  1099. elif args.mode == "person":
  1100. people_burndown()
  1101. elif args.mode == "churn_matrix":
  1102. churn_matrix()
  1103. elif args.mode == "ownership":
  1104. ownership_burndown()
  1105. elif args.mode == "couples":
  1106. couples()
  1107. elif args.mode == "shotness":
  1108. shotness()
  1109. elif args.mode == "sentiment":
  1110. sentiment()
  1111. elif args.mode == "all":
  1112. project_burndown()
  1113. files_burndown()
  1114. people_burndown()
  1115. churn_matrix()
  1116. ownership_burndown()
  1117. couples()
  1118. shotness()
  1119. sentiment()
  1120. if web_server.running:
  1121. secs = int(os.getenv("COUPLES_SERVER_TIME", "60"))
  1122. print("Sleeping for %d seconds, safe to Ctrl-C" % secs)
  1123. sys.stdout.flush()
  1124. try:
  1125. time.sleep(secs)
  1126. except KeyboardInterrupt:
  1127. pass
  1128. web_server.stop()
  1129. if __name__ == "__main__":
  1130. sys.exit(main())