Repository navigation
Expand file tree
/
Copy pathSequiturVsRepairBench.java
More file actions
210 lines (192 loc) · 7.64 KB
/
Copy pathSequiturVsRepairBench.java
File metadata and controls
210 lines (192 loc) · 7.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import net.seninp.gi.logic.GrammarRuleRecord;
import net.seninp.gi.logic.GrammarRules;
import net.seninp.gi.repair.RePairFactory;
import net.seninp.gi.repair.RePairGrammar;
import net.seninp.gi.sequitur.SequiturFactory;
import net.seninp.grammarviz.anomaly.RRAImplementation;
import net.seninp.grammarviz.anomaly.RRAIntervalBuilder;
import net.seninp.jmotif.sax.NumerosityReductionStrategy;
import net.seninp.jmotif.sax.SAXProcessor;
import net.seninp.jmotif.sax.TSProcessor;
import net.seninp.jmotif.sax.alphabet.NormalAlphabet;
import net.seninp.jmotif.sax.datastructure.SAXRecords;
import net.seninp.jmotif.sax.discord.DiscordRecord;
import net.seninp.jmotif.sax.discord.DiscordRecords;
/**
* Informative Sequitur-vs-RePair comparison as RRA grammar backends (not conformance goldens).
* Both algorithms consume the identical single-threaded SAX discretization, so every reported
* difference is attributable to grammar induction alone. Emits one JSON object per (w,p,a) cell:
* grammar shape (rules, size proxy, hierarchy depth), inference wall-clock, and the RRA top
* discord each grammar leads to. A final entry reports a parallel-sweep timing for Sequitur —
* the capability unlocked by the de-static refactor.
*/
public class SequiturVsRepairBench {
static double[] series;
static double threshold = 0.01;
static long seed = 0L;
static int k = 3;
static class GrammarStats {
long inferMs;
int rules;
int sizeProxy;
int maxLevel;
String r0Head;
int topPos = -1;
double topNn = Double.NaN;
long rraMs;
}
static SAXRecords discretize(int w, int p, int a) throws Exception {
SAXProcessor sp = new SAXProcessor();
NormalAlphabet na = new NormalAlphabet();
SAXRecords sax = sp.ts2saxViaWindow(series, w, p, na.getCuts(a),
NumerosityReductionStrategy.EXACT, threshold);
sax.buildIndex();
return sax;
}
static GrammarRules inferSequitur(SAXRecords sax, int w, int p) throws Exception {
GrammarRules rules = SequiturFactory.runSequitur(sax.getSAXString(" ")).toGrammarRulesData();
SequiturFactory.updateRuleIntervals(rules, sax, true, series, w, p);
return rules;
}
static GrammarRules inferRepair(SAXRecords sax, int w) throws Exception {
RePairGrammar grammar = RePairFactory.buildGrammar(sax.getSAXString(" "));
grammar.expandRules();
grammar.buildIntervals(sax, series, w);
return grammar.toGrammarRulesData();
}
static GrammarStats measure(String algo, SAXRecords sax, int w, int p) throws Exception {
GrammarStats s = new GrammarStats();
long t0 = System.nanoTime();
GrammarRules rules = "sequitur".equals(algo) ? inferSequitur(sax, w, p)
: inferRepair(sax, w);
s.inferMs = (System.nanoTime() - t0) / 1_000_000;
s.rules = rules.size();
for (GrammarRuleRecord r : rules) {
if (r.ruleNumber() == 0) {
s.r0Head = r.getRuleString().trim();
if (s.r0Head.length() > 40) {
s.r0Head = s.r0Head.substring(0, 40) + "...";
}
continue;
}
s.sizeProxy += r.getRuleString().trim().split("\\s+").length;
if (r.getRuleLevel() > s.maxLevel) {
s.maxLevel = r.getRuleLevel();
}
}
long t1 = System.nanoTime();
DiscordRecords d = RRAImplementation.series2RRAAnomalies(series, k,
RRAIntervalBuilder.fromGrammarRules(rules, series.length), threshold, new Random(seed));
s.rraMs = (System.nanoTime() - t1) / 1_000_000;
if (d.getSize() > 0) {
DiscordRecord top = d.get(0);
s.topPos = top.getPosition();
s.topNn = top.getNNDistance();
}
return s;
}
static void emit(String label, int w, int p, int a, GrammarStats seq, GrammarStats rep) {
StringBuilder sb = new StringBuilder("{");
sb.append("\"label\":\"").append(label).append("\",\"w\":").append(w).append(",\"p\":")
.append(p).append(",\"a\":").append(a);
sb.append(",\"sequitur\":").append(json(seq)).append(",\"repair\":").append(json(rep));
sb.append(",\"same_top_discord\":")
.append(seq.topPos == rep.topPos && seq.topPos >= 0);
sb.append('}');
System.out.println(sb);
}
static String json(GrammarStats s) {
return "{\"infer_ms\":" + s.inferMs + ",\"rules\":" + s.rules + ",\"size_proxy\":"
+ s.sizeProxy + ",\"max_level\":" + s.maxLevel + ",\"rra_ms\":" + s.rraMs
+ ",\"top_pos\":" + s.topPos + ",\"top_nn\":" + s.topNn + "}";
}
/** Tiles a series to the requested length with a tiny per-copy drift (same recipe as
* RRAvsHotsaxBench) — keeps discords non-trivial while scaling the workload. */
static double[] tile(double[] base, int tileLength) {
if (tileLength <= base.length) {
return base;
}
double[] out = new double[tileLength];
double drift = 0.0;
for (int i = 0; i < tileLength; i++) {
if (i > 0 && i % base.length == 0) {
drift += 1e-4 * (i / base.length);
}
out[i] = base[i % base.length] + drift;
}
return out;
}
public static void main(String[] args) throws Exception {
Path repoRoot = Paths.get(".").toAbsolutePath().normalize();
String dataset = "ecg0606_1.csv";
Integer tileLength = null;
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--repo-root":
repoRoot = Paths.get(args[++i]).toAbsolutePath().normalize();
break;
case "--dataset":
dataset = args[++i];
break;
case "--tile-length":
tileLength = Integer.parseInt(args[++i]);
break;
default:
throw new IllegalArgumentException("unknown flag: " + args[i]);
}
}
series = TSProcessor.readFileColumn(
repoRoot.resolve("datasets").resolve(dataset).toString(), 0, 0);
if (tileLength != null) {
series = tile(series, tileLength);
}
int[][] grid = { { 100, 4, 4 }, { 120, 4, 4 }, { 100, 6, 4 }, { 120, 6, 6 }, { 160, 8, 4 },
{ 200, 8, 6 } };
for (int[] cell : grid) {
SAXRecords sax = discretize(cell[0], cell[1], cell[2]);
GrammarStats seq = measure("sequitur", sax, cell[0], cell[1]);
GrammarStats rep = measure("repair", sax, cell[0], cell[1]);
emit("grid", cell[0], cell[1], cell[2], seq, rep);
}
// parallel-sweep timing: the same grid, all Sequitur inferences at once (the de-static win)
long tSeq0 = System.nanoTime();
for (int[] cell : grid) {
SAXRecords sax = discretize(cell[0], cell[1], cell[2]);
inferSequitur(sax, cell[0], cell[1]);
}
long sequentialMs = (System.nanoTime() - tSeq0) / 1_000_000;
ExecutorService pool = Executors.newFixedThreadPool(grid.length);
try {
long tPar0 = System.nanoTime();
List<Future<GrammarRules>> futures = new ArrayList<Future<GrammarRules>>();
for (int[] cell : grid) {
final int w = cell[0];
final int p = cell[1];
final int a = cell[2];
futures.add(pool.submit(new Callable<GrammarRules>() {
public GrammarRules call() throws Exception {
return inferSequitur(discretize(w, p, a), w, p);
}
}));
}
for (Future<GrammarRules> f : futures) {
f.get();
}
long parallelMs = (System.nanoTime() - tPar0) / 1_000_000;
System.out.println("{\"label\":\"sweep\",\"sequitur_sequential_ms\":" + sequentialMs
+ ",\"sequitur_parallel_ms\":" + parallelMs + ",\"threads\":" + grid.length + "}");
}
finally {
pool.shutdownNow();
}
}
}