ddk_converter.py: add testing script for lab5

This commit is contained in:
dymik739 2023-06-02 20:07:56 +03:00
parent b18d13e922
commit a981e16a8e
3 changed files with 141 additions and 0 deletions

113
src/ddk_converter.py Normal file
View File

@ -0,0 +1,113 @@
import bitutils as bu
import math
def to_int(x):
return int("0b" + x, 2)
def to_bin(x, n):
return bu.ar(bin(x)[2:], n)
def table_to_text(dt):
from lib.prettytable import PrettyTable
pt = PrettyTable()
initial_x_length = len(dt[0][0][-1])
final_row_length = len(dt[-1][-1])
pt.field_names = ["Iteration"] + [f"RG{i+1}" for i in range(final_row_length)]
for iteration, cycle in enumerate(dt):
for operation_id, row in enumerate(cycle):
complete_row = [iteration] + ['']*(final_row_length-len(row)) + row[:-1] + [bu.al(row[-1], initial_x_length)]
#print(complete_row)
if operation_id+1 == len(cycle):
pt.add_row(complete_row, divider = True)
else:
pt.add_row(complete_row)
return pt.get_string()
def binary_to_ddk(k, x):
required_register_size = math.ceil(math.log(k, 2))
required_shift = to_bin(2**required_register_size - k, required_register_size)
#print(f"math.log(k, 2): {math.log(k, 2)}")
#print(f"k: {k}, x: {x}")
#print(f"RRS: {required_register_size}, RS: {required_shift}")
# data table for logging registers
ddk_rg = ["0"*required_register_size]
device_states_log = []
x = str(x)
while len(x) != 0:
#print(f"Iter: DDK_RG: {ddk_rg}")
# start new logging section
device_states_log.append([])
# increasing registers amount if required
if ddk_rg[0][0] == '1':
ddk_rg.insert(0, "0"*required_register_size)
# reset force corrections
force_correction = [False]*len(ddk_rg)
device_states_log[-1].append(ddk_rg + [x]) # log
# shift left all registers
# iterating over registers from left to right
for i, rg in list(enumerate(ddk_rg))[:-1]:
force_correction[i+1] = bool(int(ddk_rg[i+1][0]))
ddk_rg[i] = bu.l(ddk_rg[i], ddk_rg[i+1][0])
#if do_correction:
# ddk_rg[i+1] = bu.sum(ddk_rg[i+1], required_shift, required_register_size)
ddk_rg[-1] = bu.l(ddk_rg[-1], x[0])
x = bu.l(x, '')
device_states_log[-1].append(ddk_rg + [x]) # log
# correct errors where needed
# iterating over registers from right to left
#print(ddk_rg)
for i, rg in list(enumerate(ddk_rg))[1:][::-1]:
#print(f"Correcting errors for: {rg} (i={i})")
if force_correction[i]:
ddk_rg[i] = bu.rsum(ddk_rg[i], required_shift, required_register_size)
if to_int(rg) >= k:
ddk_rg[i] = bu.rsum(ddk_rg[i], required_shift, required_register_size)
ddk_rg[i-1] = bu.rsum(ddk_rg[i-1], '1', required_register_size)
# special correction for first register
if to_int(ddk_rg[0]) >= k:
#print("Special correction triggered!")
ddk_rg[0] = bu.rsum(ddk_rg[0], required_shift, required_register_size)
ddk_rg.insert(0, "0"*(required_register_size-1) + '1')
device_states_log[-1].append(ddk_rg + [x]) # log
formatted_result = ""
for i in ddk_rg:
digit = to_int(i)
if digit <= 9:
formatted_result += str(digit)
else:
formatted_result += chr(digit-10 + 65)
return device_states_log, ddk_rg, formatted_result
if __name__ == "__main__":
x = input("Enter x: ")
k = int(input("Enter k: "))
dt, result, formatted_result = binary_to_ddk(k, x)
print(table_to_text(dt))
print(f"Result: {result}")
print(f"Formatted result: {formatted_result}")

1
src/www/ddk_converter.py Symbolic link
View File

@ -0,0 +1 @@
../ddk_converter.py

View File

@ -0,0 +1,27 @@
import os
import sys
from ddk_converter import binary_to_ddk, table_to_text
print(os.environ, file = sys.stderr)
raw_params = list(map(lambda x: x.split("="), os.environ['QUERY_STRING'].split("&")))
baked_params = {k:v for (k, v) in raw_params}
bp = baked_params
if all([i in bp for i in ('x', 'k', 'op')]):
x = bp['x']
k = int(bp['k'])
if bp['op'] == "binary-ddk":
dt, result, formatted_result = binary_to_ddk(k, x)
print(f"Content-Type: text/plain; charset=UTF-8\n"
f"\n"
f"{table_to_text(dt)}\n"
f"Result: {result}\n"
f"Formatted result: {formatted_result}")
else:
print("Content-Type: text/plain; charset=UTF-8\r\n\r\nThis operation is not supported yet")
else:
print("Content-Type: text/plain; charset=UTF-8\r\n\r\nCheck your input!")