labours.py 46 KB

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