-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathPpmModel.java
More file actions
90 lines (63 loc) · 1.96 KB
/
Copy pathPpmModel.java
File metadata and controls
90 lines (63 loc) · 1.96 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
/*
* Reference arithmetic coding
*
* Copyright (c) Project Nayuki
* MIT License. See readme file.
* https://www.nayuki.io/page/reference-arithmetic-coding
*/
final class PpmModel {
/*---- Fields ----*/
public final int modelOrder;
private final int symbolLimit;
private final int escapeSymbol;
public final Context rootContext;
public final FrequencyTable orderMinus1Freqs;
/*---- Constructors ----*/
public PpmModel(int order, int symbolLimit, int escapeSymbol) {
if (!(order >= -1 && 0 <= escapeSymbol && escapeSymbol < symbolLimit))
throw new IllegalArgumentException();
this.modelOrder = order;
this.symbolLimit = symbolLimit;
this.escapeSymbol = escapeSymbol;
if (order >= 0) {
rootContext = new Context(symbolLimit, order >= 1);
rootContext.frequencies.increment(escapeSymbol);
} else
rootContext = null;
orderMinus1Freqs = new FlatFrequencyTable(symbolLimit);
}
/*---- Methods ----*/
public void incrementContexts(int[] history, int symbol) {
if (modelOrder == -1)
return;
if (!(history.length <= modelOrder && 0 <= symbol && symbol < symbolLimit))
throw new IllegalArgumentException();
Context ctx = rootContext;
ctx.frequencies.increment(symbol);
int i = 0;
for (int sym : history) {
Context[] subctxs = ctx.subcontexts;
if (subctxs == null)
throw new AssertionError();
if (subctxs[sym] == null) {
subctxs[sym] = new Context(symbolLimit, i + 1 < modelOrder);
subctxs[sym].frequencies.increment(escapeSymbol);
}
ctx = subctxs[sym];
ctx.frequencies.increment(symbol);
i++;
}
}
/*---- Helper structure ----*/
public static final class Context {
public final FrequencyTable frequencies;
public final Context[] subcontexts;
public Context(int symbols, boolean hasSubctx) {
frequencies = new SimpleFrequencyTable(new int[symbols]);
if (hasSubctx)
subcontexts = new Context[symbols];
else
subcontexts = null;
}
}
}