atcoder-standings-difficulty-analyzer

順位表の得点情報を集計し,推定 difficulty やその推移を表示します.

目前為 2021-04-30 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name atcoder-standings-difficulty-analyzer
  3. // @namespace iilj
  4. // @version 2021.4.30.1
  5. // @description 順位表の得点情報を集計し,推定 difficulty やその推移を表示します.
  6. // @author iilj
  7. // @supportURL https://github.com/iilj/atcoder-standings-difficulty-analyzer/issues
  8. // @match https://atcoder.jp/*standings*
  9. // @exclude https://atcoder.jp/*standings/json
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly.min.js
  11. // @resource loaders.min.css https://cdnjs.cloudflare.com/ajax/libs/loaders.css/0.1.2/loaders.min.css
  12. // @grant GM_getResourceText
  13. // @grant GM_addStyle
  14. // ==/UserScript==
  15.  
  16. /**
  17. * 問題ごとの結果エントリ
  18. * @typedef {Object} TaskResultEntry
  19. * @property {any} Additional 謎
  20. * @property {number} Count 提出回数
  21. * @property {number} Elapsed コンテスト開始からの経過時間 [ns].
  22. * @property {number} Failure 非 AC の提出数(ACするまではペナルティではない).
  23. * @property {boolean} Frozen アカウントが凍結済みかどうか?
  24. * @property {number} Penalty ペナルティ数
  25. * @property {boolean} Pending ジャッジ中かどうか?
  26. * @property {number} Score 得点(×100)
  27. * @property {number} Status 1 のとき満点? 6 のとき部分点?
  28. */
  29.  
  30. /**
  31. * 全問題の結果
  32. * @typedef {Object} TotalResultEntry
  33. * @property {number} Accepted 正解した問題数
  34. * @property {any} Additional 謎
  35. * @property {number} Count 提出回数
  36. * @property {number} Elapsed コンテスト開始からの経過時間 [ns].
  37. * @property {boolean} Frozen アカウントが凍結済みかどうか?
  38. * @property {number} Penalty ペナルティ数
  39. * @property {number} Score 得点(×100)
  40. */
  41.  
  42. /**
  43. * 順位表エントリ
  44. * @typedef {Object} StandingsEntry
  45. * @property {any} Additional 謎
  46. * @property {string} Affiliation 所属.IsTeam = true のときは,チームメンバを「, 」で結合した文字列.
  47. * @property {number} AtCoderRank AtCoder 内順位
  48. * @property {number} Competitions Rated コンテスト参加回数
  49. * @property {string} Country 国ラベル."JP" など.
  50. * @property {string} DisplayName 表示名."hitonanode" など.
  51. * @property {number} EntireRank コンテスト順位?
  52. * @property {boolean} IsRated Rated かどうか
  53. * @property {boolean} IsTeam チームかどうか
  54. * @property {number} OldRating コンテスト前のレーティング.コンテスト後のみ有効.
  55. * @property {number} Rank コンテスト順位?
  56. * @property {number} Rating コンテスト後のレーティング
  57. * @property {{[key: string]: TaskResultEntry}} TaskResults 問題ごとの結果.参加登録していない人は空.
  58. * @property {TotalResultEntry} TotalResult 全体の結果
  59. * @property {boolean} UserIsDeleted ユーザアカウントが削除済みかどうか
  60. * @property {string} UserName ユーザ名."hitonanode" など.
  61. * @property {string} UserScreenName ユーザの表示名."hitonanode" など.
  62. */
  63.  
  64. /**
  65. * 問題エントリ
  66. * @typedef {Object} TaskInfoEntry
  67. * @property {string} Assignment 問題ラベル."A" など.
  68. * @property {string} TaskName 問題名.
  69. * @property {string} TaskScreenName 問題の slug. "abc185_a" など.
  70. */
  71.  
  72. /**
  73. * 順位表情報
  74. * @typedef {Object} Standings
  75. * @property {any} AdditionalColumns 謎
  76. * @property {boolean} Fixed 謎
  77. * @property {StandingsEntry[]} StandingsData 順位表データ
  78. * @property {TaskInfoEntry[]} TaskInfo 問題データ
  79. */
  80.  
  81. /* globals vueStandings, $, contestScreenName, startTime, endTime, userScreenName, Plotly */
  82.  
  83. (() => {
  84. 'use strict';
  85.  
  86. // loader のスタイル設定
  87. const loaderStyles = GM_getResourceText("loaders.min.css");
  88. const loaderWrapperStyles = `
  89. .acssa-table {
  90. width: 100%;
  91. table-layout: fixed;
  92. margin-bottom: 1.5rem;
  93. }
  94. .acssa-thead {
  95. font-weight: bold;
  96. }
  97. .acssa-loader-wrapper {
  98. background-color: #337ab7;
  99. display: flex;
  100. justify-content: center;
  101. align-items: center;
  102. padding: 1rem;
  103. margin-bottom: 1.5rem;
  104. border-radius: 3px;
  105. }
  106. #acssa-tab-wrapper {
  107. display: none;
  108. }
  109. #acssa-chart-tab, #acssa-checkbox-tab {
  110. margin-bottom: 0.5rem;
  111. display: inline-block;
  112. }
  113. #acssa-chart-tab a, #acssa-checkbox-tab label, #acssa-checkbox-tab label input {
  114. cursor: pointer;
  115. }
  116. #acssa-chart-tab span.glyphicon {
  117. margin-right: 0.5rem;
  118. }
  119. #acssa-checkbox-tab label, #acssa-checkbox-tab input {
  120. margin: 0;
  121. }
  122. #acssa-checkbox-tab li a {
  123. color: black;
  124. }
  125. #acssa-checkbox-tab li a:hover {
  126. background-color: transparent;
  127. }
  128. .acssa-chart-wrapper {
  129. display: none;
  130. }
  131. .acssa-chart-wrapper.acssa-chart-wrapper-active {
  132. display: block;
  133. }
  134. .table>tbody>tr>td.success.acssa-task-success.acssa-task-success-suppress {
  135. background-color: transparent;
  136. }
  137. #acssa-checkbox-toggle-log-plot-parent {
  138. display: none;
  139. }
  140. `;
  141. GM_addStyle(loaderStyles + loaderWrapperStyles);
  142.  
  143. class RatingConverter {
  144. /** 表示用の低レート帯補正レート → 低レート帯補正前のレート
  145. * @type {(correctedRating: number) => number} */
  146. static toRealRating = (correctedRating) => {
  147. if (correctedRating >= 400) return correctedRating;
  148. else return 400 * (1 - Math.log(400 / correctedRating));
  149. };
  150.  
  151. /** 低レート帯補正前のレート → 内部レート推定値
  152. * @type {(correctedRating: number) => number} */
  153. static toInnerRating = (realRating, comp) => {
  154. return realRating + 1200 * (Math.sqrt(1 - Math.pow(0.81, comp)) / (1 - Math.pow(0.9, comp)) - 1) / (Math.sqrt(19) - 1);
  155. };
  156.  
  157. /** 低レート帯補正前のレート → 表示用の低レート帯補正レート
  158. * @type {(correctedRating: number) => number} */
  159. static toCorrectedRating = (realRating) => {
  160. if (realRating >= 400) return realRating;
  161. else return Math.floor(400 / Math.exp((400 - realRating) / 400));
  162. };
  163. }
  164.  
  165. class DifficultyCalculator {
  166. /** @constructor
  167. * @type {(sortedInnerRatings: number[]) => DifficultyCalculator}
  168. */
  169. constructor(sortedInnerRatings) {
  170. this.innerRatings = sortedInnerRatings;
  171. /** @type {Map<number, number>} */
  172. this.prepared = new Map();
  173. /** @type {Map<number, number>} */
  174. this.memo = new Map();
  175. }
  176.  
  177. perf2ExpectedAcceptedCount = (m) => {
  178. let expectedAcceptedCount;
  179. if (this.prepared.has(m)) {
  180. expectedAcceptedCount = this.prepared.get(m);
  181. } else {
  182. expectedAcceptedCount = this.innerRatings.reduce((prev_expected_accepts, innerRating) =>
  183. prev_expected_accepts += 1 / (1 + Math.pow(6, (m - innerRating) / 400)), 0);
  184. this.prepared.set(m, expectedAcceptedCount);
  185. }
  186. return expectedAcceptedCount;
  187. };
  188.  
  189. perf2Ranking = (x) => this.perf2ExpectedAcceptedCount(x) + 0.5;
  190.  
  191. /** Difficulty 推定値を算出する
  192. * @type {((acceptedCount: number) => number)} */
  193. binarySearch = (acceptedCount) => {
  194. if (this.memo.has(acceptedCount)) {
  195. return this.memo.get(acceptedCount);
  196. }
  197. let lb = -10000;
  198. let ub = 10000;
  199. while (ub - lb > 1) {
  200. const m = Math.floor((ub + lb) / 2);
  201. const expectedAcceptedCount = this.perf2ExpectedAcceptedCount(m);
  202.  
  203. if (expectedAcceptedCount < acceptedCount) ub = m;
  204. else lb = m;
  205. }
  206. const difficulty = lb
  207. const correctedDifficulty = RatingConverter.toCorrectedRating(difficulty);
  208. this.memo.set(acceptedCount, correctedDifficulty);
  209. return correctedDifficulty;
  210. };
  211. }
  212.  
  213. /** @type {(ar: number[], n: number) => number} */
  214. const arrayLowerBound = (arr, n) => {
  215. let first = 0, last = arr.length - 1, middle;
  216. while (first <= last) {
  217. middle = 0 | (first + last) / 2;
  218. if (arr[middle] < n) first = middle + 1;
  219. else last = middle - 1;
  220. }
  221. return first;
  222. };
  223.  
  224. /** @type {(rating: number) => string} */
  225. const getColor = (rating) => {
  226. if (rating < 400) return '#808080'; // gray
  227. else if (rating < 800) return '#804000'; // brown
  228. else if (rating < 1200) return '#008000'; // green
  229. else if (rating < 1600) return '#00C0C0'; // cyan
  230. else if (rating < 2000) return '#0000FF'; // blue
  231. else if (rating < 2400) return '#C0C000'; // yellow
  232. else if (rating < 2800) return '#FF8000'; // orange
  233. else if (rating == 9999) return '#000000';
  234. return '#FF0000'; // red
  235. };
  236.  
  237. /** レートを表す難易度円(◒)の HTML 文字列を生成
  238. * @type {(rating: number, isSmall?: boolean) => string} */
  239. const generateDifficultyCircle = (rating, isSmall = true) => {
  240. const size = (isSmall ? 12 : 36);
  241. const borderWidth = (isSmall ? 1 : 3);
  242.  
  243. const style = `display:inline-block;border-radius:50%;border-style:solid;border-width:${borderWidth}px;`
  244. + `margin-right:5px;vertical-align:initial;height:${size}px;width:${size}px;`;
  245.  
  246. if (rating < 3200) {
  247. // 色と円がどのぐらい満ちているかを計算
  248. const color = getColor(rating);
  249. const percentFull = (rating % 400) / 400 * 100;
  250.  
  251. // ◒を生成
  252. return `
  253. <span style='${style}border-color:${color};background:`
  254. + `linear-gradient(to top, ${color} 0%, ${color} ${percentFull}%, `
  255. + `rgba(0, 0, 0, 0) ${percentFull}%, rgba(0, 0, 0, 0) 100%); '>
  256. </span>`;
  257.  
  258. }
  259. // 金銀銅は例外処理
  260. else if (rating < 3600) {
  261. return `<span style="${style}border-color: rgb(150, 92, 44);`
  262. + 'background: linear-gradient(to right, rgb(150, 92, 44), rgb(255, 218, 189), rgb(150, 92, 44));"></span>';
  263. } else if (rating < 4000) {
  264. return `<span style="${style}border-color: rgb(128, 128, 128);`
  265. + 'background: linear-gradient(to right, rgb(128, 128, 128), white, rgb(128, 128, 128));"></span>';
  266. } else {
  267. return `<span style="${style}border-color: rgb(255, 215, 0);`
  268. + 'background: linear-gradient(to right, rgb(255, 215, 0), white, rgb(255, 215, 0));"></span>';
  269. }
  270. }
  271.  
  272. /** @type {(sec: number) => string} */
  273. const formatTimespan = (sec) => {
  274. let sign;
  275. if (sec >= 0) {
  276. sign = "";
  277. } else {
  278. sign = "-";
  279. sec *= -1;
  280. }
  281. return `${sign}${Math.floor(sec / 60)}:${`0${sec % 60}`.slice(-2)}`;
  282. };
  283.  
  284. /** 現在のページから,コンテストの開始から終了までの秒数を抽出する
  285. * @type {() => number}
  286. */
  287. const getContestDurationSec = () => {
  288. if (contestScreenName.startsWith("past")) {
  289. return 300 * 60;
  290. }
  291. return (endTime - startTime) / 1000;
  292. };
  293.  
  294. /** @type {(contestScreenName: string) => number} */
  295. const getCenterOfInnerRating = (contestScreenName) => {
  296. if (contestScreenName.startsWith("agc")) {
  297. const contestNumber = Number(contestScreenName.substring(3, 6));
  298. return (contestNumber >= 34) ? 1200 : 1600;
  299. }
  300. if (contestScreenName.startsWith("arc")) {
  301. const contestNumber = Number(contestScreenName.substring(3, 6));
  302. return (contestNumber >= 104) ? 1000 : 1600;
  303. }
  304. return 800;
  305. };
  306. const centerOfInnerRating = getCenterOfInnerRating(contestScreenName);
  307.  
  308. let working = false;
  309. let oldStandingsData = null;
  310.  
  311. /** 順位表更新時の処理:テーブル追加
  312. * @type {(v: Standings) => void} */
  313. const onStandingsChanged = async (standings) => {
  314. if (!standings) return;
  315. if (working) return;
  316.  
  317. const tasks = standings.TaskInfo;
  318. const standingsData = standings.StandingsData; // vueStandings.filteredStandings;
  319.  
  320. if (oldStandingsData === standingsData) return;
  321. oldStandingsData = standingsData;
  322. working = true;
  323. // console.log(standings);
  324.  
  325. { // remove old contents
  326. const oldContents = document.getElementById("acssa-contents");
  327. if (oldContents) {
  328. // oldContents.parentNode.removeChild(oldContents);
  329. oldContents.remove();
  330. }
  331. }
  332.  
  333. /** 問題ごとの最終 AC 時刻リスト.
  334. * @type {Map<number, number[]>} */
  335. const scoreLastAcceptedTimeMap = new Map();
  336.  
  337. // コンテスト中かどうか判別する
  338. let isDuringContest = true;
  339. for (let i = 0; i < standingsData.length; ++i) {
  340. const standingsEntry = standingsData[i];
  341. if (standingsEntry.OldRating > 0) {
  342. isDuringContest = false;
  343. break;
  344. }
  345. }
  346.  
  347. /** 各問題の正答者数.
  348. * @type {number[]} */
  349. const taskAcceptedCounts = Array(tasks.length);
  350. taskAcceptedCounts.fill(0);
  351.  
  352. /** 各問題の正答時間リスト.秒単位で格納する.
  353. * @type {number[][]} */
  354. const taskAcceptedElapsedTimes = [...Array(tasks.length)].map((_, i) => []);
  355. // taskAcceptedElapsedTimes.fill([]); // これだと同じインスタンスで埋めてしまう
  356.  
  357. /** 内部レートのリスト.
  358. * @type {number[]} */
  359. const innerRatings = [];
  360.  
  361. const NS2SEC = 1000000000;
  362.  
  363. /** @type {{[key: string]: number}} */
  364. const innerRatingsFromPredictor = await (async () => {
  365. try {
  366. const res = await fetch(`https://data.ac-predictor.com/aperfs/${contestScreenName}.json`);
  367. if (res.ok) return await res.json();
  368. } catch (e) {
  369. console.warn(e);
  370. }
  371. return {};
  372. })();
  373.  
  374. /** 現在のユーザの各問題の AC 時刻.
  375. * @type {number[]} */
  376. const yourTaskAcceptedElapsedTimes = Array(tasks.length);
  377. yourTaskAcceptedElapsedTimes.fill(-1);
  378. /** 現在のユーザのスコア */
  379. let yourScore = -1;
  380. /** 現在のユーザの最終 AC 時刻 */
  381. let yourLastAcceptedTime = -1;
  382.  
  383. // 順位表情報を走査する(内部レートのリストと正答時間リストを構築する)
  384. let participants = 0;
  385. for (let i = 0; i < standingsData.length; ++i) {
  386. const standingsEntry = standingsData[i];
  387.  
  388. if (!standingsEntry.TaskResults) continue; // 参加登録していない
  389. if (standingsEntry.UserIsDeleted) continue; // アカウント削除
  390. let correctedRating = isDuringContest ? standingsEntry.Rating : standingsEntry.OldRating;
  391. const isTeamOrBeginner = (correctedRating === 0);
  392. if (isTeamOrBeginner) {
  393. // continue; // 初参加 or チーム
  394. correctedRating = centerOfInnerRating;
  395. }
  396.  
  397. // これは飛ばしちゃダメ(提出しても 0 AC だと Penalty == 0 なので)
  398. // if (standingsEntry.TotalResult.Score == 0 && standingsEntry.TotalResult.Penalty == 0) continue;
  399.  
  400. let score = 0;
  401. let penalty = 0;
  402. for (let j = 0; j < tasks.length; ++j) {
  403. const taskResultEntry = standingsEntry.TaskResults[tasks[j].TaskScreenName];
  404. if (!taskResultEntry) continue; // 未提出
  405. score += taskResultEntry.Score;
  406. penalty += (taskResultEntry.Score === 0 ? taskResultEntry.Failure : taskResultEntry.Penalty);
  407. }
  408. if (score === 0 && penalty === 0) continue; // NoSub を飛ばす
  409. participants++;
  410. // console.log(i + 1, score, penalty);
  411.  
  412. score /= 100;
  413. if (scoreLastAcceptedTimeMap.has(score)) {
  414. scoreLastAcceptedTimeMap.get(score).push(standingsEntry.TotalResult.Elapsed / NS2SEC)
  415. } else {
  416. scoreLastAcceptedTimeMap.set(score, [standingsEntry.TotalResult.Elapsed / NS2SEC]);
  417. }
  418.  
  419. const innerRating = isTeamOrBeginner
  420. ? correctedRating
  421. : (standingsEntry.UserScreenName in innerRatingsFromPredictor)
  422. ? innerRatingsFromPredictor[standingsEntry.UserScreenName]
  423. : RatingConverter.toInnerRating(
  424. Math.max(RatingConverter.toRealRating(correctedRating), 1), standingsEntry.Competitions);
  425. if (innerRating) innerRatings.push(innerRating);
  426. else {
  427. console.log(i, innerRating, correctedRating, standingsEntry.Competitions);
  428. continue;
  429. }
  430. for (let j = 0; j < tasks.length; ++j) {
  431. const taskResultEntry = standingsEntry.TaskResults[tasks[j].TaskScreenName];
  432. const isAccepted = (taskResultEntry?.Score > 0 && taskResultEntry?.Status == 1);
  433. if (isAccepted) {
  434. ++taskAcceptedCounts[j];
  435. taskAcceptedElapsedTimes[j].push(taskResultEntry.Elapsed / NS2SEC);
  436. }
  437. }
  438. if (standingsEntry.UserScreenName == userScreenName) {
  439. yourScore = score;
  440. yourLastAcceptedTime = standingsEntry.TotalResult.Elapsed / NS2SEC;
  441. for (let j = 0; j < tasks.length; ++j) {
  442. const taskResultEntry = standingsEntry.TaskResults[tasks[j].TaskScreenName];
  443. const isAccepted = (taskResultEntry?.Score > 0 && taskResultEntry?.Status == 1);
  444. if (isAccepted) {
  445. yourTaskAcceptedElapsedTimes[j] = taskResultEntry.Elapsed / NS2SEC;
  446. }
  447. }
  448. }
  449. }
  450. innerRatings.sort((a, b) => a - b);
  451.  
  452. const dc = new DifficultyCalculator(innerRatings);
  453.  
  454. const plotlyDifficultyChartId = 'acssa-mydiv-difficulty';
  455. const plotlyAcceptedCountChartId = 'acssa-mydiv-accepted-count';
  456. const plotlyLastAcceptedTimeChartId = 'acssa-mydiv-accepted-time';
  457. const COL_PER_ROW = 20;
  458. $('#vue-standings').prepend(`
  459. <div id="acssa-contents">
  460. ${[...Array(Math.ceil(tasks.length / COL_PER_ROW)).keys()].map(tableIdx => `
  461. <table id="acssa-table-${tableIdx}" class="table table-bordered table-hover th-center td-center td-middle acssa-table">
  462. <tbody>
  463. <tr id="acssa-thead-${tableIdx}" class="acssa-thead"></tr>
  464. </tbody>
  465. <tbody>
  466. <tr id="acssa-tbody-${tableIdx}" class="acssa-tbody"></tr>
  467. </tbody>
  468. </table>
  469. `).join('')}
  470. <div id="acssa-tab-wrapper">
  471. <ul class="nav nav-pills small" id="acssa-chart-tab">
  472. <li class="active">
  473. <a class="acssa-chart-tab-button"><span class="glyphicon glyphicon-stats" aria-hidden="true"></span>Difficulty</a></li>
  474. <li>
  475. <a class="acssa-chart-tab-button"><span class="glyphicon glyphicon-stats" aria-hidden="true"></span>AC Count</a></li>
  476. <li>
  477. <a class="acssa-chart-tab-button"><span class="glyphicon glyphicon-stats" aria-hidden="true"></span>LastAcceptedTime</a></li>
  478. </ul>
  479. <ul class="nav nav-pills" id="acssa-checkbox-tab">
  480. <li>
  481. <a><label><input type="checkbox" id="acssa-checkbox-toggle-your-result-visibility" checked> Plot your result</label></a></li>
  482. <li id="acssa-checkbox-toggle-log-plot-parent">
  483. <a><label><input type="checkbox" id="acssa-checkbox-toggle-log-plot">Log plot</label></a></li>
  484. </ul>
  485. </div>
  486. <div id="acssa-loader" class="loader acssa-loader-wrapper">
  487. <div class="loader-inner ball-pulse">
  488. <div></div>
  489. <div></div>
  490. <div></div>
  491. </div>
  492. </div>
  493. <div id="acssa-chart-block">
  494. <div class="acssa-chart-wrapper acssa-chart-wrapper-active" id="${plotlyDifficultyChartId}-wrapper">
  495. <div id="${plotlyDifficultyChartId}" style="width:100%;"></div>
  496. </div>
  497. <div class="acssa-chart-wrapper" id="${plotlyAcceptedCountChartId}-wrapper">
  498. <div id="${plotlyAcceptedCountChartId}" style="width:100%;"></div>
  499. </div>
  500. <div class="acssa-chart-wrapper" id="${plotlyLastAcceptedTimeChartId}-wrapper">
  501. <div id="${plotlyLastAcceptedTimeChartId}" style="width:100%;"></div>
  502. </div>
  503. </div>
  504. </div>
  505. `);
  506.  
  507. // チェックボックス操作時のイベントを登録する
  508. /** @type {HTMLInputElement} */
  509. const checkbox = document.getElementById("acssa-checkbox-toggle-your-result-visibility");
  510. checkbox.addEventListener("change", () => {
  511. if (checkbox.checked) {
  512. document.querySelectorAll('.acssa-task-success.acssa-task-success-suppress').forEach(elm => {
  513. elm.classList.remove('acssa-task-success-suppress');
  514. });
  515. } else {
  516. document.querySelectorAll('.acssa-task-success').forEach(elm => {
  517. elm.classList.add('acssa-task-success-suppress');
  518. });
  519. }
  520. });
  521.  
  522. let activeTab = 0;
  523. const showYourResult = [true, true, true];
  524.  
  525. let yourDifficultyChartData = null;
  526. let yourAcceptedCountChartData = null;
  527. let yourLastAcceptedTimeChartData = null;
  528. let yourLastAcceptedTimeChartDataIndex = -1;
  529. const onCheckboxChanged = () => {
  530. showYourResult[activeTab] = checkbox.checked;
  531. if (checkbox.checked) {
  532. // show
  533. switch (activeTab) {
  534. case 0:
  535. if (yourScore > 0) Plotly.addTraces(plotlyDifficultyChartId, yourDifficultyChartData);
  536. break;
  537. case 1:
  538. if (yourScore > 0) Plotly.addTraces(plotlyAcceptedCountChartId, yourAcceptedCountChartData);
  539. break;
  540. case 2:
  541. if (yourLastAcceptedTimeChartDataIndex != -1) {
  542. Plotly.addTraces(plotlyLastAcceptedTimeChartId, yourLastAcceptedTimeChartData, yourLastAcceptedTimeChartDataIndex);
  543. }
  544. break;
  545. default:
  546. break;
  547. }
  548. } else {
  549. // hide
  550. switch (activeTab) {
  551. case 0:
  552. if (yourScore > 0) Plotly.deleteTraces(plotlyDifficultyChartId, -1);
  553. break;
  554. case 1:
  555. if (yourScore > 0) Plotly.deleteTraces(plotlyAcceptedCountChartId, -1);
  556. break;
  557. case 2:
  558. if (yourLastAcceptedTimeChartDataIndex != -1) {
  559. Plotly.deleteTraces(plotlyLastAcceptedTimeChartId, yourLastAcceptedTimeChartDataIndex);
  560. }
  561. break;
  562. default:
  563. break;
  564. }
  565. }
  566. };
  567.  
  568. /** @type {HTMLInputElement} */
  569. const logPlotCheckbox = document.getElementById('acssa-checkbox-toggle-log-plot');
  570. const logPlotCheckboxParent = document.getElementById('acssa-checkbox-toggle-log-plot-parent');
  571.  
  572. let acceptedCountYMax = -1;
  573. const useLogPlot = [false, false, false];
  574. const onLogPlotCheckboxChanged = () => {
  575. if (acceptedCountYMax == -1) return;
  576. useLogPlot[activeTab] = logPlotCheckbox.checked;
  577. if (activeTab == 1) {
  578. if (logPlotCheckbox.checked) {
  579. // log plot
  580. const layout = {
  581. yaxis: {
  582. type: 'log',
  583. range: [
  584. Math.log10(0.5),
  585. Math.log10(acceptedCountYMax)
  586. ],
  587. },
  588. };
  589. Plotly.relayout(plotlyAcceptedCountChartId, layout);
  590. } else {
  591. // linear plot
  592. const layout = {
  593. yaxis: {
  594. type: 'linear',
  595. range: [
  596. 0,
  597. acceptedCountYMax
  598. ],
  599. },
  600. };
  601. Plotly.relayout(plotlyAcceptedCountChartId, layout);
  602. }
  603. } else if (activeTab == 2) {
  604. if (logPlotCheckbox.checked) {
  605. // log plot
  606. const layout = {
  607. xaxis: {
  608. type: 'log',
  609. range: [
  610. Math.log10(0.5),
  611. Math.log10(participants)
  612. ],
  613. },
  614. };
  615. Plotly.relayout(plotlyLastAcceptedTimeChartId, layout);
  616. } else {
  617. // linear plot
  618. const layout = {
  619. xaxis: {
  620. type: 'linear',
  621. range: [
  622. 0,
  623. participants
  624. ],
  625. },
  626. };
  627. Plotly.relayout(plotlyLastAcceptedTimeChartId, layout);
  628. }
  629. }
  630. };
  631.  
  632. document.querySelectorAll(".acssa-chart-tab-button").forEach((btn, key) => {
  633. btn.addEventListener("click", () => {
  634. // check whether active or not
  635. if (btn.parentElement.className == "active") return;
  636. // modify visibility
  637. activeTab = key;
  638. document.querySelector("#acssa-chart-tab li.active").classList.remove("active");
  639. document.querySelector(`#acssa-chart-tab li:nth-child(${key + 1})`).classList.add("active");
  640. document.querySelector("#acssa-chart-block div.acssa-chart-wrapper-active").classList.remove("acssa-chart-wrapper-active");
  641. document.querySelector(`#acssa-chart-block div.acssa-chart-wrapper:nth-child(${key + 1})`).classList.add("acssa-chart-wrapper-active");
  642. // resize charts
  643. switch (key) {
  644. case 0:
  645. Plotly.relayout(plotlyDifficultyChartId, { width: document.getElementById(plotlyDifficultyChartId).clientWidth });
  646. logPlotCheckboxParent.style.display = 'none';
  647. break;
  648. case 1:
  649. Plotly.relayout(plotlyAcceptedCountChartId, { width: document.getElementById(plotlyAcceptedCountChartId).clientWidth });
  650. logPlotCheckboxParent.style.display = 'block';
  651. break;
  652. case 2:
  653. Plotly.relayout(plotlyLastAcceptedTimeChartId, { width: document.getElementById(plotlyLastAcceptedTimeChartId).clientWidth });
  654. logPlotCheckboxParent.style.display = 'block';
  655. break;
  656. default:
  657. break;
  658. }
  659. if (showYourResult[activeTab] !== checkbox.checked) {
  660. onCheckboxChanged();
  661. }
  662. if (activeTab !== 0 && useLogPlot[activeTab] !== logPlotCheckbox.checked) {
  663. onLogPlotCheckboxChanged();
  664. }
  665. });
  666. });
  667.  
  668. logPlotCheckbox.addEventListener('change', onLogPlotCheckboxChanged);
  669.  
  670. // 現在の Difficulty テーブルを構築する
  671. for (let j = 0; j < tasks.length; ++j) {
  672. const tableIdx = Math.floor(j / COL_PER_ROW);
  673. const correctedDifficulty = RatingConverter.toCorrectedRating(dc.binarySearch(taskAcceptedCounts[j]));
  674. const tdClass = yourTaskAcceptedElapsedTimes[j] === -1 ? '' : 'class="success acssa-task-success"';
  675. document.getElementById(`acssa-thead-${tableIdx}`).insertAdjacentHTML("beforeend", `
  676. <td ${tdClass}>
  677. ${tasks[j].Assignment}
  678. </td>
  679. `);
  680. const id = `td-assa-difficulty-${j}`;
  681. document.getElementById(`acssa-tbody-${tableIdx}`).insertAdjacentHTML("beforeend", `
  682. <td ${tdClass} id="${id}" style="color:${getColor(correctedDifficulty)};">
  683. ${correctedDifficulty === 9999 ? '-' : correctedDifficulty}</td>
  684. `);
  685. if (correctedDifficulty !== 9999) {
  686. document.getElementById(id).insertAdjacentHTML(
  687. "afterbegin", generateDifficultyCircle(correctedDifficulty));
  688. }
  689. }
  690.  
  691. if (yourScore == -1) {
  692. // disable checkbox
  693. checkbox.checked = false;
  694. checkbox.disabled = true;
  695. checkbox.parentElement.style.cursor = 'default';
  696. checkbox.parentElement.style.textDecoration = 'line-through';
  697. }
  698.  
  699. // 順位表のその他の描画を優先するために,後回しにする
  700. setTimeout(() => {
  701. const maxAcceptedCount = taskAcceptedCounts.reduce((a, b) => Math.max(a, b));
  702. const yMax = RatingConverter.toCorrectedRating(dc.binarySearch(1));
  703. const yMin = RatingConverter.toCorrectedRating(dc.binarySearch(Math.max(2, maxAcceptedCount)));
  704.  
  705. // 以降の計算は時間がかかる
  706.  
  707. taskAcceptedElapsedTimes.forEach(ar => {
  708. ar.sort((a, b) => a - b);
  709. });
  710.  
  711. // 時系列データの準備
  712. /** Difficulty Chart のデータ
  713. * @type {{x: number, y: number, type: string, name: string}[]} */
  714. const difficultyChartData = [];
  715. /** AC Count Chart のデータ
  716. * @type {{x: number, y: number, type: string, name: string}[]} */
  717. const acceptedCountChartData = [];
  718.  
  719. for (let j = 0; j < tasks.length; ++j) { //
  720. const interval = Math.ceil(taskAcceptedCounts[j] / 140);
  721. /** @type {[number[], number[]]} */
  722. const [taskAcceptedElapsedTimesForChart, taskAcceptedCountsForChart] = taskAcceptedElapsedTimes[j].reduce(
  723. ([ar, arr], tm, idx) => {
  724. const tmpInterval = Math.max(1, Math.min(Math.ceil(idx / 10), interval));
  725. if (idx % tmpInterval == 0 || idx == taskAcceptedCounts[j] - 1) {
  726. ar.push(tm);
  727. arr.push(idx + 1);
  728. }
  729. return [ar, arr];
  730. },
  731. [[], []]
  732. );
  733.  
  734. difficultyChartData.push({
  735. x: taskAcceptedElapsedTimesForChart,
  736. y: taskAcceptedCountsForChart.map(taskAcceptedCountForChart => dc.binarySearch(taskAcceptedCountForChart)),
  737. type: 'scatter',
  738. name: `${tasks[j].Assignment}`,
  739. });
  740. acceptedCountChartData.push({
  741. x: taskAcceptedElapsedTimesForChart,
  742. y: taskAcceptedCountsForChart,
  743. type: 'scatter',
  744. name: `${tasks[j].Assignment}`,
  745. });
  746. }
  747.  
  748. // 現在のユーザのデータを追加
  749. const yourMarker = {
  750. size: 10,
  751. symbol: "cross",
  752. color: 'red',
  753. line: {
  754. color: 'white',
  755. width: 1,
  756. },
  757. };
  758. if (yourScore !== -1) {
  759. /** @type {number[]} */
  760. const yourAcceptedTimes = [];
  761. /** @type {number[]} */
  762. const yourAcceptedDifficulties = [];
  763. /** @type {number[]} */
  764. const yourAcceptedCounts = [];
  765.  
  766. for (let j = 0; j < tasks.length; ++j) {
  767. if (yourTaskAcceptedElapsedTimes[j] !== -1) {
  768. yourAcceptedTimes.push(yourTaskAcceptedElapsedTimes[j]);
  769. const yourAcceptedCount = arrayLowerBound(taskAcceptedElapsedTimes[j], yourTaskAcceptedElapsedTimes[j]) + 1;
  770. yourAcceptedCounts.push(yourAcceptedCount);
  771. yourAcceptedDifficulties.push(dc.binarySearch(yourAcceptedCount));
  772. }
  773. }
  774.  
  775. yourDifficultyChartData = {
  776. x: yourAcceptedTimes,
  777. y: yourAcceptedDifficulties,
  778. mode: 'markers',
  779. type: 'scatter',
  780. name: `${userScreenName}`,
  781. marker: yourMarker,
  782. };
  783. yourAcceptedCountChartData = {
  784. x: yourAcceptedTimes,
  785. y: yourAcceptedCounts,
  786. mode: 'markers',
  787. type: 'scatter',
  788. name: `${userScreenName}`,
  789. marker: yourMarker,
  790. };
  791. difficultyChartData.push(yourDifficultyChartData);
  792. acceptedCountChartData.push(yourAcceptedCountChartData);
  793. }
  794.  
  795. // 得点と提出時間データの準備
  796. /** @type {{x: number, y: number, type: string, name: string}[]} */
  797. const lastAcceptedTimeChartData = [];
  798. const scores = [...scoreLastAcceptedTimeMap.keys()];
  799. scores.sort((a, b) => b - a);
  800. let acc = 0;
  801. let maxAcceptedTime = 0;
  802. scores.forEach(score => {
  803. const lastAcceptedTimes = scoreLastAcceptedTimeMap.get(score);
  804. lastAcceptedTimes.sort((a, b) => a - b);
  805. const interval = Math.ceil(lastAcceptedTimes.length / 100);
  806. /** @type {number[]} */
  807. const lastAcceptedTimesForChart = lastAcceptedTimes.reduce((ar, tm, idx) => {
  808. if (idx % interval == 0 || idx == lastAcceptedTimes.length - 1) ar.push(tm);
  809. return ar;
  810. }, []);
  811. const lastAcceptedTimesRanks = lastAcceptedTimes.reduce((ar, tm, idx) => {
  812. if (idx % interval == 0 || idx == lastAcceptedTimes.length - 1) ar.push(acc + idx + 1);
  813. return ar;
  814. }, []);
  815.  
  816. lastAcceptedTimeChartData.push({
  817. x: lastAcceptedTimesRanks,
  818. y: lastAcceptedTimesForChart,
  819. type: 'scatter',
  820. name: `${score}`,
  821. });
  822.  
  823. if (score === yourScore) {
  824. const lastAcceptedTimesRank = arrayLowerBound(lastAcceptedTimes, yourLastAcceptedTime);
  825. yourLastAcceptedTimeChartData = {
  826. x: [acc + lastAcceptedTimesRank + 1],
  827. y: [yourLastAcceptedTime],
  828. mode: 'markers',
  829. type: 'scatter',
  830. name: `${userScreenName}`,
  831. marker: yourMarker,
  832. };
  833. yourLastAcceptedTimeChartDataIndex = lastAcceptedTimeChartData.length + 0;
  834. lastAcceptedTimeChartData.push(yourLastAcceptedTimeChartData);
  835. }
  836.  
  837. acc += lastAcceptedTimes.length;
  838. if (lastAcceptedTimes[lastAcceptedTimes.length - 1] > maxAcceptedTime) {
  839. maxAcceptedTime = lastAcceptedTimes[lastAcceptedTimes.length - 1];
  840. }
  841. });
  842.  
  843. const duration = getContestDurationSec();
  844. const xtick = (60 * 10) * Math.max(1, Math.ceil(duration / (60 * 10 * 20))); // 10 分を最小単位にする
  845.  
  846. // 軸フォーマットをカスタムする
  847. // Support specifying a function for tickformat · Issue #1464 · plotly/plotly.js
  848. // https://github.com/plotly/plotly.js/issues/1464#issuecomment-498050894
  849. {
  850. const org_locale = Plotly.d3.locale;
  851. Plotly.d3.locale = (locale) => {
  852. const result = org_locale(locale);
  853. const org_number_format = result.numberFormat;
  854. result.numberFormat = (format) => {
  855. if (format != 'TIME') {
  856. return org_number_format(format)
  857. }
  858. return (x) => formatTimespan(x).toString();
  859. }
  860. return result;
  861. };
  862. }
  863.  
  864. // 背景用設定
  865. const alpha = 0.3;
  866. /** @type {[number, number, string][]} */
  867. const colors = [
  868. [0, 400, `rgba(128,128,128,${alpha})`],
  869. [400, 800, `rgba(128,0,0,${alpha})`],
  870. [800, 1200, `rgba(0,128,0,${alpha})`],
  871. [1200, 1600, `rgba(0,255,255,${alpha})`],
  872. [1600, 2000, `rgba(0,0,255,${alpha})`],
  873. [2000, 2400, `rgba(255,255,0,${alpha})`],
  874. [2400, 2800, `rgba(255,165,0,${alpha})`],
  875. [2800, 10000, `rgba(255,0,0,${alpha})`],
  876. ];
  877.  
  878. // Difficulty Chart 描画
  879. {
  880. // 描画
  881. const layout = {
  882. title: 'Difficulty',
  883. xaxis: {
  884. dtick: xtick,
  885. tickformat: 'TIME',
  886. range: [0, duration],
  887. // title: { text: 'Elapsed' }
  888. },
  889. yaxis: {
  890. dtick: 400,
  891. tickformat: 'd',
  892. range: [
  893. Math.max(0, Math.floor((yMin - 100) / 400) * 400),
  894. Math.max(0, Math.ceil((yMax + 100) / 400) * 400)
  895. ],
  896. // title: { text: 'Difficulty' }
  897. },
  898. shapes: colors.map(c => {
  899. return {
  900. type: 'rect',
  901. layer: 'below',
  902. xref: 'x',
  903. yref: 'y',
  904. x0: 0,
  905. x1: duration,
  906. y0: c[0],
  907. y1: c[1],
  908. line: { width: 0 },
  909. fillcolor: c[2]
  910. };
  911. }),
  912. margin: {
  913. b: 60,
  914. t: 30,
  915. }
  916. };
  917. const config = { autosize: true };
  918. Plotly.newPlot(plotlyDifficultyChartId, difficultyChartData, layout, config);
  919.  
  920. window.addEventListener('resize', () => {
  921. if (activeTab == 0)
  922. Plotly.relayout(plotlyDifficultyChartId, { width: document.getElementById(plotlyDifficultyChartId).clientWidth });
  923. });
  924. }
  925.  
  926. // Accepted Count Chart 描画
  927. {
  928. acceptedCountYMax = participants;
  929. /** @type {[number, number, string][]} */
  930. const rectSpans = colors.reduce((ar, cur) => {
  931. const bottom = dc.perf2ExpectedAcceptedCount(cur[1]);
  932. if (bottom > acceptedCountYMax) return ar;
  933. const top = (cur[0] == 0) ? acceptedCountYMax : dc.perf2ExpectedAcceptedCount(cur[0]);
  934. if (top < 0.5) return ar;
  935. ar.push([Math.max(0.5, bottom), Math.min(acceptedCountYMax, top), cur[2]]);
  936. return ar;
  937. }, []);
  938. // 描画
  939. const layout = {
  940. title: 'Accepted Count',
  941. xaxis: {
  942. dtick: xtick,
  943. tickformat: 'TIME',
  944. range: [0, duration],
  945. // title: { text: 'Elapsed' }
  946. },
  947. yaxis: {
  948. // type: 'log',
  949. // dtick: 100,
  950. tickformat: 'd',
  951. range: [
  952. 0,
  953. acceptedCountYMax
  954. ],
  955. // range: [
  956. // Math.log10(0.5),
  957. // Math.log10(acceptedCountYMax)
  958. // ],
  959. // title: { text: 'Difficulty' }
  960. },
  961. shapes: rectSpans.map(span => {
  962. return {
  963. type: 'rect',
  964. layer: 'below',
  965. xref: 'x',
  966. yref: 'y',
  967. x0: 0,
  968. x1: duration,
  969. y0: span[0],
  970. y1: span[1],
  971. line: { width: 0 },
  972. fillcolor: span[2]
  973. };
  974. }),
  975. margin: {
  976. b: 60,
  977. t: 30,
  978. }
  979. };
  980. const config = { autosize: true };
  981. Plotly.newPlot(plotlyAcceptedCountChartId, acceptedCountChartData, layout, config);
  982.  
  983. window.addEventListener('resize', () => {
  984. if (activeTab == 1)
  985. Plotly.relayout(plotlyAcceptedCountChartId, { width: document.getElementById(plotlyAcceptedCountChartId).clientWidth });
  986. });
  987. }
  988.  
  989. // LastAcceptedTime Chart 描画
  990. {
  991. const xMax = participants;
  992. const yMax = Math.ceil((maxAcceptedTime + xtick / 2) / xtick) * xtick;
  993. /** @type {[number, number, string][]} */
  994. const rectSpans = colors.reduce((ar, cur) => {
  995. const right = (cur[0] == 0) ? xMax : dc.perf2Ranking(cur[0]);
  996. if (right < 1) return ar;
  997. const left = dc.perf2Ranking(cur[1]);
  998. if (left > xMax) return ar;
  999. ar.push([Math.max(0, left), Math.min(xMax, right), cur[2]]);
  1000. return ar;
  1001. }, []);
  1002. // console.log(colors);
  1003. // console.log(rectSpans);
  1004. const layout = {
  1005. title: 'LastAcceptedTime v.s. Rank',
  1006. xaxis: {
  1007. // dtick: 100,
  1008. tickformat: 'd',
  1009. range: [0, xMax],
  1010. // title: { text: 'Elapsed' }
  1011. },
  1012. yaxis: {
  1013. dtick: xtick,
  1014. tickformat: 'TIME',
  1015. range: [0, yMax],
  1016. // range: [
  1017. // Math.max(0, Math.floor((yMin - 100) / 400) * 400),
  1018. // Math.max(0, Math.ceil((yMax + 100) / 400) * 400)
  1019. // ],
  1020. // title: { text: 'Difficulty' }
  1021. },
  1022. shapes: rectSpans.map(span => {
  1023. return {
  1024. type: 'rect',
  1025. layer: 'below',
  1026. xref: 'x',
  1027. yref: 'y',
  1028. x0: span[0],
  1029. x1: span[1],
  1030. y0: 0,
  1031. y1: yMax,
  1032. line: { width: 0 },
  1033. fillcolor: span[2]
  1034. };
  1035. }),
  1036. margin: {
  1037. b: 60,
  1038. t: 30,
  1039. }
  1040. };
  1041. const config = { autosize: true };
  1042. Plotly.newPlot(plotlyLastAcceptedTimeChartId, lastAcceptedTimeChartData, layout, config);
  1043.  
  1044. window.addEventListener('resize', () => {
  1045. if (activeTab == 2)
  1046. Plotly.relayout(plotlyLastAcceptedTimeChartId, { width: document.getElementById(plotlyLastAcceptedTimeChartId).clientWidth });
  1047. });
  1048. }
  1049.  
  1050. // 現在のユーザの結果表示・非表示 toggle
  1051. checkbox.addEventListener('change', onCheckboxChanged);
  1052.  
  1053. document.getElementById('acssa-loader').style.display = 'none';
  1054. document.getElementById('acssa-tab-wrapper').style.display = 'block';
  1055. working = false;
  1056. }, 100); // end setTimeout()
  1057. };
  1058.  
  1059. // MAIN
  1060. vueStandings.$watch('standings', onStandingsChanged, { deep: true, immediate: true });
  1061.  
  1062. })();