@pkmn/stats 0.0.2 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGES.md +90 -0
  2. package/README.md +11 -7
  3. package/build/aliases.json +1 -0
  4. package/build/binary.d.ts +137 -0
  5. package/build/binary.js +386 -0
  6. package/build/binary.js.map +1 -0
  7. package/build/classifier.d.ts +2 -2
  8. package/build/classifier.js +45 -39
  9. package/build/classifier.js.map +1 -1
  10. package/build/data.d.ts +39 -0
  11. package/build/data.js +126 -0
  12. package/build/data.js.map +1 -0
  13. package/build/display.d.ts +1 -1
  14. package/build/display.js +18 -8
  15. package/build/display.js.map +1 -1
  16. package/build/index.d.ts +1 -0
  17. package/build/index.js +3 -1
  18. package/build/index.js.map +1 -1
  19. package/build/parser.d.ts +2 -2
  20. package/build/parser.js +55 -37
  21. package/build/parser.js.map +1 -1
  22. package/build/pkmn/data.d.ts +39 -0
  23. package/build/pkmn/data.js +126 -0
  24. package/build/pkmn/data.js.map +1 -0
  25. package/build/pkmn/index.d.ts +1 -0
  26. package/build/pkmn/index.js +18 -0
  27. package/build/pkmn/index.js.map +1 -0
  28. package/build/reports.d.ts +2 -2
  29. package/build/reports.js +27 -20
  30. package/build/reports.js.map +1 -1
  31. package/build/smogon/aliases.json +227 -0
  32. package/build/smogon/classifier.d.ts +12 -0
  33. package/build/smogon/classifier.js +556 -0
  34. package/build/smogon/classifier.js.map +1 -0
  35. package/build/smogon/display.d.ts +96 -0
  36. package/build/smogon/display.js +412 -0
  37. package/build/smogon/display.js.map +1 -0
  38. package/build/smogon/index.d.ts +6 -0
  39. package/build/smogon/index.js +19 -0
  40. package/build/smogon/index.js.map +1 -0
  41. package/build/smogon/parser.d.ts +57 -0
  42. package/build/smogon/parser.js +358 -0
  43. package/build/smogon/parser.js.map +1 -0
  44. package/build/smogon/reports.d.ts +51 -0
  45. package/build/smogon/reports.js +652 -0
  46. package/build/smogon/reports.js.map +1 -0
  47. package/build/smogon/stats.d.ts +119 -0
  48. package/build/smogon/stats.js +521 -0
  49. package/build/smogon/stats.js.map +1 -0
  50. package/build/smogon/test/integration.d.ts +30 -0
  51. package/build/smogon/test/integration.js +179 -0
  52. package/build/smogon/test/integration.js.map +1 -0
  53. package/build/smogon/test/integration.test.d.ts +1 -0
  54. package/build/smogon/test/integration.test.js +38 -0
  55. package/build/smogon/test/integration.test.js.map +1 -0
  56. package/build/smogon/test/parser.test.d.ts +1 -0
  57. package/build/smogon/test/parser.test.js +91 -0
  58. package/build/smogon/test/parser.test.js.map +1 -0
  59. package/build/smogon/util.d.ts +63 -0
  60. package/build/smogon/util.js +400 -0
  61. package/build/smogon/util.js.map +1 -0
  62. package/build/stats.d.ts +3 -3
  63. package/build/stats.js +34 -34
  64. package/build/stats.js.map +1 -1
  65. package/build/util.d.ts +7 -7
  66. package/build/util.js +42 -32
  67. package/build/util.js.map +1 -1
  68. package/package.json +11 -14
  69. package/src/aliases.json +1 -0
  70. package/src/binary.ts +514 -0
  71. package/src/classifier.ts +38 -37
  72. package/src/display.ts +12 -14
  73. package/src/index.ts +6 -17
  74. package/src/parser.ts +39 -22
  75. package/src/reports.ts +22 -21
  76. package/src/stats.ts +27 -24
  77. package/src/util.ts +39 -39
package/CHANGES.md ADDED
@@ -0,0 +1,90 @@
1
+ # Changes
2
+
3
+ [Smogon-Usage-Stats](https://github.com/Antar1011/Smogon-Usage-Stats) covers both the reading and
4
+ processing logs aspect of logs analysis as well as the the logic for computing stats and reports
5
+ from the logs themselves. In this project these two aspects are instead separated into `@okmn/logs`
6
+ and `@pkmn/stats` respectively, with `@pkmn/logs` being substantially more sophisticated than the
7
+ data pipeline provided by Smogon-Usage-Stats for increased flexibilty and performance.
8
+
9
+ Smogon-Usage-Stats serially processes logs files for each format using `batchLogReader.py` (and
10
+ `TA.py`) which is run incrementally, writing the compressed intermediate results of the processing
11
+ to a `'Raw/'` directory. At the end of the month when analysis is performed, several different
12
+ types of reports are created based on various rating 'cutoffs' which impact the weighting of the
13
+ statistics in the reports. Producing reports involves running `StatCounter.py` followed by the
14
+ `batchMovesetReader.py` (which depends on the output from `StatCounter.py`). Producing these reports
15
+ is performed using the GNU `parallel` command, effectively allowing the reports for each cutoff to
16
+ be performed simultaneously. Finally, the same reports generation process is repeated again in
17
+ `MonotypeAnalysis.sh`. `TierUpdate.py` / `TierUpdateOM.py` can be run separately against past
18
+ reports to generate tier updates (Pokémon rises and drops per tier).
19
+
20
+ `@pkmn/stats` has been written to allow for increased flexibility and parallelism in the data
21
+ processing pipeline by providing support for combining and reordering stages (eg. computing all of
22
+ the statistics `StatCounter.py` and `batchMovesetCounter.py` do at the same time instead of
23
+ serially, computing cutoffs or tags in parallel, etc) and avoiding duplicate work wherever possible.
24
+ All complicated file processing logic has been split off to the `@pkmn/logs` package, leaving
25
+ `@pkmn/stats` as a pure package responsible solely for the manipulation of the data in the logs as
26
+ opposed to the logs themselves.
27
+
28
+ In addition to the high-level architectural changes, Smogon-Usage-Stats has a number of bugs and
29
+ quirks that have been corrected by `@pkmn/stats` unless "legacy" mode is opted into:
30
+
31
+ - The ordering of output from Smogon-Usage-Stats often depends on Python 2's internal **sort
32
+ ordering** for dictionaries, `@pkmn/stats` does not base its sort orders on a particular
33
+ programming language's implementation details.
34
+ - `@pkmn/stats` offers a [**unified display option**](OUTPUT.md) that consolidates and extends the
35
+ information from all of Smogon-Usage-Stats reports.
36
+ - The reports from processing logs with `@pkmn/stats` via `@pkmn/logs` are going to be subtly
37
+ different than those from Smogon-Usage-Stats due to different architectures and the fact that
38
+ [**floating-point arithmetic**](https://en.wikipedia.org/wiki/Floating-point_arithmetic) is not
39
+ commutative. This is not an inherent difference between `@pkmn/stats` and Smogon-Usage-Stats (logs
40
+ can be processed with `@pkmn/stats` in a similar way to Smogon-Usage-Stats to ensure that the
41
+ reports match), but is a difference that results in practice given that `@pkmn/logs` is the
42
+ replacement for Smogon-Usage-Stats' processing infrastructure.
43
+ - Smogon-Usage-Stats 'extracts' type and base stat data from Pokémon Showdown's data files but
44
+ **only handles the most recent generation**, meaning when it processes logs from older
45
+ generations. the modern data is erroneously used. `@pkmn/stats` uses the accurate data for the
46
+ generation being processed.
47
+ - Smogon-Usage-Stats considers 'Primal' Pokémon as mega-evolutions along with 'Mega' Pokémon but
48
+ forgets about **'Ultra Burst'**. `@pkmn/stats` handles 'Ultra Burst' Pokémon the same as the other
49
+ mega-evolution types.
50
+ - Smogon-Usage-Stats depends on numerous **hardcoded lists** - of non-singles or non-6v6 formats,
51
+ 'setup' moves, 'dragon' Pokémon, battle formes etc which include several notable absences
52
+ (Darmanitan-Zen and Meloetta-Piroutte are not considered formes, Kommo-o is not considered a
53
+ 'dragon') and have not been updated for Generation 8. `@pkmn/stats` instead computes these lists
54
+ programmatically from the data files to ensure they are comphrensive and up to date.
55
+ - `Nidoran-M` is displayed in reports as `NidoranM`, `Nidroran-F` as `NidoranF` and `Flabébé` as
56
+ `Flabebe` in Smogon-Usage-Stats whereas these **names display** correctly in `@pkmn/stats`.
57
+ - The **'`empty'`** internal placeholder value is filtered out of reports and stats update logic by
58
+ `@pkmn/stats` but influences results and is displayed by Smogon-Usage-Stats.
59
+ - The code used by Smogon-Usage-Stats to display the **'stalliness' histogram** report contains a
60
+ bug in the [logic used to determine the start as it attempts to compare an array and a
61
+ number](https://github.com/Antar1011/Smogon-Usage-Stats/blob/59a9c1cf/StatCounter.py#L354-L356) -
62
+ this no-op is simply removed in `@pkmn/stats`.
63
+ - In the case of a **'double down'** where both sides' Pokémon faint, Smogon-Usage-Stats only
64
+ increments the KO count for a single side in the case of `|switch|` or `|drag|` protocol messages
65
+ (it handles double downs properly in the case of `|win|` or `|tie|`). `@pkmn/stats` treats all
66
+ double downs correctly.
67
+ - Smogon-Usage-Stats' team canconicalization does not respect the **`hpType`** field when
68
+ determining Hidden Power type, `@pkmn/stats` does.
69
+ - Smogon-Usage-Stats ignores and does not track a mega-evolved Pokémon's **Ability pre-mega
70
+ evolution**, `@pkmn/stats` does.
71
+ - Smogon-Usage-Stats team analyzer intends to handle the **classification** of Meloetta-Pirouette,
72
+ Darmanitan-Zen, Mega-Rayquaze and regular megas separately but fails to do so, `@pkmn/stats`
73
+ instead applies the intended handling approriately.
74
+ - The 'Checks and Counters' section of Smogon-Usage-Stats' moveset report has **botched padding**
75
+ around the 'KOed/switched out' cell, `@pkmn/stats` fixes this.
76
+ - The Smogon-Usage-Stat moveset report is **sorted incorrectly** because it sorts *after* rounding
77
+ the usage values - `@pkmn/stats` sorts before rounding.
78
+ - Smogon-Usage-Stats intends to coalesce all neutral Natures into 'Hardy' but fails to do so,
79
+ `@pkmn/stats` corrects this.
80
+ - Smogon-Usage-Stats only **removes extraneous EVs** from a Pokémon's Defense EV total instead of
81
+ applying the rounding logic to all EVs like `@pkmn/stats` does.
82
+ - Smogon-Usage-Stats internally treats an **`rprd` of `0`** differently in various reports,
83
+ `@pkmn/stats` handles a `rprd` of `0` consistently across its output.
84
+
85
+ Smogon-Usage-Stats has a bug in its log parsing logic where it chokes on an interaction between
86
+ Illusion and Transform/Imposter that `@pkmn/stats` does **not** fix because it is exclusively a
87
+ concern for Hackmons formats and would require an overhaul of the parsing architecture to handle
88
+ (there is not enough information in a s single log line to disambiguate the scenario). If
89
+ `@pkmn/stats`'s parsing logic were to be rewritten using `@pkmn/client` or similar this would be
90
+ fixable, but this would potentially have undersirable performance implications.
package/README.md CHANGED
@@ -12,7 +12,10 @@ Mathieu "Marty" Dias-Martins) from Python to TypeScript, though has since been [
12
12
  optimized, and corrected](CHANGES.md).
13
13
 
14
14
  This package can be used together with [`@pkmn/logs`](../logs) to efficiently process gigabytes of
15
- battle logs within minutes to produce the reports hosted at https://www.smogon.com/stats/.
15
+ battle logs within minutes to produce the reports hosted at https://www.smogon.com/stats/. It also
16
+ supports a custom [binary](BINARY.md) format based on
17
+ [`@pkmn/engine`](https://github.com/pkmn/engine) data and used by [pkmn](https://pkmn.cc) projects
18
+ such as [EPOKé](https://github.com/pkmn/EPOke) or [0 ERROR](https://github.com/pkmn/0-ERROR).
16
19
 
17
20
  ## Installation
18
21
 
@@ -23,8 +26,8 @@ $ npm install @pkmn/stats
23
26
  ## Usage
24
27
 
25
28
  The most naive way of using `@pkmn/stats` is to iterate over a collection of logs, run them through
26
- the [`Parser`](#Parser) and use [`Stats`](#Stats) to compute various statistics that can then be
27
- displayed by [`Display`](#Display):
29
+ the [`Parser`](#parser) and use [`Stats`](#stats) to compute various statistics that can then be
30
+ displayed by [`Display`](#display):
28
31
 
29
32
  ```ts
30
33
  import {Dex} from '@pkmn/dex';
@@ -46,8 +49,9 @@ for (const log of logs) {
46
49
  console.log(Display.fromStatistics(gen, format, stats));
47
50
  ```
48
51
 
49
- In practice, `@pkmn/stats` should be used in tandem with [`@pkmn/logs`](../logs) to produce the
50
- statistics and reports that are desired by your application.
52
+ When attempting to generate statistics for a large (100GiB+) corpus, `@pkmn/stats` can be used in
53
+ tandem with [`@pkmn/logs`](../logs) to efficiently produce the statistics and reports that are
54
+ desired by your application.
51
55
 
52
56
  #### `Parser`
53
57
 
@@ -78,7 +82,7 @@ The `Display` class can be used to produce `@pkmn/stats`'s [unified output forma
78
82
  methods are provided - `fromStatistics` for converting the `Statistics` returned by the `Stats`
79
83
  class into the unified report, and a `fromReports` method which can be used to convert legacy
80
84
  reports to a unified report which is similar ([but not identical](OUTPUT.md#Legacy)) to
81
- `@pkmn/stats`'s new format. A [CLI](#CLI) exists for converting legacy reports to the new format,
85
+ `@pkmn/stats`'s new format. A [CLI](#cli) exists for converting legacy reports to the new format,
82
86
  see below.
83
87
 
84
88
  #### `Reports`
@@ -125,7 +129,7 @@ application.
125
129
 
126
130
  ## Tests
127
131
 
128
- The 'update' report test depends on the current tiering information of every Pokéemon to determine
132
+ The 'update' report test depends on the current tiering information of every Pokémon to determine
129
133
  what the correct updates are. Because tiers changes over time, when the `@pkmn/dex` dependency gets
130
134
  updated the 'golden' expected output will need to be updated as well. To update the golden files,
131
135
  run the update script and check in its output after inspection:
@@ -215,6 +215,7 @@
215
215
  "vivillontundra": "vivillon",
216
216
  "wormadamg": "wormadamtrash",
217
217
  "wormadams": "wormadamsandy",
218
+ "zarudedada": "zarude",
218
219
  "zoroaaku": "zoroark",
219
220
  "zyc": "zygardecomplete",
220
221
  "zydog": "zygarde10",
@@ -0,0 +1,137 @@
1
+ import { Generation, ID, PokemonSet, TypeName, Dex } from '@pkmn/data';
2
+ import * as parser from './parser';
3
+ declare const enum EndType {
4
+ NORMAL = 0,
5
+ TIE = 1,
6
+ FORFEIT = 2,
7
+ FORCED_WIN = 3,
8
+ FORCED_TIE = 4
9
+ }
10
+ declare const Log: {
11
+ encode(gen: Generation, lookup: Binary.Lookup, canonicalize: (team: Partial<PokemonSet>[], dex: Dex) => Partial<PokemonSet>[], log: parser.Log, buf: Buffer, offset?: number): Buffer;
12
+ decode(gen: Generation, lookup: Binary.Lookup, buf: Buffer, offset?: number): Binary.Data;
13
+ };
14
+ export declare const Binary: {
15
+ Read: {
16
+ u8(this: void, buf: Buffer, offset: number): number;
17
+ u16(this: void, buf: Buffer, offset: number): number;
18
+ u32(this: void, buf: Buffer, offset: number): number;
19
+ u64(this: void, buf: Buffer, offset: number): bigint;
20
+ };
21
+ Write: {
22
+ u8(this: void, buf: Buffer, value: number, offset: number): number;
23
+ u16(this: void, buf: Buffer, value: number, offset: number): number;
24
+ u32(this: void, buf: Buffer, value: number, offset: number): number;
25
+ u64(this: void, buf: Buffer, value: number, offset: number): number;
26
+ };
27
+ Sizes: {
28
+ readonly 1: 5;
29
+ readonly 2: 7;
30
+ readonly 3: 24;
31
+ readonly 4: 24;
32
+ readonly 5: 24;
33
+ readonly 6: 25;
34
+ readonly 7: 26;
35
+ readonly 8: 25;
36
+ };
37
+ Log: {
38
+ encode(gen: Generation, lookup: Binary.Lookup, canonicalize: (team: Partial<PokemonSet>[], dex: Dex) => Partial<PokemonSet>[], log: parser.Log, buf: Buffer, offset?: number): Buffer;
39
+ decode(gen: Generation, lookup: Binary.Lookup, buf: Buffer, offset?: number): Binary.Data;
40
+ };
41
+ Team: {
42
+ encode(gen: Generation, lookup: Binary.Lookup, team: Partial<PokemonSet>[], buf: Buffer, offset?: number): number;
43
+ decode(gen: Generation, lookup: Binary.Lookup, buf: Buffer, offset?: number): Partial<PokemonSet<string>>[];
44
+ };
45
+ Stats: {
46
+ sizes(gen: Generation, lookup: Binary.Lookup, options?: {
47
+ moves?: number;
48
+ items?: number;
49
+ }): {
50
+ species: number;
51
+ moves: number;
52
+ items: number;
53
+ stats: number;
54
+ };
55
+ compute(gen: Generation, lookup: Binary.Lookup, db: Buffer, options: {
56
+ cutoff: number;
57
+ }): void;
58
+ encode(gen: Generation, lookup: Binary.Lookup, stats: Binary.Statistics, options: {
59
+ moves: number;
60
+ items: number;
61
+ }): Buffer;
62
+ moveByID(lookup: Binary.Lookup, move: ID): number;
63
+ moveByNum(lookup: Binary.Lookup, num: number): ID;
64
+ };
65
+ Display: {
66
+ pokemon(gen: Generation, lookup: Binary.Lookup, db: Buffer, options: {
67
+ moves: number;
68
+ items: number;
69
+ }): Binary.DisplayStatistics;
70
+ };
71
+ };
72
+ export declare namespace Binary {
73
+ interface Lookup {
74
+ sizes: {
75
+ types: number;
76
+ species: number;
77
+ moves: number;
78
+ items: number;
79
+ };
80
+ typeByNum(num: number): TypeName;
81
+ typeByName(name: TypeName): number;
82
+ speciesByNum(num: number): ID;
83
+ speciesByID(id: ID | undefined): number;
84
+ moveByNum(num: number): ID;
85
+ moveByID(id: ID | undefined): number;
86
+ itemByNum(num: number): ID;
87
+ itemByID(id: ID | undefined): number;
88
+ }
89
+ interface Data {
90
+ timestamp: bigint;
91
+ turns: number;
92
+ endType: EndType;
93
+ winner: {
94
+ team: Array<Partial<PokemonSet>>;
95
+ rating?: {
96
+ rpr: number;
97
+ rprd: number;
98
+ };
99
+ };
100
+ loser: {
101
+ team: Array<Partial<PokemonSet>>;
102
+ rating?: {
103
+ rpr: number;
104
+ rprd: number;
105
+ };
106
+ };
107
+ }
108
+ interface Statistics {
109
+ total: {
110
+ lead: number;
111
+ usage: number;
112
+ };
113
+ species: number[];
114
+ species_lead: number[];
115
+ move_species: {
116
+ [num: number]: number;
117
+ }[];
118
+ item_species: {
119
+ [num: number]: number;
120
+ }[];
121
+ species_species: number[][];
122
+ move_move: number[][];
123
+ }
124
+ interface DisplayStatistics {
125
+ [id: string]: {
126
+ usage: number;
127
+ lead: number;
128
+ moves: {
129
+ [id: string]: number;
130
+ };
131
+ items?: {
132
+ [id: string]: number;
133
+ };
134
+ };
135
+ }
136
+ }
137
+ export {};
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Binary = void 0;
4
+ const data_1 = require("@pkmn/data");
5
+ const util_1 = require("./util");
6
+ const LE = (() => {
7
+ const u8 = new Uint8Array(4);
8
+ const u16 = new Uint16Array(u8.buffer);
9
+ return !!((u16[0] = 1) & u16[0]);
10
+ })();
11
+ const Read = new class {
12
+ u8(buf, offset) {
13
+ return buf.readUInt8(offset);
14
+ }
15
+ u16(buf, offset) {
16
+ return LE ? buf.readUInt16LE(offset) : buf.readUInt16BE(offset);
17
+ }
18
+ u32(buf, offset) {
19
+ return LE ? buf.readUInt32LE(offset) : buf.readUInt32BE(offset);
20
+ }
21
+ u64(buf, offset) {
22
+ return LE ? buf.readBigInt64LE(offset) : buf.readBigInt64BE(offset);
23
+ }
24
+ };
25
+ const Write = new class {
26
+ u8(buf, value, offset) {
27
+ return buf.writeUInt8(offset);
28
+ }
29
+ u16(buf, value, offset) {
30
+ return LE ? buf.writeUInt16LE(value, offset) : buf.writeUInt16BE(value, offset);
31
+ }
32
+ u32(buf, value, offset) {
33
+ return LE ? buf.writeUInt32LE(value, offset) : buf.writeUInt32BE(value, offset);
34
+ }
35
+ u64(buf, value, offset) {
36
+ return LE ? buf.writeBigInt64LE(BigInt(value), offset)
37
+ : buf.writeBigInt64BE(BigInt(value), offset);
38
+ }
39
+ };
40
+ const Sizes = { 1: 5, 2: 7, 3: 24, 4: 24, 5: 24, 6: 25, 7: 26, 8: 25 };
41
+ const Team = new class {
42
+ encode(gen, lookup, team, buf, offset = 0) {
43
+ switch (gen.num) {
44
+ case 1: {
45
+ for (const set of team) {
46
+ Write.u8(buf, lookup.speciesByID(set.species), offset++);
47
+ for (let i = 0; i < 4; i++) {
48
+ Write.u8(buf, i < set.moves.length ? lookup.moveByID(set.moves[i]) : 0, offset++);
49
+ }
50
+ }
51
+ return offset;
52
+ }
53
+ case 2: {
54
+ for (const set of team) {
55
+ Write.u8(buf, lookup.speciesByID(set.species), offset++);
56
+ Write.u8(buf, set.item ? lookup.itemByID(set.item) : 0, offset++);
57
+ let type = 'Normal';
58
+ for (let i = 0; i < 4; i++) {
59
+ let move = set.moves[i];
60
+ if (set.moves[i].startsWith('hiddenpower')) {
61
+ move = 'hiddenpower';
62
+ type = (move.charAt(11).toUpperCase() + move.slice(12));
63
+ }
64
+ Write.u8(buf, i < set.moves.length ? lookup.moveByID(move) : 0, offset++);
65
+ }
66
+ Write.u8(buf, lookup.typeByName(type), offset++);
67
+ }
68
+ return offset;
69
+ }
70
+ default: throw new Error(`Unsupported gen ${gen.num}}`);
71
+ }
72
+ }
73
+ decode(gen, lookup, buf, offset = 0) {
74
+ const team = [];
75
+ const N = Sizes[gen.num];
76
+ let byte = 0;
77
+ switch (gen.num) {
78
+ case 1: {
79
+ for (let i = offset; i < offset + 6 * N; i += N) {
80
+ byte = Read.u8(buf, i);
81
+ if (!byte)
82
+ return team;
83
+ const set = {};
84
+ set.species = lookup.speciesByNum(byte);
85
+ set.moves = [];
86
+ for (let j = 0; j < 4; j++) {
87
+ byte = Read.u8(buf, i + 1 + j);
88
+ if (!byte)
89
+ break;
90
+ set.moves.push(lookup.moveByNum(byte));
91
+ }
92
+ team.push(set);
93
+ }
94
+ return team;
95
+ }
96
+ case 2: {
97
+ for (let i = offset; i < offset + 6 * N; i += N) {
98
+ byte = Read.u8(buf, i);
99
+ if (!byte)
100
+ return team;
101
+ const set = {};
102
+ set.species = lookup.speciesByNum(byte);
103
+ byte = Read.u8(buf, i + 1);
104
+ set.item = byte ? lookup.itemByNum(byte) : undefined;
105
+ set.moves = [];
106
+ for (let j = 0; j < 4; j++) {
107
+ byte = Read.u8(buf, i + 2 + j);
108
+ if (!byte)
109
+ break;
110
+ const move = lookup.moveByNum(byte);
111
+ set.moves.push(move === 'hiddenpower'
112
+ ? `${move}${(0, data_1.toID)(lookup.typeByNum(Read.u8(buf, i + 6)))}`
113
+ : move);
114
+ }
115
+ team.push(set);
116
+ }
117
+ return team;
118
+ }
119
+ default: throw new Error(`Unsupported gen ${gen.num}`);
120
+ }
121
+ }
122
+ };
123
+ const Log = new class {
124
+ encode(gen, lookup, canonicalize, log, buf, offset = 0) {
125
+ if (gen.num >= 3)
126
+ throw new Error(`Unsupported gen ${gen.num}`); // TODO
127
+ Write.u64(buf, new Date(log.timestamp).getTime(), offset);
128
+ Write.u16(buf, log.turns, offset + 8);
129
+ const winner = log.winner === log.p2 ? 'p2' : 'p1';
130
+ const loser = winner === 'p1' ? 'p2' : 'p1';
131
+ let endType = 0 /* EndType.NORMAL */;
132
+ if (!log.winner || log.winner === 'tie') {
133
+ endType = 1 /* EndType.TIE */;
134
+ }
135
+ if (log.endType === 'forced') {
136
+ endType = endType === 0 /* EndType.NORMAL */ ? 3 /* EndType.FORCED_WIN */ : 4 /* EndType.FORCED_TIE */;
137
+ }
138
+ else if (log.endType === 'forfeit') {
139
+ endType = 2 /* EndType.FORFEIT */;
140
+ }
141
+ Write.u8(buf, endType, offset + 10);
142
+ if (log[`${winner}rating`]) {
143
+ Write.u16(buf, Math.round(log[`${winner}rating`].rpr), offset + 11);
144
+ Write.u8(buf, Math.round(log[`${winner}rating`].rprd), offset + 13);
145
+ }
146
+ if (log[`${loser}rating`]) {
147
+ Write.u16(buf, Math.round(log[`${loser}rating`].rpr), offset + 14);
148
+ Write.u8(buf, Math.round(log[`${loser}rating`].rprd), offset + 16);
149
+ }
150
+ const N = 6 * Sizes[gen.num];
151
+ Team.encode(gen, lookup, canonicalize(log[`${winner}team`], gen.dex), buf, offset + 17);
152
+ Team.encode(gen, lookup, canonicalize(log[`${loser}team`], gen.dex), buf, offset + 17 + N);
153
+ return buf;
154
+ }
155
+ decode(gen, lookup, buf, offset = 0) {
156
+ if (gen.num >= 3)
157
+ throw new Error(`Unsupported gen ${gen.num}`); // TODO
158
+ const N = 6 * Sizes[gen.num];
159
+ const data = {
160
+ timestamp: BigInt(0),
161
+ turns: 0,
162
+ endType: 0 /* EndType.NORMAL */,
163
+ winner: {
164
+ team: undefined,
165
+ rating: undefined,
166
+ },
167
+ loser: {
168
+ team: undefined,
169
+ rating: undefined,
170
+ },
171
+ };
172
+ data.timestamp = Read.u64(buf, offset);
173
+ data.turns = Read.u16(buf, offset + 8);
174
+ data.endType = Read.u8(buf, offset + 10);
175
+ let byte = Read.u16(buf, offset + 11);
176
+ if (byte)
177
+ data.winner.rating = { rpr: byte, rprd: Read.u8(buf, offset + 13) };
178
+ byte = Read.u16(buf, offset + 14);
179
+ if (byte)
180
+ data.loser.rating = { rpr: byte, rprd: Read.u8(buf, offset + 16) };
181
+ data.winner.team = Team.decode(gen, lookup, buf, offset + 17);
182
+ data.loser.team = Team.decode(gen, lookup, buf, offset + 17 + N);
183
+ return data;
184
+ }
185
+ };
186
+ const HP_TYPE_TO_NUM = {
187
+ fighting: 0, flying: 1, poison: 2, ground: 3, rock: 4, bug: 5, ghost: 6, steel: 7,
188
+ fire: 8, water: 9, grass: 10, electric: 11, psychic: 12, ice: 13, dragon: 14, dark: 15,
189
+ };
190
+ const NUM_TO_HP_TYPE = Object.values(HP_TYPE_TO_NUM);
191
+ const Stats = new class {
192
+ sizes(gen, lookup, options) {
193
+ const species = lookup.sizes.species;
194
+ const moves = lookup.sizes.moves + (gen.num < 2 ? 0 : 16);
195
+ const items = gen.num < 2 ? 0 : lookup.sizes.items + 1;
196
+ const stats = options
197
+ ? (species * 2) + (species * 2) +
198
+ (species * options.moves * 3) +
199
+ (gen.num >= 2 ? species * options.items * 3 : 0)
200
+ // (species * species * 2);
201
+ : -1;
202
+ return { species, moves, items, stats };
203
+ }
204
+ compute(gen, lookup, db, options) {
205
+ const sizes = this.sizes(gen, lookup);
206
+ const stats = {
207
+ total: { lead: 0, usage: 0 },
208
+ species: new Array(sizes.species),
209
+ species_lead: new Array(sizes.species),
210
+ move_species: new Array(sizes.species),
211
+ item_species: new Array(sizes.species),
212
+ species_species: new Array(sizes.species),
213
+ move_move: new Array(sizes.moves),
214
+ };
215
+ for (let i = 0; i < sizes.species; i++) {
216
+ stats.species[i] = 0;
217
+ stats.species_lead[i] = 0;
218
+ stats.move_species[i] = {};
219
+ stats.item_species[i] = {};
220
+ stats.species_species[i] = new Array(sizes.species);
221
+ for (let j = 0; j < sizes.species; j++) {
222
+ stats.species_species[i][j] = 0;
223
+ }
224
+ }
225
+ for (let i = 0; i < sizes.moves; i++) {
226
+ stats.move_move[i] = new Array(sizes.moves);
227
+ for (let j = 0; j < sizes.moves; j++) {
228
+ stats.move_move[i][j] = 0;
229
+ }
230
+ }
231
+ const N = 6 * Sizes[gen.num];
232
+ const row = 17 + 2 * N;
233
+ if (db.length % row !== 0) {
234
+ throw new Error(`Corrupted logs database of size ${db.length} (${row})`);
235
+ }
236
+ for (let offset = 0; offset < db.length; offset += row) {
237
+ const data = Log.decode(gen, lookup, db, offset);
238
+ for (const player of [data.winner, data.loser]) {
239
+ if (!player.rating)
240
+ continue;
241
+ const weight = (0, util_1.weighting)(player.rating.rpr, player.rating.rprd, options.cutoff);
242
+ if (!weight)
243
+ continue;
244
+ for (const [index, set] of player.team.entries()) {
245
+ const s = lookup.speciesByID(set.species) - 1;
246
+ stats.species[s] += weight;
247
+ stats.total.usage += weight;
248
+ // FIXME track average team size so dont just naively multiply by 6
249
+ if (index === 0) {
250
+ stats.species_lead[s] += weight;
251
+ stats.total.lead += weight;
252
+ }
253
+ // FIXME non lead
254
+ for (let j = 0; j < index; j++) {
255
+ const t = lookup.speciesByID(player.team[j].species) - 1;
256
+ stats.species_species[s][t] = (stats.species_species[t][s] += weight);
257
+ }
258
+ for (const move of set.moves) {
259
+ const m = this.moveByID(lookup, move);
260
+ stats.move_species[s][m] = (stats.move_species[s][m] || 0) + weight;
261
+ }
262
+ if (gen.num >= 2) {
263
+ const i = set.item ? lookup.itemByID(set.item) : 0;
264
+ stats.item_species[s][i] = (stats.item_species[s][i] || 0) + weight;
265
+ }
266
+ }
267
+ }
268
+ }
269
+ }
270
+ encode(gen, lookup, stats, options) {
271
+ const sizes = this.sizes(gen, lookup);
272
+ const BY_VAL = (a, b) => b[1] - a[1];
273
+ let cursor = 0;
274
+ const buf = Buffer.alloc(sizes.stats);
275
+ for (let i = cursor; i < stats.species_lead.length; i++) {
276
+ Write.u16(buf, round(stats.species_lead[i] / stats.total.lead), i * 2);
277
+ }
278
+ cursor += sizes.species * 2;
279
+ // FIXME: want to track only NON lead statistics for other pokemon!
280
+ for (let i = cursor; i < stats.species.length; i++) {
281
+ Write.u16(buf, round((stats.species[i] / stats.total.usage) * 6), i * 2);
282
+ }
283
+ cursor += sizes.species * 2;
284
+ const n = gen.num < 2 ? 3 : 4;
285
+ const write = gen.num < 2 ? Write.u8 : Write.u16;
286
+ for (let i = cursor; i < stats.move_species.length; i++) {
287
+ const moves = Object.entries(stats.move_species[i]).sort(BY_VAL);
288
+ for (let j = 0; j < Math.min(moves.length, options.moves); j++) {
289
+ const [key, weight] = moves[j];
290
+ const offset = (i * options.moves * n) + (j * n);
291
+ write(buf, +key, offset);
292
+ Write.u16(buf, round(weight / stats.species[i]), offset + 1);
293
+ }
294
+ }
295
+ cursor += sizes.species * options.moves * n;
296
+ if (gen.num >= 2) {
297
+ for (let i = cursor; i < stats.item_species.length; i++) {
298
+ const items = Object.entries(stats.item_species[i]).sort(BY_VAL);
299
+ for (let j = 0; j < Math.min(items.length, options.items); j++) {
300
+ const [key, weight] = items[j];
301
+ const offset = (i * options.items * 3) + (j * 3);
302
+ Write.u8(buf, +key, offset);
303
+ Write.u16(buf, round(weight / stats.species[i]), offset + 1);
304
+ }
305
+ }
306
+ cursor += sizes.species * options.items * 3;
307
+ }
308
+ for (let i = cursor; i < sizes.species; i++) {
309
+ for (let j = 0; j < sizes.species; j++) {
310
+ const offset = (i * sizes.species) + (j * 2);
311
+ const weight = stats.species[i];
312
+ const w = stats.species_species[i][j];
313
+ const usage = (stats.species[j] / stats.total.usage) * 6;
314
+ Write.u16(buf, round((w - weight * usage) / weight), offset);
315
+ }
316
+ }
317
+ cursor += sizes.species * sizes.species * 2;
318
+ return buf;
319
+ }
320
+ moveByID(lookup, move) {
321
+ return (move.startsWith('hiddenpower')
322
+ ? lookup.sizes.moves + HP_TYPE_TO_NUM[move.slice(11)]
323
+ : lookup.moveByID(move));
324
+ }
325
+ moveByNum(lookup, num) {
326
+ return (num >= lookup.sizes.moves
327
+ ? `hiddenpower${NUM_TO_HP_TYPE[num]}`
328
+ : lookup.moveByNum(num));
329
+ }
330
+ };
331
+ const Display = new class {
332
+ pokemon(gen, lookup, db, options) {
333
+ const sizes = Stats.sizes(gen, lookup, options);
334
+ if (db.length !== sizes.stats) {
335
+ throw new Error(`Corrupted stats.db of size ${db.length} (${sizes.stats})`);
336
+ }
337
+ const pokemon = [];
338
+ for (let i = 0; i < sizes.species; i++) {
339
+ let offset = 0;
340
+ const id = lookup.speciesByNum(i + 1);
341
+ const lead = Read.u16(db, offset + (i * 2)) / 100;
342
+ offset += sizes.species * 2;
343
+ const nonlead = Read.u16(db, offset + (i * 2)) / 100;
344
+ offset += sizes.species * 2;
345
+ const usage = nonlead; // TODO: compute based on nonlead and lead!
346
+ const moves = {};
347
+ for (let j = 0; j < options.moves; j++) {
348
+ const off = offset + (i * options.moves * 3) + (j * 3);
349
+ const move = Read.u8(db, off);
350
+ if (move === 0)
351
+ break;
352
+ moves[Stats.moveByNum(lookup, move)] = Read.u16(db, off + 1) / 100;
353
+ }
354
+ offset += sizes.species * options.moves * 3;
355
+ let items = undefined;
356
+ if (gen.num >= 2) {
357
+ items = {};
358
+ for (let j = 0; j < options.moves; j++) {
359
+ const off = offset + (i * options.moves * 3) + (j * 3);
360
+ const item = Read.u8(db, off);
361
+ const val = Read.u16(db, off + 1);
362
+ if (item === 0 && val === 0)
363
+ break;
364
+ moves[lookup.itemByNum(item)] = val / 100;
365
+ }
366
+ offset += sizes.species * options.items * 3;
367
+ }
368
+ pokemon.push([id, { usage, lead, moves, items }]);
369
+ }
370
+ const stats = {};
371
+ for (const p of pokemon.sort((a, b) => b[1].usage - a[1].usage)) {
372
+ stats[p[0]] = p[1];
373
+ }
374
+ return stats;
375
+ }
376
+ };
377
+ function round(v, p = 1e4) {
378
+ return Math.round(v * p);
379
+ }
380
+ function bias(stats) {
381
+ const [first, second] = Object.entries(stats).sort((a, b) => b[1] - a[1]);
382
+ // TODO: convert this pair (eg. 'atkhp') to a number
383
+ return first[0] > second[0] ? [first[0], second[0]] : [second[0], first[0]];
384
+ }
385
+ exports.Binary = { Read, Write, Sizes, Log, Team, Stats, Display };
386
+ //# sourceMappingURL=binary.js.map