labours.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import argparse
  2. from datetime import datetime, timedelta
  3. import io
  4. import os
  5. import re
  6. import sys
  7. import tempfile
  8. import threading
  9. import time
  10. import warnings
  11. try:
  12. from clint.textui import progress
  13. except ImportError:
  14. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  15. progress = None
  16. import numpy
  17. import yaml
  18. if sys.version_info[0] < 3:
  19. # OK, ancients, I will support Python 2, but you owe me a beer
  20. input = raw_input
  21. def parse_args():
  22. parser = argparse.ArgumentParser()
  23. parser.add_argument("-o", "--output", default="",
  24. help="Path to the output file/directory (empty for display).")
  25. parser.add_argument("-i", "--input", default="-",
  26. help="Path to the input file (- for stdin).")
  27. parser.add_argument("--text-size", default=12, type=int,
  28. help="Size of the labels and legend.")
  29. parser.add_argument("--backend", help="Matplotlib backend to use.")
  30. parser.add_argument("--style", choices=["black", "white"], default="black",
  31. help="Plot's general color scheme.")
  32. parser.add_argument("--relative", action="store_true",
  33. help="Occupy 100%% height for every measurement.")
  34. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  35. parser.add_argument("-m", "--mode",
  36. choices=["project", "file", "person", "churn_matrix", "people", "couples",
  37. "all"],
  38. default="project", help="What to plot.")
  39. parser.add_argument(
  40. "--resample", default="year",
  41. help="The way to resample the time series. Possible values are: "
  42. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  43. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  44. "#offset-aliases).")
  45. parser.add_argument("--disable-projector", action="store_true",
  46. help="Do not run Tensorflow Projector on couples.")
  47. parser.add_argument("--max-people", default=20, type=int,
  48. help="Maximum number of developers in churn matrix and people plots.")
  49. args = parser.parse_args()
  50. return args
  51. def read_input(args):
  52. sys.stdout.write("Reading the input... ")
  53. sys.stdout.flush()
  54. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  55. try:
  56. loader = yaml.CLoader
  57. except AttributeError:
  58. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  59. loader = yaml.Loader
  60. try:
  61. if args.input != "-":
  62. with open(args.input) as fin:
  63. data = yaml.load(fin, Loader=loader)
  64. else:
  65. data = yaml.load(sys.stdin, Loader=loader)
  66. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  67. print("\nInvalid unicode in the input: %s\nPlease filter it through fix_yaml_unicode.py" %
  68. e)
  69. sys.exit(1)
  70. print("done")
  71. return data["burndown"], data["project"], data.get("files"), data.get("people_sequence"), \
  72. data.get("people"), data.get("people_interaction"), data.get("files_coocc"), \
  73. data.get("people_coocc")
  74. def calculate_average_lifetime(matrix):
  75. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  76. for band in matrix:
  77. start = 0
  78. for i, line in enumerate(band):
  79. if i == 0 or band[i - 1] == 0:
  80. start += 1
  81. continue
  82. lifetimes[i - start] = band[i - 1] - line
  83. lifetimes[i - start] = band[i - 1]
  84. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  85. / (lifetimes.sum() * matrix.shape[1]))
  86. def load_main(header, name, matrix, resample):
  87. import pandas
  88. start = header["begin"]
  89. last = header["end"]
  90. granularity = header["granularity"]
  91. sampling = header["sampling"]
  92. start = datetime.fromtimestamp(int(start))
  93. last = datetime.fromtimestamp(int(last))
  94. granularity = int(granularity)
  95. sampling = int(sampling)
  96. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  97. for line in matrix.split("\n")]).T
  98. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  99. finish = start + timedelta(days=matrix.shape[1] * sampling)
  100. if resample not in ("no", "raw"):
  101. # Interpolate the day x day matrix.
  102. # Each day brings equal weight in the granularity.
  103. # Sampling's interpolation is linear.
  104. daily_matrix = numpy.zeros(
  105. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  106. dtype=numpy.float32)
  107. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  108. for y in range(matrix.shape[0]):
  109. for x in range(matrix.shape[1]):
  110. previous = matrix[y, x - 1] if x > 0 else 0
  111. value = ((previous + (matrix[y, x] - previous) * epsrange)
  112. / granularity)[numpy.newaxis, :]
  113. if (y + 1) * granularity <= x * sampling:
  114. daily_matrix[y * granularity:(y + 1) * granularity,
  115. x * sampling:(x + 1) * sampling] = value
  116. elif y * granularity <= (x + 1) * sampling:
  117. for suby in range(y * granularity, (y + 1) * granularity):
  118. for subx in range(suby, (x + 1) * sampling):
  119. daily_matrix[suby, subx] = matrix[
  120. y, x] / granularity
  121. daily_matrix[(last - start).days:] = 0
  122. # Resample the bands
  123. aliases = {
  124. "year": "A",
  125. "month": "M"
  126. }
  127. resample = aliases.get(resample, resample)
  128. periods = 0
  129. date_granularity_sampling = [start]
  130. while date_granularity_sampling[-1] < finish:
  131. periods += 1
  132. date_granularity_sampling = pandas.date_range(
  133. start, periods=periods, freq=resample)
  134. date_range_sampling = pandas.date_range(
  135. date_granularity_sampling[0],
  136. periods=(finish - date_granularity_sampling[0]).days,
  137. freq="1D")
  138. # Fill the new square matrix
  139. matrix = numpy.zeros(
  140. (len(date_granularity_sampling), len(date_range_sampling)),
  141. dtype=numpy.float32)
  142. for i, gdt in enumerate(date_granularity_sampling):
  143. istart = (date_granularity_sampling[i - 1] - start).days \
  144. if i > 0 else 0
  145. ifinish = (gdt - start).days
  146. for j, sdt in enumerate(date_range_sampling):
  147. if (sdt - start).days >= istart:
  148. break
  149. matrix[i, j:] = \
  150. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  151. # Hardcode some cases to improve labels" readability
  152. if resample in ("year", "A"):
  153. labels = [dt.year for dt in date_granularity_sampling]
  154. elif resample in ("month", "M"):
  155. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  156. else:
  157. labels = [dt.date() for dt in date_granularity_sampling]
  158. else:
  159. labels = [
  160. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  161. (
  162. start + timedelta(days=(i + 1) * granularity)).date())
  163. for i in range(matrix.shape[0])]
  164. if len(labels) > 18:
  165. warnings.warn("Too many labels - consider resampling.")
  166. resample = "M" # fake resampling type is checked while plotting
  167. date_range_sampling = pandas.date_range(
  168. start + timedelta(days=sampling), periods=matrix.shape[1],
  169. freq="%dD" % sampling)
  170. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  171. def load_churn_matrix(contents):
  172. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  173. for line in contents.split("\n")])
  174. return matrix
  175. def load_people(header, sequence, contents):
  176. import pandas
  177. start = header["begin"]
  178. last = header["end"]
  179. sampling = header["sampling"]
  180. start = datetime.fromtimestamp(int(start))
  181. last = datetime.fromtimestamp(int(last))
  182. sampling = int(sampling)
  183. people = []
  184. for name in sequence:
  185. people.append(numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  186. for line in contents[name].split("\n")]).sum(axis=1))
  187. people = numpy.array(people)
  188. date_range_sampling = pandas.date_range(
  189. start + timedelta(days=sampling), periods=people[0].shape[0],
  190. freq="%dD" % sampling)
  191. return sequence, people, date_range_sampling, last
  192. def apply_plot_style(figure, axes, legend, style, text_size):
  193. figure.set_size_inches(12, 9)
  194. for side in ("bottom", "top", "left", "right"):
  195. axes.spines[side].set_color(style)
  196. for axis in (axes.xaxis, axes.yaxis):
  197. axis.label.update(dict(fontsize=text_size, color=style))
  198. for axis in ("x", "y"):
  199. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  200. if legend is not None:
  201. frame = legend.get_frame()
  202. for setter in (frame.set_facecolor, frame.set_edgecolor):
  203. setter("black" if style == "white" else "white")
  204. for text in legend.get_texts():
  205. text.set_color(style)
  206. def get_plot_path(base, name):
  207. root, ext = os.path.splitext(base)
  208. if not ext:
  209. ext = ".png"
  210. output = os.path.join(root, name + ext)
  211. os.makedirs(os.path.dirname(output), exist_ok=True)
  212. return output
  213. def deploy_plot(title, output, style):
  214. import matplotlib.pyplot as pyplot
  215. if not output:
  216. pyplot.gcf().canvas.set_window_title(title)
  217. pyplot.show()
  218. else:
  219. if title:
  220. pyplot.title(title, color=style)
  221. try:
  222. pyplot.tight_layout()
  223. except:
  224. print("Warning: failed to set the tight layout")
  225. pyplot.savefig(output, transparent=True)
  226. pyplot.clf()
  227. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  228. sampling, resample):
  229. import matplotlib
  230. if args.backend:
  231. matplotlib.use(args.backend)
  232. import matplotlib.pyplot as pyplot
  233. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  234. if args.relative:
  235. for i in range(matrix.shape[1]):
  236. matrix[:, i] /= matrix[:, i].sum()
  237. pyplot.ylim(0, 1)
  238. legend_loc = 3
  239. else:
  240. legend_loc = 2
  241. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  242. pyplot.ylabel("Lines of code")
  243. pyplot.xlabel("Time")
  244. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  245. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  246. locator = pyplot.gca().xaxis.get_major_locator()
  247. # set the optimal xticks locator
  248. if "M" not in resample:
  249. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  250. locs = pyplot.gca().get_xticks().tolist()
  251. if len(locs) >= 16:
  252. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  253. locs = pyplot.gca().get_xticks().tolist()
  254. if len(locs) >= 16:
  255. pyplot.gca().xaxis.set_major_locator(locator)
  256. if locs[0] < pyplot.xlim()[0]:
  257. del locs[0]
  258. endindex = -1
  259. if len(locs) >= 2 and \
  260. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  261. locs.append(pyplot.xlim()[1])
  262. endindex = len(locs) - 1
  263. startindex = -1
  264. if len(locs) >= 2 and \
  265. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  266. locs.append(pyplot.xlim()[0])
  267. startindex = len(locs) - 1
  268. pyplot.gca().set_xticks(locs)
  269. # hacking time!
  270. labels = pyplot.gca().get_xticklabels()
  271. if startindex >= 0:
  272. labels[startindex].set_text(date_range_sampling[0].date())
  273. labels[startindex].set_text = lambda _: None
  274. labels[startindex].set_rotation(30)
  275. labels[startindex].set_ha("right")
  276. if endindex >= 0:
  277. labels[endindex].set_text(date_range_sampling[-1].date())
  278. labels[endindex].set_text = lambda _: None
  279. labels[endindex].set_rotation(30)
  280. labels[endindex].set_ha("right")
  281. title = "%s %d x %d (granularity %d, sampling %d)" % \
  282. ((name,) + matrix.shape + (granularity, sampling))
  283. output = args.output
  284. if output:
  285. if args.mode == "project" and target == "project":
  286. output = args.output
  287. else:
  288. if target == "project":
  289. name = "project"
  290. output = get_plot_path(args.output, name)
  291. deploy_plot(title, output, args.style)
  292. def plot_many(args, target, header, parts):
  293. if not args.output:
  294. print("Warning: output not set, showing %d plots." % len(parts))
  295. itercnt = progress.bar(parts.items(), expected_size=len(parts)) \
  296. if progress is not None else parts.items()
  297. stdout = io.StringIO()
  298. for name, matrix in itercnt:
  299. backup = sys.stdout
  300. sys.stdout = stdout
  301. plot_burndown(args, target, *load_main(header, name, matrix, args.resample))
  302. sys.stdout = backup
  303. sys.stdout.write(stdout.getvalue())
  304. def plot_churn_matrix(args, repo, people, matrix):
  305. matrix = matrix.astype(float)
  306. if matrix.shape[0] > args.max_people:
  307. order = numpy.argsort(-matrix[:, 0])
  308. matrix = matrix[order[:args.max_people]][:, [0, 1] + list(2 + order[:args.max_people])]
  309. people = [people[i] for i in order[:args.max_people]]
  310. print("Warning: truncated people to most productive %d" % args.max_people)
  311. zeros = matrix[:, 0] == 0
  312. matrix[zeros, :] = 1
  313. matrix /= matrix[:, 0][:, None]
  314. matrix = -matrix[:, 1:]
  315. matrix[zeros, :] = 0
  316. for i, name in enumerate(people):
  317. if len(name) > 40:
  318. people[i] = name[:37] + "..."
  319. import matplotlib
  320. if args.backend:
  321. matplotlib.use(args.backend)
  322. import matplotlib.pyplot as pyplot
  323. s = 4 + matrix.shape[1] * 0.3
  324. fig = pyplot.figure(figsize=(s, s))
  325. ax = fig.add_subplot(111)
  326. ax.xaxis.set_label_position("top")
  327. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  328. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  329. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  330. ax.set_xticklabels(["Unidentified"] + people, rotation=90, ha="center")
  331. ax.set_yticklabels(people, va="center")
  332. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  333. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  334. ax.grid(which="minor")
  335. apply_plot_style(fig, ax, None, args.style, args.text_size)
  336. if not args.output:
  337. pos1 = ax.get_position()
  338. pos2 = (pos1.x0 + 0.245, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  339. ax.set_position(pos2)
  340. if args.mode == "all":
  341. output = get_plot_path(args.output, "matrix")
  342. else:
  343. output = args.output
  344. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  345. if args.output:
  346. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  347. title = ""
  348. deploy_plot(title, output, args.style)
  349. def plot_people(args, repo, names, people, date_range, last):
  350. import matplotlib
  351. if args.backend:
  352. matplotlib.use(args.backend)
  353. import matplotlib.pyplot as pyplot
  354. if people.shape[0] > args.max_people:
  355. order = numpy.argsort(-people.sum(axis=1))
  356. people = people[order[:args.max_people]]
  357. names = [names[i] for i in order[:args.max_people]]
  358. print("Warning: truncated people to most owning %d" % args.max_people)
  359. for i, name in enumerate(names):
  360. if len(name) > 40:
  361. names[i] = name[:37] + "..."
  362. pyplot.stackplot(date_range, people, labels=names)
  363. pyplot.xlim(date_range[0], last)
  364. if args.relative:
  365. for i in range(people.shape[1]):
  366. people[:, i] /= people[:, i].sum()
  367. pyplot.ylim(0, 1)
  368. legend_loc = 3
  369. else:
  370. legend_loc = 2
  371. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  372. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  373. if args.mode == "all":
  374. output = get_plot_path(args.output, "people")
  375. else:
  376. output = args.output
  377. deploy_plot("%s code ratio through time" % repo, output, args.style)
  378. def train_embeddings(coocc_tree, tmpdir, shard_size=4096):
  379. from scipy.sparse import csr_matrix
  380. try:
  381. from . import swivel
  382. except SystemError:
  383. import swivel
  384. index = coocc_tree["index"]
  385. nshards = len(index) // shard_size
  386. if nshards * shard_size < len(index):
  387. nshards += 1
  388. shard_size = len(index) // nshards
  389. nshards = len(index) // shard_size
  390. remainder = len(index) - nshards * shard_size
  391. if remainder > 0:
  392. lengths = numpy.array([len(cd) for cd in coocc_tree["matrix"]])
  393. filtered = sorted(numpy.argsort(lengths)[remainder:])
  394. else:
  395. filtered = list(range(len(index)))
  396. print("Reading the sparse matrix...")
  397. data = []
  398. indices = []
  399. indptr = [0]
  400. for row, cd in enumerate(coocc_tree["matrix"]):
  401. if row >= len(index):
  402. break
  403. for col, val in sorted(cd.items()):
  404. data.append(val)
  405. indices.append(col)
  406. indptr.append(indptr[-1] + len(cd))
  407. matrix = csr_matrix((data, indices, indptr), shape=(len(index), len(index)))
  408. if len(filtered) < len(index):
  409. matrix = matrix[filtered, :][:, filtered]
  410. meta_index = []
  411. for i, j in enumerate(filtered):
  412. meta_index.append((index[j], matrix[i, i]))
  413. index = [mi[0] for mi in meta_index]
  414. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  415. print("Writing Swivel metadata...")
  416. vocabulary = "\n".join(index)
  417. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  418. out.write(vocabulary)
  419. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  420. out.write(vocabulary)
  421. del vocabulary
  422. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  423. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  424. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  425. out.write(bool_sums_str)
  426. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  427. out.write(bool_sums_str)
  428. del bool_sums_str
  429. reorder = numpy.argsort(-bool_sums)
  430. print("Writing Swivel shards...")
  431. for row in range(nshards):
  432. for col in range(nshards):
  433. def _int64s(xs):
  434. return tf.train.Feature(
  435. int64_list=tf.train.Int64List(value=list(xs)))
  436. def _floats(xs):
  437. return tf.train.Feature(
  438. float_list=tf.train.FloatList(value=list(xs)))
  439. indices_row = reorder[row::nshards]
  440. indices_col = reorder[col::nshards]
  441. shard = matrix[indices_row][:, indices_col].tocoo()
  442. example = tf.train.Example(features=tf.train.Features(feature={
  443. "global_row": _int64s(indices_row),
  444. "global_col": _int64s(indices_col),
  445. "sparse_local_row": _int64s(shard.row),
  446. "sparse_local_col": _int64s(shard.col),
  447. "sparse_value": _floats(shard.data)}))
  448. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  449. out.write(example.SerializeToString())
  450. print("Training Swivel model...")
  451. swivel.FLAGS.submatrix_rows = shard_size
  452. swivel.FLAGS.submatrix_cols = shard_size
  453. if len(meta_index) < 10000:
  454. embedding_size = 50
  455. num_epochs = 200
  456. elif len(meta_index) < 100000:
  457. embedding_size = 100
  458. num_epochs = 250
  459. elif len(meta_index) < 500000:
  460. embedding_size = 200
  461. num_epochs = 300
  462. else:
  463. embedding_size = 300
  464. num_epochs = 200
  465. swivel.FLAGS.embedding_size = embedding_size
  466. swivel.FLAGS.input_base_path = tmproot
  467. swivel.FLAGS.output_base_path = tmproot
  468. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  469. swivel.FLAGS.num_epochs = num_epochs
  470. swivel.main(None)
  471. print("Reading Swivel embeddings...")
  472. embeddings = []
  473. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  474. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  475. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  476. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  477. assert prow[0] == pcol[0]
  478. erow, ecol = \
  479. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  480. for p in (prow, pcol))
  481. embeddings.append((erow + ecol) / 2)
  482. return meta_index, embeddings
  483. class CORSWebServer(object):
  484. def __init__(self):
  485. self.thread = threading.Thread(target=self.serve)
  486. self.server = None
  487. def serve(self):
  488. outer = self
  489. try:
  490. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  491. except ImportError: # Python 2
  492. from BaseHTTPServer import HTTPServer, test
  493. from SimpleHTTPServer import SimpleHTTPRequestHandler
  494. class ClojureServer(HTTPServer):
  495. def __init__(self, *args, **kwargs):
  496. HTTPServer.__init__(self, *args, **kwargs)
  497. outer.server = self
  498. class CORSRequestHandler(SimpleHTTPRequestHandler):
  499. def end_headers (self):
  500. self.send_header("Access-Control-Allow-Origin", "*")
  501. SimpleHTTPRequestHandler.end_headers(self)
  502. test(CORSRequestHandler, ClojureServer)
  503. def start(self):
  504. self.thread.start()
  505. def stop(self):
  506. if self.running:
  507. self.server.shutdown()
  508. self.thread.join()
  509. @property
  510. def running(self):
  511. return self.server is not None
  512. web_server = CORSWebServer()
  513. def write_embeddings(name, output, run_server, index, embeddings):
  514. print("Writing Tensorflow Projector files...")
  515. if not output:
  516. output = "couples_" + name
  517. metaf = "%s_%s_meta.tsv" % (output, name)
  518. with open(metaf, "w") as fout:
  519. fout.write("name\tcommits\n")
  520. for pair in index:
  521. fout.write("%s\t%s\n" % pair)
  522. print("Wrote", metaf)
  523. dataf = "%s_%s_data.tsv" % (output, name)
  524. with open(dataf, "w") as fout:
  525. for vec in embeddings:
  526. fout.write("\t".join(str(v) for v in vec))
  527. fout.write("\n")
  528. print("Wrote", dataf)
  529. jsonf = "%s_%s.json" % (output, name)
  530. with open(jsonf, "w") as fout:
  531. fout.write("""{
  532. "embeddings": [
  533. {
  534. "tensorName": "%s %s coupling",
  535. "tensorShape": [%s, %s],
  536. "tensorPath": "http://0.0.0.0:8000/%s",
  537. "metadataPath": "http://0.0.0.0:8000/%s"
  538. }
  539. ]
  540. }
  541. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  542. print("Wrote %s", jsonf)
  543. if run_server and not web_server.running:
  544. web_server.start()
  545. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  546. print(url)
  547. if run_server:
  548. os.system("xdg-open " + url)
  549. def main():
  550. args = parse_args()
  551. header, main_contents, files_contents, people_sequence, people_contents, people_matrix, \
  552. files_coocc, people_coocc = read_input(args)
  553. name = next(iter(main_contents))
  554. files_warning = "Files stats were not collected. Re-run hercules with -files."
  555. people_warning = "People stats were not collected. Re-run hercules with -people."
  556. couples_warning = "Coupling stats were not collected. Re-run hercules with -couples."
  557. if args.mode == "project":
  558. plot_burndown(args, "project",
  559. *load_main(header, name, main_contents[name], args.resample))
  560. elif args.mode == "file":
  561. if not files_contents:
  562. print(files_warning)
  563. return
  564. plot_many(args, "file", header, files_contents)
  565. elif args.mode == "person":
  566. if not people_contents:
  567. print(people_warning)
  568. return
  569. plot_many(args, "person", header, people_contents)
  570. elif args.mode == "churn_matrix":
  571. if not people_contents:
  572. print(people_warning)
  573. return
  574. plot_churn_matrix(args, name, people_sequence, load_churn_matrix(people_matrix))
  575. elif args.mode == "people":
  576. if not people_contents:
  577. print(people_warning)
  578. return
  579. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  580. elif args.mode == "couples":
  581. if not files_coocc or not people_coocc:
  582. print(couples_warning)
  583. return
  584. write_embeddings("files", args.output, not args.disable_projector,
  585. *train_embeddings(files_coocc, args.couples_tmp_dir))
  586. write_embeddings("people", args.output, not args.disable_projector,
  587. *train_embeddings(people_coocc, args.couples_tmp_dir))
  588. elif args.mode == "all":
  589. plot_burndown(args, "project",
  590. *load_main(header, name, main_contents[name], args.resample))
  591. if files_contents:
  592. plot_many(args, "file", header, files_contents)
  593. if people_contents:
  594. plot_many(args, "person", header, people_contents)
  595. plot_churn_matrix(args, name, people_sequence, load_churn_matrix(people_matrix))
  596. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  597. if people_coocc:
  598. if not files_coocc or not people_coocc:
  599. print(couples_warning)
  600. return
  601. write_embeddings("files", args.output, not args.disable_projector,
  602. *train_embeddings(files_coocc, args.couples_tmp_dir))
  603. write_embeddings("people", args.output, not args.disable_projector,
  604. *train_embeddings(people_coocc, args.couples_tmp_dir))
  605. if web_server.running:
  606. print("Sleeping for 60 seconds, safe to Ctrl-C")
  607. try:
  608. time.sleep(60)
  609. except KeyboardInterrupt:
  610. pass
  611. web_server.stop()
  612. if __name__ == "__main__":
  613. sys.exit(main())