-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodecTools.py
More file actions
384 lines (293 loc) · 15.7 KB
/
Copy pathCodecTools.py
File metadata and controls
384 lines (293 loc) · 15.7 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""
CodecTools.py by John Dorsey.
CodecTools.py contains classes and other tools that might help make it easier to rapidly create and test codecs made from smaller codecs applied in stages.
"""
import traceback
import PyGenTools
from PyGenTools import makeArr, isGen, makeGen, ExhaustionError, genAddInt, arrAddInt
from PyArrTools import ljustedArr
from PyDictTools import augmentedDict
from IntDomains import simpleIntDomains
from TestingTools import printComparison
class ParseError(Exception):
pass
def roundTripTest(testCodec, plainData, useZeroSafeMethods=False, showDetails=False):
#test the input testCodec on testData to make sure that it is capable of reconstructing its original input. If it isn't, print additional information before returning False.
if isGen(plainData):
plainData = makeArr(plainData)
if type(plainData) == list:
if len(plainData) == 0:
print("CodecTools.roundTripTest: warning: plainData is empty.")
pressData = testCodec.zeroSafeEncode(plainData) if useZeroSafeMethods else testCodec.encode(plainData)
if isGen(pressData):
pressData = makeArr(pressData)
if type(pressData) == list:
if len(pressData) == 0:
print("CodecTools.roundTripTest: Warning: pressData is empty.")
if showDetails:
printComparison(plainData,pressData)
reconstPlainData = testCodec.zeroSafeDecode(pressData) if useZeroSafeMethods else testCodec.decode(pressData)
if isGen(reconstPlainData):
reconstPlainData = makeArr(reconstPlainData)
if type(reconstPlainData) == list:
if len(reconstPlainData) == 0:
print("CodecTools.roundTripTest: Warning: reconstPlainData is empty.")
result = (reconstPlainData == plainData)
if not result:
print("CodecTools.roundTripTest: Test failed.")
print("CodecTools.roundTripTest: testData is " + str(plainData) + " and reconstData is " + str(reconstPlainData) + ". pressData is " + str(pressData) + ".")
if type(plainData) == list and type(reconstPlainData) == list:
print("CodecTools.roundTripTest: Lengths " + ("do not" if len(reconstPlainData)==len(plainData) else "") + " differ.")
return result
class Codec:
def __init__(self, encodeFun, decodeFun, transcodeFun=None, zeroSafe=None, domain=None, extraArgs=None, extraKwargs=None):
#initialize transcoding functions:
self.encodeFun, self.decodeFun, self.transcodeFun = (encodeFun, decodeFun, transcodeFun)
if not (self.encodeFun or self.decodeFun or self.transcodeFun):
print("CodecTools.Codec.__init__: Warning: No functions for encoding, decoding, or transcoding were specified! They must be added manually before transcoding can take place!")
#initialize extra arguments:
self.extraArgs, self.extraKwargs = (extraArgs if extraArgs else [], extraKwargs if extraKwargs else {})
#initialize domain:
if zeroSafe != None:
print("CodecTools.Codec.__init__: Warning: initialization using the zeroSafe argument is deprecated. Please specify a domain instead. A domain will be assumed.")
domain = simpleIntDomains["UNSIGNED" if zeroSafe else "UNSIGNED_NONZERO"]
if domain == None:
#print("CodecTools.Codec.__init__: Warning: No domain was provided.")
#domain = simpleIntDomains["UNSIGNED"]
pass
elif type(domain) == str:
if domain not in simpleIntDomains.keys():
raise ValueError("the domain string argument is not a valid key for CodecTools.simpleIntDomains.")
domain = simpleIntDomains[domain]
self._domain = domain
#self.zeroSafe = (0 in self.domain) #remove soon.
def getDomain(self):
if self._domain == None:
raise AttributeError("No Codec domain was provided.")
return self._domain
def isZeroSafe(self):
#print("CodecTools.Codec.isZeroSafe: this method is deprecated.")
return 0 in self.getDomain()
def encode(self,data,*args,**kwargs):
if not (self.encodeFun or self.transcodeFun):
raise AttributeError("Either encodeFun or transcodeFun must be defined to decode.")
#argsToUse = args if args else self.extraArgs #a single extra argument specified when calling Codec.encode will override ALL stored values in Codec.extraArgs.
#kwargsToUse = kwargs if kwargs else self.extraKwargs #a single extra keyword argument specified when calling Codec.encode will override ALL stored values in Codec.extraKwargs.
if args and self.extraArgs:
print("CodecTools.Codec.encode: warning: some args may be excluded.")
argsToUse = args if args else self.extraArgs
kwargsToUse = augmentedDict(kwargs, self.extraKwargs)
if self.encodeFun:
return self.encodeFun(data,*argsToUse,**kwargsToUse)
else:
return self.transcodeFun(data,"encode",*argsToUse,**kwargsToUse)
def decode(self,data,*args,**kwargs):
if not (self.decodeFun or self.transcodeFun):
raise AttributeError("Either decodeFun or transcodeFun must be defined to decode.")
#argsToUse = args if args else self.extraArgs
#kwargsToUse = kwargs if kwargs else self.extraKwargs
if args and self.extraArgs:
print("CodecTools.Codec.encode: warning: some args may be excluded.")
argsToUse = args if args else self.extraArgs
kwargsToUse = augmentedDict(kwargs, self.extraKwargs)
if self.decodeFun:
return self.decodeFun(data,*argsToUse,**kwargsToUse)
else:
return self.transcodeFun(data,"decode",*argsToUse,**kwargsToUse)
def zeroSafeEncode(self,data,*args,**kwargs):
#will be replaced with domain comparisons soon.
if self.isZeroSafe():
dataToUse = data
#return self.encode(data,*args,**kwargs)
else:
maxInputInt = kwargs.get("maxInputInt",None)
if maxInputInt != None:
kwargs["maxInputInt"] = maxInputInt+1
if "seqSum" in kwargs:
print("CodecTools.zeroSafeEncode: warning: can't adjust seqSum.")
if type(data) == int:
#return self.encode(data+1,*args,**kwargs)
dataToUse = data+1
elif isGen(data):
#return self.encode(genAddInt(data,1),*args,**kwargs)
dataToUse = genAddInt(data,1)
elif type(data) == list:
#return self.encode(arrAddInt(data,1),*args,**kwargs)
dataToUse = arrAddInt(data,1)
else:
raise NotImplementedError("CodecTools.Codec.zeroSafeEncode can't handle data of this type.")
try:
return self.encode(dataToUse,*args,**kwargs)
except AssertionError as ae:
print("AssertionError encountered. Args were {}, kwargs were {}. Error will be re-raised.".format(args,kwargs))
print(traceback.format_exc())
raise ae
def zeroSafeDecode(self,data,*args,**kwargs):
#will be replaced with domain comparisons soon.
if not self.isZeroSafe():
maxInputInt = kwargs.get("maxInputInt",None)
if maxInputInt != None:
kwargs["maxInputInt"] = maxInputInt+1
if "seqSum" in kwargs:
print("CodecTools.zeroSafeDecode: warning: can't adjust seqSum.")
try:
result = self.decode(data,*args,**kwargs)
except AssertionError as ae:
print("AssertionError encountered. Args were {}, kwargs were {}. Error will be re-raised.".format(args,kwargs))
print(traceback.format_exc())
raise ae
if self.isZeroSafe():
return result
else:
if type(result) == int:
return result-1
elif isGen(result):
return genAddInt(result,-1)
elif type(result) == list:
return arrAddInt(result,-1)
else:
raise NotImplementedError("CodecTools.Codec.zeroSafeDecode can't handle data of this type.")
def clone(self,extraArgs=None,extraKwargs=None):
if self.extraArgs != [] and extraArgs != None:
print("CodecTools.Codec.clone: warning: some existing extraArgs will not be cloned.")
if self.extraKwargs != {} and extraKwargs != None:
print("CodecTools.Codec.clone: warning: some existing extraKwargs may not be cloned.")
argsToUse = extraArgs if extraArgs else self.extraArgs
kwargsToUse = augmentedDict(extraKwargs, self.extraKwargs)
return Codec(self.encodeFun, self.decodeFun, transcodeFun=self.transcodeFun, domain=self._domain, extraArgs=argsToUse, extraKwargs=kwargsToUse)
def makePlatformCodec(platCodec, mainCodec):
return Codec((lambda x: platCodec.encode(mainCodec.encode(platCodec.decode(x)))), (lambda y: platCodec.encode(mainCodec.decode(platCodec.decode(y)))))
def makePlainDataNumOffsetClone(mainCodec, offset): #used in MarkovTools.
return Codec((lambda x: mainCodec.encode(x+offset)), (lambda y: mainCodec.decode(y)-offset))
def makeChainedPairCodec(codec1,codec2):
return Codec((lambda x: codec2.encode(codec1.encode(x))), (lambda y: codec1.decode(codec2.decode(y))))
def makeSeqCodec(inputCodec,demoPlainData,zeroSafe):
demoEncodeInputType = type(demoPlainData)
demoPressData = inputCodec.encode(demoPlainData)
demoEncodeOutputType = type(demoPressData)
#demoReconstPlainData = inputCodec.decode(demoPressData)
#demoDecodeOutputType = type(demoReconstPlainData)
newEncodeFun = None
if demoEncodeInputType == int:
if demoEncodeOutputType == int:
def newEncodeFun(encodeInputSeq):
encodeInputSeq = makeGen(encodeInputSeq)
for encodeInputSeqItem in encodeInputSeq:
yield inputCodec.encode(encodeInputSeqItem)
elif demoEncodeOutputType == list or demoEncodeOutputType == type((i for i in range(10))):
def newEncodeFun(encodeInputSeq):
encodeInputSeq = makeGen(encodeInputSeq)
for encodeInputSeqItem in encodeInputSeq:
for encodeOutputBit in inputCodec.encode(encodeInputSeqItem):
yield encodeOutputBit
else:
raise NotImplementedError("demoEncodeOutputType is not acceptable.")
else:
raise NotImplementedError("demoEncodeInputType is not acceptable.")
newDecodeFun = None
if demoEncodeOutputType == int:
def newDecodeFun(decodeInputSeq):
decodeInputSeq = makeGen(decodeInputSeq)
for decodeInputSeqItem in decodeInputSeq:
yield inputCodec.decode(decodeInputSeqItem)
elif demoEncodeOutputType == list or demoEncodeOutputType == type((i for i in range(10))):
def newDecodeFun(decodeInputSeq):
decodeInputSeq = makeGen(decodeInputSeq)
while True:
try:
yield inputCodec.decode(decodeInputSeq)
except ExhaustionError:
return
else:
raise NotImplementedError("demoEncodeOutputType is not acceptable.")
result = Codec(newEncodeFun,newDecodeFun,zeroSafe=zeroSafe)
return result
def genConcatenatedElements(sourcesArr): #used only by makeUnlimitedNumCodecWithEscapeCode.
for source in sourcesArr:
if type(source) == list or isGen(source):
for outputElement in source:
yield outputElement
else:
yield source
def remapToOutsideValueArrTranscode(inputValue,opMode,predictedValues): #used in CodecTools and MarkovTools.
if opMode == "encode":
return inputValue - len([predictedValue for predictedValue in predictedValues if predictedValue < inputValue])
elif opMode == "decode":
return inputValue + len([predictedValue for predictedValue in predictedValues if predictedValue < inputValue])
else:
assert False, "invalid opMode."
def remapToValueArrTranscode(inputValue,opMode,predictedValues):
if opMode not in ["encode","decode"]:
raise ValueError("invalid opMode.")
if opMode == "encode":
if inputValue in predictedValues:
resultValue = predictedValues.index(inputValue)
else:
resultValue = remapToOutsideValueArrTranscode(inputValue,opMode,predictedValues) + len(predictedValues)
elif opMode == "decode":
if inputValue < len(predictedValues):
resultValue = predictedValues[inputValue]
else:
resultValue = remapToOutsideValueArrTranscode(inputValue,opMode,predictedValues) - len(predictedValues)
else:
assert False, "reality error."
return resultValue
remapToValueArrCodec = Codec(None,None,transcodeFun=remapToValueArrTranscode)
def makeUnlimitedNumCodecWithSelectionBit(inputLimitedNumCodec,inputUnlimitedNumCodec):
if not inputLimitedNumCodec.isZeroSafe():
print("CodecTools.makeUnlimitedNumCodecWithSelectionBit: warning: inputLimitedNumCodec is not zero safe, which may reduce CR.")
#for i in range(1,len(inputLimitedNumCodec.getDomain())):
# assert abs(inputLimitedNumCodec.getDomain()[i]-inputLimitedNumCodec.getDomain()[i-1]) == 1, "non-contiguous inputLimitedNumCodec domains are not yet supported."
def newEncodeFun(newEncInput):
if newEncInput in inputLimitedNumCodec.getDomain():
return genConcatenatedElements([0,inputLimitedNumCodec.zeroSafeEncode(newEncInput)])
else:
return genConcatenatedElements([1,inputUnlimitedNumCodec.zeroSafeEncode(remapToOutsideValueArrTranscode(newEncInput,"encode",inputLimitedNumCodec.getDomain()))])
def newDecodeFun(newDecInput):
newDecInput = makeGen(newDecInput)
selectionBit = None
try:
selectionBit = next(newDecInput)
except StopIteration:
raise ExhaustionError("CodecTools.makeUnlimitedNumCodecWithSelectionBit-made-CodecTools.Codec: newDecodeFun: Received an empty newDecInput.")
if selectionBit == 0:
return inputLimitedNumCodec.zeroSafeDecode(newDecInput)
elif selectionBit == 1:
valueBeforeRemapping = inputUnlimitedNumCodec.zeroSafeDecode(newDecInput)
return remapToOutsideValueArrTranscode(valueBeforeRemapping,"decode",inputLimitedNumCodec.getDomain())
else:
raise ParseError("CodecTools.makeUnlimitedNumCodecWithSelectionBit-made-CodecTools.Codec: newDecodeFun: Received an invalid selection bit with the value " + str(selectionBit) + ".")
result = Codec(newEncodeFun,newDecodeFun,domain="UNSIGNED")
return result
def makeUnlimitedNumCodecWithEscapeCode(inputLimitedNumCodec,inputUnlimitedNumCodec,escapeCode):
if not inputLimitedNumCodec.isZeroSafe():
print("CodecTools.makeUnlimitedNumCodecWithSelectionBit: warning: inputLimitedNumCodec is not zero safe, which may reduce CR.")
assert escapeCode in inputLimitedNumCodec.getDomain()
noEscapeDomain = [item for item in inputLimitedNumCodec.getDomain() if item != escapeCode] #@ slow. Slow to search through later.
storableWithoutEscape = (lambda x: x in inputLimitedNumCodec.getDomain() and x != escapeCode)
def newEncodeFun(newEncInput):
if storableWithoutEscape(newEncInput):
return genConcatenatedElements([inputLimitedNumCodec.zeroSafeEncode(newEncInput)])
else:
return genConcatenatedElements([inputLimitedNumCodec.zeroSafeEncode(escapeCode), inputUnlimitedNumCodec.zeroSafeEncode(remapToOutsideValueArrTranscode(newEncInput, "encode", noEscapeDomain))])
def newDecodeFun(newDecInput):
newDecInput = makeGen(newDecInput)
limitedResult = inputLimitedNumCodec.zeroSafeDecode(newDecInput)
if limitedResult != escapeCode:
return limitedResult
else:
valueBeforeRemapping = inputUnlimitedNumCodec.zeroSafeDecode(newDecInput)
return remapToOutsideValueArrTranscode(valueBeforeRemapping,"decode",noEscapeDomain)
result = Codec(newEncodeFun,newDecodeFun,domain="UNSIGNED")
return result
bitSeqToStrCodec = Codec((lambda x: "".join(str(item) for item in x)),(lambda x: [int(char) for char in x]))
def bitSeqToBytearray(inputBitSeq):
return bytearray(int("".join(str(bit) for bit in ljustedArr(subSeq,8,fillItem=0)), 2) for subSeq in PyGenTools.genChunksAsLists(inputBitSeq, n=8, partialChunkHandling="warn partial"))
def bytearrayToBitSeq(inputBytearray):
raise NotImplementedError()
bitSeqToBytearrayCodec = Codec(bitSeqToBytearray, bytearrayToBitSeq, domain=range(0,256)) #@ might break in python3
#tests:
get_delimitedStr_codec = lambda delimiter: Codec((lambda x: delimiter.join(x)),(lambda x: x.split(delimiter)))
assert get_delimitedStr_codec("&").encode(["hello","world!"]) == "hello&world!"
assert get_delimitedStr_codec("&").decode("hello&world!") == ["hello","world!"]
del get_delimitedStr_codec