-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.py
executable file
·197 lines (151 loc) · 10 KB
/
encode.py
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
#!/usr/bin/env python3
import os
import random
import math
import numpy as np
import gzip
import json
import argparse
import time
"""
RATIONALE: A fountain code is a type of encoding process that allows the original data to be recovered from sufficiently
large subsets of the encoded data. This property makes them highly desirable in hostile network environments, and thus
perfect for use in space.
https://en.wikipedia.org/wiki/Fountain_code
Arguably the most easily understandable method of encoding blocks involves combining them with the bitwise exclusive-or
operation. This is the foundation of a subclass of fountain codes called Luby transform (LT) codes. The exact methods of
encoding and decoding used by LT codes are fairly standardized and agreed upon, and this software prototype attempts to
implement those methods.
https://en.wikipedia.org/wiki/Luby_transform_code
More advanced and efficient subclasses of fountain code exist, such as Raptor codes, but as most of our research has
been focused on LT fountain codes, the prototype software below uses their methodology instead.
Implementations studied during research for this project those by:
Anson Rosenthal (anrosent): https://github.com/anrosent/LT-Code
Darren (darrenldl): https://github.com/darrenldl/ocaml-lt-code
Spriteware: https://github.com/Spriteware/lt-codes-python
Roberto Francescon (obolo) and Dominik Danelski (Etua): https://github.com/obolo/freeRaptor
Daniel Chang (mwdchang): https://github.com/mwdchang/fountain-code
Aman Tiwari: https://observablehq.com/@aman-tiwari/fountain-codes
ASSUMPTIONS:
This encoder assumes that HDTN has a way of designating ordering information with bundles when it creates them.
This encoder does not add any ordering information in its current iteration.
"""
def ideal_soliton(k):
# The soliton probability distributions are designed to account for transmission errors by intelligently introducing
# redundancy. Michael Luby, the namesake of Luby transform (LT) codes, is also the mastermind behind this algorithm.
# A more robust version of this distribution exists and could be implemented later.
# https://en.wikipedia.org/wiki/Erasure_code
# https://en.wikipedia.org/wiki/Soliton_distribution
dist = [0, 1 / k]
for i in range(2, k + 1):
dist.append(1 / (i * (i - 1)))
return dist
def encode(bundles, original_size, encoded_size):
# Start by obtaining an ideal soliton probability distribution that will be used to generate xor neighbor values
# later.
ideal_dist = ideal_soliton(original_size)
xor_possibilities = []
for i in range(0, original_size + 1):
xor_possibilities.append(i)
# Encode data by cycling through our bundles and XORing them together to create encoded bundles. These bundles
# consist of an index number "index", the XORing result "value", an empty list of "components" to be used later,
# and the block's number of XOR neighbors "to_solve".
encoded_data = []
# Randomly choosing a number of xor neighbors, even from a probability distribution, will likely lead to
# unsolvable encoding, so to ensure that the encoding is solvable, we start by creating a bundle with one xor
# neighbor. In this way, the xor neighbors distribution is slightly less ideal, but it is far more important
# that the encoded data is solvable.
xor_neighbors = np.random.choice(xor_possibilities, size=(encoded_size - 1), p=ideal_dist).tolist()
# cur_xor_neighbors = np.random.choice(xor_possibilities, size=1, p=ideal_dist).tolist()[0]
xor_neighbors.append(1)
for cur_xor_neighbors in xor_neighbors:
components = random.sample(range(original_size), cur_xor_neighbors)
cur_encode = bundles[components[0]]
for j in range(1, cur_xor_neighbors):
cur_encode = cur_encode ^ bundles[components[j]]
encoded_data.append(dict(value=cur_encode, components=components))
return encoded_data
def main():
print("<encoder> setting up...")
parser = argparse.ArgumentParser(description="Fountain code encoder for use with NASA's HDTN")
parser.add_argument("input_filename", help="Input file/directory path")
parser.add_argument("output_directory", help="Output directory path")
parser.add_argument("-b", "--bytes", help="Number of bytes per bundle >= 8", default=65536, type=int)
parser.add_argument("-r", "--redundancy",
help="Scalar for the encoded data's size >= 1.3; higher values will increase loss tolerance as well as file size",
default=2.0, type=float)
parser.add_argument("-tlp", "--transmission-loss-percentage", help="Simulate transmission loss; percentage from 0 to 100",
default=0.0, type=float)
parser.add_argument("--x86", help="Use 32-bit unsigned int datatype for the encoded data buffer",
action="store_true")
args = parser.parse_args()
file_list = []
if os.path.isfile(args.input_filename):
file_list.append(args.input_filename)
elif os.path.isdir(args.input_filename):
for file in os.listdir(args.input_filename):
file_list.append(os.path.join(args.input_filename, file))
print(f"<encoder> setup finished!")
for filename in file_list:
print(f"<encoder> reading file {filename}...")
with open(filename, "rb") as input_file:
BUNDLE_BYTES = args.bytes
REDUNDANCY = args.redundancy
TRANSMISSION_LOSS_PERCENTAGE = args.transmission_loss_percentage
DATATYPE = np.uint64 if not args.x86 else np.uint32
if BUNDLE_BYTES < 8:
raise argparse.ArgumentError("Minimum bundle size is 8 bytes")
if REDUNDANCY < 1.3:
raise argparse.ArgumentError("Minimum redundancy scalar is 1.3")
if TRANSMISSION_LOSS_PERCENTAGE < 0.0 or TRANSMISSION_LOSS_PERCENTAGE > 100.0:
raise argparse.ArgumentError("Transmission loss percentage must be a value from 0.0 to 100.0, inclusive")
# Using a text file as input instead of a numpy array because LT code implementation doesn't seem to play nicely
# with the numpy arrays of random integers. Using files seems to be a popular method of simulating a data stream
# into the LT code software, as was seen in many implementations studied during our research. Also, opening the file
# in binary mode allows it to be compiled into a bytearray later, so we use the b mode.
input_file_name = input_file.name
# Only really need to get the file extension in this simulated environment, data can be sent without extensions in
# practice
_, extension = os.path.splitext(os.path.abspath(input_file.name))
data = []
# Read the text file into bundles of predefined size specified by BUNDLE_BYTES above
for i in range(math.ceil(os.path.getsize(input_file_name) / BUNDLE_BYTES)):
byte_array = input_file.read(BUNDLE_BYTES)
# Testfile is transformed into an object of type bytearray so that it can be parsed by np.frombuffer later.
# Just in case our text file does not have an exact multiple of BUNDLE_BYTES bytes (it probably doesn't) pad the
# end of the last byte with zeros. This slightly increases the size of the original data, but it is necessary to
# make it play nicely with the encoding and decoding process of LT code
byte_array = byte_array.ljust(BUNDLE_BYTES, b'\x00')
# np.frombuffer takes our bytearray and interprets it as a buffer of elements of a specific type. The default
# value for dtype is float, but since LT code uses XORs, it would be better to interpret these elements as
# integers. The magic of how exactly these values are translated to unsigned 64 bit integers is handled by
# numpy. If we want to forgo using any python packages (helpful if someone ever translates this to C), we will
# need to uncover said magic methods.
byte_array = np.frombuffer(byte_array, dtype=DATATYPE)
data.append(byte_array)
# For debugging purposes, we can output all our data sets. Could be added to a verbose option in the future.
#print(f"ORIGINAL DATA: \n{data}")
print(f"<encoder> reading finished!\n<encoder> encoding {filename}...")
start = time.time()
encoded_data = encode(data, len(data), round(REDUNDANCY * len(data))) # Redundancy is introduced here
end = time.time()
print(f"<encoder> data encoded! elapsed time: {round((end - start) * 1000,1)} ms\n<encoder> writing encoded data to {args.output_directory}/encodefile_{os.path.basename(filename)}.gz...")
# print(f"\n\n\nENCODED DATA: \n{encoded_data}")
# Simulate data loss, if necessary
if TRANSMISSION_LOSS_PERCENTAGE > 0.0:
encoded_data = random.sample(encoded_data, round(len(encoded_data) * (100 - TRANSMISSION_LOSS_PERCENTAGE) / 100))
# Write each bundle to the temporary output file. Since HDTN will be fragmenting this encoded file into bundles,
# we should not write these bundles to the file all at once in a unified data structure like a list.
# As long as each bundle is surrounded by curly braces {}, the decoder can recover them using regex.
if not os.path.exists(args.output_directory):
os.makedirs(args.output_directory)
with gzip.open(args.output_directory + "/encodefile_" + os.path.basename(filename) + ".gz", "wb") as f:
for bundle in encoded_data:
# For the purposes of reading these bundles later, we should write them with lists instead of numpy arrays.
# The lists are converted back into numpy arrays by the decoder.
bundle["value"] = bundle["value"].tolist()
to_write = json.dumps(bundle).encode()
f.write(to_write)
print(f"<encoder> writing finished!")
if __name__ == "__main__":
main()