-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
executable file
·333 lines (242 loc) · 8.91 KB
/
script.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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File name: strong_arms.py
Author: Tomas Tombakas
Email: [email protected]
Date created: 11/12/2017
"""
import re
import json
import string
import argparse
from collections import OrderedDict
from itertools import combinations
from itertools import tee
from functools import reduce
from copy import deepcopy
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def parse_file(f):
data = {}
columns = []
dependencies = {}
with open(f, "r") as f:
for line in f:
if "R =" in line:
for item in re.split(",|\(|\)", line.split("=")[1]):
item = item.strip()
if item != "":
if item in string.ascii_uppercase:
columns.append(item)
if "F =" in line:
for item in re.split(",|\{|\}", line.split("=")[1]):
item = item.strip()
if item != "":
key, value = tuple(re.split("->", item))
dependencies[key] = dependencies.get(key, "") + value
data["columns"] = columns
data["dependencies"] = dependencies
return data
def get_combinations(columns):
combs = []
for n in range(1, len(columns)):
for c in combinations(columns, n):
combs.append("".join(c))
return combs
def get_closures(columns, dependencies):
closures_a = {}
closures_b = {}
combs = get_combinations(columns)
for comb in combs:
closures_a[comb] = comb
while True:
closures_b = deepcopy(closures_a)
for left_side, right_side in closures_a.items():
for key, value in dependencies.items():
if set(key).issubset(set(right_side)):
if not set(value).issubset(set(right_side)):
closures_a[left_side] += value
if closures_a == closures_b:
break
for key, value in closures_a.items():
closures_a[key] = "".join(sorted(value))
return closures_a
def reduce_closures(closures, n):
abridged = {}
# Remove closures that are superkeys
for key, value in deepcopy(closures).items():
value = "".join(set(value))
if len(value) >= n:
del closures[key]
for key, value in closures.items():
value = "".join(sorted((set(value))))
# only keep one of the closures having the same value
if value not in abridged.values():
abridged["".join(sorted(key))] = value
return abridged
def regular_armstrong(columns, closures):
iterable = 2
nr_columns = len(columns)
entries = []
armstrong = {}
tex_armstrong = []
tex_armstrong_dict = OrderedDict()
# empty set closure
entries.append([0] * nr_columns)
entries.append([1] * nr_columns)
tex_armstrong_dict["0"] = [
["1_{\\varnothing}"] * nr_columns,
["0_{\\varnothing}"] * nr_columns
]
tex_armstrong.extend(tex_armstrong_dict["0"])
for key, value in closures.items():
tmp_tex_entries = []
tex_value_array = []
value_array = [iterable] * nr_columns
entries.append(deepcopy(value_array))
for column in columns:
tex_value_array.append("1_{" + key + "}")
tmp_tex_entries.append(deepcopy(tex_value_array))
for column in columns:
if column not in value:
value_array[columns.index(column)] = iterable + 1
tex_value_array[columns.index(column)] = "0_{" + key + "}"
entries.append(value_array)
tmp_tex_entries.append(tex_value_array)
tex_armstrong_dict[key] = tmp_tex_entries
tex_armstrong.extend(tmp_tex_entries)
iterable += 2
width = len(str(iterable)) + 4
fmt = (("{:^" + str(width) + "}|") * nr_columns)[:-1]
armstrong["name"] = "Armstrong relation table"
armstrong["width"] = width
armstrong["format"] = fmt
armstrong["columns"] = tuple(columns)
armstrong["entries"] = entries
return {"armstrong": armstrong,
"tex_armstrong": tex_armstrong,
"tex_armstrong_dict": tex_armstrong_dict}
def strong_armstrong_paul(columns, closures):
nr_columns = len(columns)
nr_entries = 2**(len(closures.keys()) + 1)
width = 2 + len((str(bin(nr_entries - 1))))
strong_armstrong = {}
fmt = (("{:^" + str(width) + "}|") * nr_columns)[:-1]
entries = [[""] * nr_columns for a in range(nr_entries)]
for i in range(nr_entries):
for j in range(nr_columns):
if i < nr_entries / 2:
entries[i][j] += "0"
else:
entries[i][j] += "1"
interval = nr_entries / 4
switch = False
for key, value in closures.items():
for n, entry in enumerate(entries):
for i in range(nr_columns):
if columns[i] in key:
entry[i] += "0"
else:
if not switch:
entry[i] += "0"
else:
entry[i] += "1"
if (n + 1) % interval == 0:
switch = not switch
interval /= 2
switch = False
strong_armstrong["name"] = "Strong Armstrong relation table"
strong_armstrong["width"] = width
strong_armstrong["format"] = fmt
strong_armstrong["columns"] = tuple(columns)
strong_armstrong["entries"] = entries
return strong_armstrong
def strong_armstrong_product(relations):
lists = [relations[key] for key in relations.keys()]
def combine_string_unicode(l, joiner=""):
result = ""
for element in l:
if not isinstance(element, str):
result += element.encode("utf8")
else:
result += element
result += joiner
return result
def meld(a, b):
concatenated = []
for item_1 in a:
for item_2 in b:
concatenated.append(
["".join(s) for s in zip(item_1, item_2)]
)
return concatenated
return reduce(meld, lists)
def print_relation(relation_dict):
print("-" * (len(relation_dict["name"]) + 1))
print(relation_dict["name"] + ":\n")
print(relation_dict["format"].format(*relation_dict["columns"]))
print("-" * ((relation_dict["width"] + 1) * len(relation_dict["columns"]) - 1))
for entry in relation_dict["entries"]:
print(relation_dict["format"].format(*entry))
return
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--regular-armstrong", action="store_true", help="Print a Regular Armstrong table")
parser.add_argument("--strong-armstrong", action="store_true", help="Print a Strong Armstrong table")
parser.add_argument("--json", action="store_true", help="Return json of tables")
parser.add_argument("--input-json", type=str, default="", help="Json containing definitions")
parser.add_argument("--input-file", type=str, default="./dependencies.txt", help="File containing definitiosn")
args = parser.parse_args()
return args
def process_request(data):
tables = get_tables(data)
j = {}
j["columns"] = data["columns"]
j["closures"] = tables["closures"]
if "TooManyClosuresError" not in tables["errors"]:
j["armstrong"] = tables["armstrong"]["entries"]
j["armstrong_latex"] = tables["tex_armstrong"]
j["s_armstrong_paul"] = tables["strong_armstrong"]
j["s_armstrong_product"] = strong_armstrong_product(tables["tex_armstrong_dict"])
else:
j["errors"] = tables["errors"]
return j
def get_tables(data):
columns = data["columns"]
dependencies = data["dependencies"]
tables = {"errors": {}}
closures = get_closures(columns, dependencies)
abridged_closures = reduce_closures(closures, len(columns))
tables["closures"] = abridged_closures
if len(abridged_closures.keys()) >= 6:
tables["errors"].update({
"TooManyClosuresError": "Too many closures to compute strong relations."
})
else:
tables.update(regular_armstrong(columns, abridged_closures))
tables["strong_armstrong"] = strong_armstrong_paul(columns, abridged_closures)
return tables
def main():
args = parse_args()
if args.input_json:
data = json.loads(args.input_json)
else:
data = parse_file(args.input_file)
tables = get_tables(data)
if args.json:
print(json.dumps(process_request(data)))
return
if tables["errors"]:
for key, value in tables["errors"].items():
print("{}: {}".format(key, value))
else:
if args.regular_armstrong:
print_relation(tables["armstrong"])
if args.strong_armstrong:
print_relation(tables["strong_armstrong"])
if __name__ == "__main__":
main()