labours.py 46 KB

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