labours.py 25 KB

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