labours.py 46 KB

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