labours.py 47 KB

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