forked from Chia-Network/chiapos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
encoding.hpp
245 lines (206 loc) · 7.46 KB
/
encoding.hpp
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2018 Chia Network Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SRC_CPP_ENCODING_HPP_
#define SRC_CPP_ENCODING_HPP_
#include <cmath>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "../lib/FiniteStateEntropy/lib/fse.h"
#include "../lib/FiniteStateEntropy/lib/hist.h"
#include "../lib/FiniteStateEntropy/lib/error_public.h"
#include "bits.hpp"
#include "exceptions.hpp"
#include "util.hpp"
#include <mutex>
class TMemoCache {
public:
~TMemoCache()
{
// Clean up global entries on destruction
std::map<double, FSE_CTable *>::iterator itc;
for (itc = CT_MEMO.begin(); itc != CT_MEMO.end(); itc++) {
FSE_freeCTable(itc->second);
}
std::map<double, FSE_DTable *>::iterator itd;
for (itd = DT_MEMO.begin(); itd != DT_MEMO.end(); itd++) {
FSE_freeDTable(itd->second);
}
}
bool CTExists(double R)
{
std::lock_guard<std::mutex> l(memoMutex);
return (CT_MEMO.find(R) != CT_MEMO.end());
}
bool DTExists(double R)
{
std::lock_guard<std::mutex> l(memoMutex);
return (DT_MEMO.find(R) != DT_MEMO.end());
}
void CTAssign(double R, FSE_CTable *ct)
{
std::lock_guard<std::mutex> l(memoMutex);
CT_MEMO[R] = ct;
}
void DTAssign(double R, FSE_DTable *dt)
{
std::lock_guard<std::mutex> l(memoMutex);
DT_MEMO[R] = dt;
}
FSE_CTable *CTGet(double R)
{
std::lock_guard<std::mutex> l(memoMutex);
return CT_MEMO[R];
}
FSE_DTable *DTGet(double R)
{
std::lock_guard<std::mutex> l(memoMutex);
return DT_MEMO[R];
}
private:
mutable std::mutex memoMutex; // Mutex to ensure map thread safety
std::map<double, FSE_CTable *> CT_MEMO;
std::map<double, FSE_DTable *> DT_MEMO;
};
TMemoCache tmCache;
class Encoding {
public:
// Calculates x * (x-1) / 2. Division is done before multiplication.
static uint128_t GetXEnc(uint64_t x)
{
uint64_t a = x, b = x - 1;
if (a % 2 == 0)
a /= 2;
else
b /= 2;
return (uint128_t)a * b;
}
// Encodes two max k bit values into one max 2k bit value. This can be thought of
// mapping points in a two dimensional space into a one dimensional space. The benefits
// of this are that we can store these line points efficiently, by sorting them, and only
// storing the differences between them. Representing numbers as pairs in two
// dimensions limits the compression strategies that can be used.
// The x and y here represent table positions in previous tables.
static uint128_t SquareToLinePoint(uint64_t x, uint64_t y)
{
// Always makes y < x, which maps the random x, y points from a square into a
// triangle. This means less data is needed to represent y, since we know it's less
// than x.
if (y > x) {
std::swap(x, y);
}
return GetXEnc(x) + y;
}
// Does the opposite as the above function, deterministicaly mapping a one dimensional
// line point into a 2d pair. However, we do not recover the original ordering here.
static std::pair<uint64_t, uint64_t> LinePointToSquare(uint128_t index)
{
// Performs a square root, without the use of doubles, to use the precision of the
// uint128_t.
uint64_t x = 0;
for (int8_t i = 63; i >= 0; i--) {
uint64_t new_x = x + ((uint64_t)1 << i);
if (GetXEnc(new_x) <= index)
x = new_x;
}
return std::pair<uint64_t, uint64_t>(x, index - GetXEnc(x));
}
static std::vector<short> CreateNormalizedCount(double R)
{
std::vector<double> dpdf;
int N = 0;
double E = 2.718281828459;
double MIN_PRB_THRESHOLD = 1e-50;
int TOTAL_QUANTA = 1 << 14;
double p = 1 - pow((E - 1) / E, 1.0 / R);
while (p > MIN_PRB_THRESHOLD && N < 255) {
dpdf.push_back(p);
N++;
p = (pow(E, 1.0 / R) - 1) * pow(E - 1, 1.0 / R);
p /= pow(E, ((N + 1) / R));
}
std::vector<short> ans(N, 1);
auto cmp = [&dpdf, &ans](int i, int j) {
return dpdf[i] * (log2(ans[i] + 1) - log2(ans[i])) <
dpdf[j] * (log2(ans[j] + 1) - log2(ans[j]));
};
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
for (int i = 0; i < N; ++i) pq.push(i);
for (int todo = 0; todo < TOTAL_QUANTA - N; ++todo) {
int i = pq.top();
pq.pop();
ans[i]++;
pq.push(i);
}
for (int i = 0; i < N; ++i) {
if (ans[i] == 1) {
ans[i] = (short)-1;
}
}
return ans;
}
static size_t ANSEncodeDeltas(std::vector<unsigned char> deltas, double R, uint8_t *out)
{
if (!tmCache.CTExists(R)) {
std::vector<short> nCount = Encoding::CreateNormalizedCount(R);
unsigned maxSymbolValue = nCount.size() - 1;
unsigned tableLog = 14;
if (maxSymbolValue > 255)
throw std::invalid_argument("maxSymbolValue > 255");
FSE_CTable *ct = FSE_createCTable(maxSymbolValue, tableLog);
size_t err = FSE_buildCTable(ct, nCount.data(), maxSymbolValue, tableLog);
if (FSE_isError(err)) {
throw InvalidStateException(FSE_getErrorName(err));
}
tmCache.CTAssign(R, ct);
}
FSE_CTable *ct = tmCache.CTGet(R);
return FSE_compress_usingCTable(
out, deltas.size() * 8, static_cast<void *>(deltas.data()), deltas.size(), ct);
}
static void ANSFree(double R)
{
// Cache all entries, only free on close
}
static std::vector<uint8_t> ANSDecodeDeltas(
const uint8_t *inp,
size_t inp_size,
int numDeltas,
double R)
{
if (!tmCache.DTExists(R)) {
std::vector<short> nCount = Encoding::CreateNormalizedCount(R);
unsigned maxSymbolValue = nCount.size() - 1;
unsigned tableLog = 14;
FSE_DTable *dt = FSE_createDTable(tableLog);
size_t err = FSE_buildDTable(dt, nCount.data(), maxSymbolValue, tableLog);
if (FSE_isError(err)) {
throw InvalidStateException(FSE_getErrorName(err));
}
tmCache.DTAssign(R, dt);
}
FSE_DTable *dt = tmCache.DTGet(R);
std::vector<uint8_t> deltas(numDeltas);
size_t err = FSE_decompress_usingDTable(&deltas[0], numDeltas, inp, inp_size, dt);
if (FSE_isError(err)) {
throw InvalidStateException(FSE_getErrorName(err));
}
for (uint32_t i = 0; i < deltas.size(); i++) {
if (deltas[i] == 0xff) {
throw InvalidStateException("Bad delta detected");
}
}
return deltas;
}
};
#endif // SRC_CPP_ENCODING_HPP_