Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
executable file 1991 lines (1738 sloc) 68.2 KB
#!/bin/python3
"""
Graph Rep:
N^2 = number of nodes (nodes {1-n^2})
Assume a square grid, so each node is connect0 to i-1, i+1, i+n
A set T |T| >=2 {1,n^2} Union {i} such that node i are trusted nodes
"""
from __future__ import print_function
from ortools.graph import pywrapgraph
import random
import collections
import sys
from copy import deepcopy
from math import log2
import math
import networkx as nx
global balance
global prio_a
global prio_b
global prio_last
prio_last = None
prio_a = prio_b =1000
balance = 1
filt = None
global CAD
CAD = True
def shortest_path2(self,source, target):
G = self.G
try:
return nx.shortest_path(G,source, target)
except nx.exception.NodeNotFound:
return ()
except nx.exception.NetworkXNoPath:
return ()
class Graph:
def __init__(self, nodes, edges, weight = lambda u,v: 1):
self._nodes = tuple([int(node) for node in nodes])
self._edges = set(edges)
self._weight = weight
self.G = False
self._paths = None
self._Alice = None
self._Bob = None
def add_graph(self):
self.G = nx.Graph()
for edge in self.get_edges():
self.G.add_edge(edge[0], edge[1])
def print_graph(self):
print("Vertices: {}".format(self.get_nodes()))
print("Edges: {}".format([ (x, self.weight(x[0],x[1])) for x in self.get_edges()]))
print("Alice {}, Bob {}".format(self._Alice, self._Bob))
def get_edges(self):
return self._edges
def weight(self, u,v):
return self._weight(u,v)
def get_nodes(self):
return self._nodes
def get_edge(self, u, v):
edge = (min(u,v), max(u,v))
if edge in self.get_edges():
return edge
return False
def set_edges(self, new_edges):
self._edges = set(new_edges)
if self.G:
for edge in self.get_edges():
self.G.add_edge(edge[0], edge[1])
def set_nodes(self, new_nodes):
self._nodes = tuple(new_nodes)
def get_neighbors(self, u):
return set([v for v in self.get_nodes() if self.get_edge(u,v)])
def remove_edge(self, u, v):
e = self.get_edge(u,v)
if e:
self.get_edges().remove((e[0],e[1]))
if self.G:
self.G.remove_edge(e[0], e[1])
def add_edge(self, u, v):
e = self.get_edge(u,v)
if not e:
self.get_edges().add((u,v))
if self.G:
self.G.add_edge(e[0], e[1])
def shortest_path(self, source, dest):
return shortest_path2(self,source,dest)
def shortest_path_old(self, source,dest):
#print("Looking for shortest path between", source, dest)
Q = set()
dist = {}
prev = {}
for v in self.get_nodes():
Q.add(v)
dist[v] = float('Inf')
prev[v] = None
dist[source] = 0
#prev[source] = 1
while Q:
u = None
udist = float('Inf')
for key in Q:
if dist[key] < udist:
u = key
udist = dist[key]
if u is None:
return () #no path
Q.remove(u)
for v in Q:
edge = self.get_edge(u,v)
if edge:
alt = dist[u] + self.weight(edge[0],edge[1])
if alt < dist[v]:
dist[v] = alt + .000 if u!= source and abs(u-v) != abs(u - prev[u]) else 0
prev[v] = u
if u == dest:
S = []
if prev[u] is not None or u == source:
while u is not None:
S = [u]+S
u = prev[u]
#print(S)
return S
else:
return ()
return ()
def all_paths(self):
if self._paths:
return self._paths
paths = {}
for u in self.get_nodes():
for v in self.get_nodes():
path = self.shortest_path(u,v)
if u in paths:
paths[u][v] = len(path) -1 #(len(path)-1, path)
else:
paths[u] = {v:len(path) -1} #(len(path)-1, path)}
self._paths = paths
return paths
class RingGraph(Graph):
def __init__(self, n, T, weight=lambda u,v: 1, Alice = None, Bob = None):
self._n = n
T = list(T)
vert = tuple([i for i in range(0,n)])
edgel = []
for i in vert:
if (i+1) % n in vert:
edgel.append((i, (i+1) % n))
if (i+2) % n in vert:
edgel.append((i, (i+2) % n))
super().__init__(vert, edgel)
if not Alice or not Bob:
self._Alice = 0
self._Bob = int(n/2)
if self._Alice in T:
T.remove(self._Alice)
T.remove(self._Bob)
T = [self._Alice] + T + [self._Bob] # make sure that T is always trusted Nodes between Alice and Bob
self.trusted = tuple(sorted([int(t) for t in T]))
def show_graph(self):
self.print_graph()
def get_dim(self):
return self._n
def get_trusted(self):
return self.trusted
class WheelGraph(Graph):
def __init__(self, n, T, weight=lambda u,v: 1):
self._n = n
T = list(T)
vert = [i for i in range(0,n)]
edgel = []
for i in vert:
if (i+1) % n in vert:
edgel.append((i, (i+1) % n))
edgel.append((i, (n)))
vert.append(n)
vert = tuple(vert)
super().__init__(vert, edgel)
if not Alice or not Bob:
self._Alice = 0
self._Bob = int(n/2)
if self._Alice in T:
T.remove(self._Alice)
T.remove(self._Bob)
T = [self._Alice] + T + [self._Bob]
self.trusted = tuple(sorted([int(t) for t in T]))
def show_graph(self):
self.print_graph()
def get_dim(self):
return self._n
def get_trusted(self):
return self.trusted
class GridGraph(Graph):
def __init__(self, n, T, weight=lambda u,v: 1, Alice = None, Bob = None):
self._n = n
T = list(T)
vert = tuple([i for i in range(0,n*n)])
edgel = []
for i in vert:
if i+1 in vert and (i+1) % n !=0:
edgel.append((i, i+1))
if i+n in vert:
edgel.append((i, i+n))
super().__init__(vert, edgel)
if not Alice or not Bob:
self._Alice = min(T)
self._Bob = max(T)
if self._Alice in T:
T.remove(self._Alice)
T.remove(self._Bob)
T = [self._Alice] + T + [self._Bob]
self.trusted = tuple(sorted([int(t) for t in T]))
def show_graph(self):
print("")
n = self._n
for row in range(n):
for nodes_or_edge in range(3):
for col in range(n):
cur_node = col + row*n
if nodes_or_edge == 0:
#print(cur_node, end = "")
print("T" if cur_node in self.get_trusted() else cur_node, end = "")
if self.get_edge(cur_node, cur_node + 1):
print(" -- ", end="")
else:
print(" ", end="")
else:
if self.get_edge(cur_node, cur_node+n):
print ("|",end="")
else:
pass
print(" "*max(len(str(cur_node)),len(str(cur_node+n))), end="")
print(" ",end="")
print("")
def get_dim(self):
return self._n
def get_trusted(self):
return self.trusted
def generate_network(n,T, p, q, d, shape = "grid"):
if shape == "ring":
G = RingGraph(n,T)
elif shape == "wheel":
G = WheelGraph(n,T)
else:
G = GridGraph(n,T)
P = {i:{j: p for j in G.get_nodes()} for i in G.get_nodes()}
D = {i:{j: d for j in G.get_nodes()} for i in G.get_nodes()}
Q = [q for i in G.get_nodes()]
K = {i:{j: 0 for j in G.get_trusted()} for i in G.get_trusted()}
Kb = {i:{j: [] for j in G.get_trusted()} for i in G.get_trusted()}
return (G,P,Q,D,K, Kb)
def pair_ent(G, P):
G1 = type(G)(G.get_dim(), G.get_trusted(), G._weight, G._Alice, G._Bob)
G1.set_edges([e for e in G.get_edges() if PRNG_gen.random() < P[e[0]][e[1]]])
return G1
def R1_find_best_links(G,G1,K,node, dumb = False):
neighbors = G1.get_neighbors(node) #these nodes are connected by ent channel to our noe
trusted = G1.get_trusted()
dist = lambda x: G._paths[x[0]][x[1]]
Pt = []
if len(neighbors) <=1:
return [] # coudn't add any
#We have a list of neighbor nodes and unique trsuted nodes, and the distance between them
neigh_trusted1 = [(u,T) for u in neighbors for T in trusted]
#print("Node:", node)
#print("Dists1: ", neigh_trusted1)
best_dist_1 = dist(min(neigh_trusted1, key=dist)) #this gives us the best distance
Poss1 = [p for p in neigh_trusted1 if dist(p) == best_dist_1]
#print(Poss1)
(v1,t1) = PRNG_gen.choice(Poss1)
neigh_trusted2 = [(u,T) for u in neighbors for T in trusted if T!=t1]
best_dist_2 = dist(min(neigh_trusted2, key=dist)) #this gives us the best distance
Poss2a = [p for p in neigh_trusted2 if dist(p) == best_dist_2 ]
Poss2 = [p for p in Poss2a if abs(node-p[0]) == abs(node-v1)]
if dumb or not Poss2 : #if dumb flag is set dont try and maintain direction
Poss2 = Poss2a
#print(Poss2)
(v2,t2) = PRNG_gen.choice(Poss2)
if v1 == v2:
#Trying
next_nt1 = [p for p in neigh_trusted1 if p[0] != v1 and p[1] != t2]
next_nt2 = [p for p in neigh_trusted2 if p[0] != v2 and p[1] != t1]
next_best_1 = dist(min(next_nt1, key=dist))
next_best_2 = dist(min(next_nt2, key=dist))
next_poss1 = [p for p in next_nt1 if dist(p) == next_best_1]
next_poss2 = [p for p in next_nt2 if dist(p) == next_best_2]
(nv1, nt1) = PRNG_gen.choice(next_poss1)
(nv2, nt2) = PRNG_gen.choice(next_poss1)
if dist((v1,t1)) + dist((nv2, nt2)) < dist((nv1,nt1)) + dist((v2,t2)):
v2,t2 = nv2,nt2
elif dist((v1,t1)) + dist((nv2, nt2)) >dist((nv1,nt1)) + dist((v2,t2)):
v1,t1 = nv1,nt1
else:
which = PRNG_gen.choice([0,1])
if which:
v1,t1 = nv1,nt1
else:
v2,t2 = nv2,nt2
if v1 == v2:
print("Error!")
print("G")
G.show_graph()
print("G1")
G1.show_graph()
print("Paths:", G._paths)
print("node", node)
print("Poss1: ", Poss1)
print("Poss2: ", Poss2)
print("V1, t1, v2, t2: ", v1,t1,v2,t2)
print("Could we do:")
print("V1, t1, v2, t2: ", v1,t1,nv2,nt2)
print("or:")
print("V1, t1, v2, t2: ", nv1,nt1,v2,t2)
print(dist((v1,t1)) + dist((nv2, nt2)), dist((nv1,nt1)) + dist((v2,t2)))
raise RuntimeError("Error, trying to link same node to itself")
#print(v1,t1, v2,t2)
Pt.append([min(v1,v2), node, max(v1,v2)])
#G1.remove_edge(node, v1)
#G1.remove_edge(node, v2)
#G1.add_edge(v1,v2)
neighbors.remove(v1)
neighbors.remove(v2)
if len(neighbors)==2:
Pt.append([min(neighbors), node, max(neighbors)])
#G1.remove_edge(node, min(neighbors))
#G1.remove_edge(node, max(neighbors))
#G1.add_edge(min(neighbors),max(neighbors))
#print(Pt)
return Pt
def local_R1(G, G1, K, dumb = False, balance_counts = None):
#G1.show_graph()
global balance
global prio_a
global prio_b
global prio_last
prio = None
G.add_graph()
G.all_paths()
trusted = G1.get_trusted()
#G1.show_graph()
# print("---")
if len(trusted) == 3 and balance and balance_counts:
#if K[trusted[0]][trusted[1]] > balance * K[trusted[1]][trusted[2]]:
if balance_counts[trusted[0]][trusted[1]] > balance * balance_counts[trusted[1]][trusted[2]]:
if prio_last != "B":
G._paths = None
G.all_paths()
for node in G._paths:
for n2 in G._paths[node]:
if n2 == trusted[0] and G._paths[node][n2]:
G._paths[node][n2] = float('inf')
prio = "B"
prio_b +=1
#print(K)
#elif K[trusted[1]][trusted[2]] > balance * K[trusted[0]][trusted[1]]:
elif balance_counts[trusted[1]][trusted[2]] > balance * balance_counts[trusted[0]][trusted[1]]:
if prio_last != "A":
G._paths = None
G.all_paths()
for node in G._paths:
for n2 in G._paths[node]:
if n2 == trusted[2] and G._paths[node][n2]:
G._paths[node][n2] = float('inf')
prio = "A"
prio_a += 1
#print(K)
else:
if prio_last:
G._paths = None
G.all_paths()
prio = None
prio_last = prio
Pt = []
for node in G1.get_nodes():
if node not in trusted:
result = R1_find_best_links(G,G1,K,node, dumb)
#print("best links for ", node, result)
#print(result)
if result:
#print("Result," ,result)
#print("Path", Pt)
for add in result:
added = False
#print("new", add)
for path in Pt:
#print(" add, path", add[:-1], path[-2:])
if add[:-1] == path[-2:]:
path.append(add[-1])
added = True
#print("mrg-",Pt)
if not added:
Pt.append(add)
#print(Pt)
#raise RuntimeError
ret = [p for p in Pt if p[0 ] in trusted and p[-1] in trusted]
for path in ret:
for pathi in range(len(path)-1):
G1.remove_edge(path[pathi], path[pathi+1])
return ret
# global balance
# global prio_a
# global prio_b
# prio_a = prio_b = 0
def R1(G,G1,K, balance_counts = None):
global balance
global prio_a
global prio_b
G1.add_graph()
trusted = G.get_trusted()
Pt = []
first_flag = False
prio = None
#G1.show_graph()
# print("---")
if len(trusted) == 3 and balance and balance_counts:
#if K[trusted[0]][trusted[1]] > balance * K[trusted[1]][trusted[2]]:
if balance_counts[trusted[0]][trusted[1]] > balance * balance_counts[trusted[1]][trusted[2]]:
prio = "B"
prio_b +=1
# print("Prioritizing B")
#print(K)
#elif K[trusted[1]][trusted[2]] > balance * K[trusted[0]][trusted[1]]:
elif balance_counts[trusted[1]][trusted[2]] > balance * balance_counts[trusted[0]][trusted[1]]:
prio = "A"
prio_a += 1
#print("Prioritizing A")
#print(K)
while True:
shortest_paths = []
if not balance or not prio:
for TN1 in trusted:
for TN2 in trusted:
if TN1 < TN2:
shortest_paths.append(G1.shortest_path(TN1, TN2))
elif prio == "B":
shortest_paths.append(G1.shortest_path(trusted[1], trusted[2]))
elif prio == "A":
shortest_paths.append(G1.shortest_path(trusted[0], trusted[1]))
adds = [p for p in shortest_paths if len(p)!=0]
#print("lens ", [[x[0],x[-1],len(x)] if x else "" for x in shortest_paths])
#print("Paths", adds)
mina = min(adds, key = lambda x: len(x)) if adds else []
#print("mina =", mina)
adds = [p for p in adds if len(p) == len(mina)]
#print("chosing from", adds)
add = PRNG_ran.choice(adds) if adds else []
#add = adds[-1] if adds else []
#print("chose", add)
# print("")
if add:
#print("{} -> {} len {}".format(add[0],add[-1], len(add)))
#print("Adding", add)
#if len(add) != 7 and ((add[0],add[-1]) == (0,24) or (add[0],add[-1]) == (24,48)):
# print("Added so far:", [(x,len(x)) for x in Pt])
# print("Paths", adds)
# print("mina =", mina)
# print("chose from", adds)
# print("Adding", add, len(add))
# G1.show_graph()
add = adds[-1] if adds else []
for j in range(len(add)-1):
G1.remove_edge(add[j], add[j+1])
Pt.append(add)
else:
#print("Breaking")
if prio:
#print("Looking for all")
prio = None
else:
break
#print("Added ", Pt)
#print("------")
#G1.show_graph()
#print(Pt)
#print(Pt)
return Pt
def path_ent(G, Q, D, Pt):
G2 = type(G)(G.get_dim(), G.get_trusted(), G._weight, G._Alice, G._Bob) #GridGraph(G.get_dim(), G.get_trusted())
G2.set_nodes(G.get_trusted())
edges = []
pathinf = []
for p in Pt:
prob_suc = 1
prob_dep = 1-D[p[0]][p[1]]
for i in range(len(p[1:-1])):
pi = p[i]
pi2 = p[i+1]
try:
prob_suc *= Q[pi]
except:
print(prob_suc, Q, pi)
try:
prob_dep *= (1-D[pi][pi2])
except:
print(pi, pi2)
raise RuntimeError
prob_dep = prob_dep + (1-prob_dep)/2
rand = PRNG_ent.random()
if rand <= prob_suc and p[0] in G2.get_trusted() and p[-1] in G2.get_trusted():
edges.append((p[0],p[-1], int(PRNG_ent.random() > prob_dep)))
pathinf.append(1 - prob_dep)
G2.set_edges([(e[0],e[1]) for e in edges ])
return G2, edges, pathinf
def attempt_QKD(G, Ed, Pz, Px, K, Kb, pathinf, balance_inf = None):
for x in range(len(Ed)):
edge = Ed[x]
path = pathinf[x]
if PRNG_qkd.random() <= Pz*Pz+Px*Px:
i = min(edge[0], edge[1])
j = max(edge[0], edge[1])
K[i][j] +=1
#Kb[i][j]+=str(int(edge[2]))
Kb[i][j].append((str(int(edge[2])),path))
balance_inf[i][j]+=max(0,(1-2*binary_entropy(path)))
G3 = type(G)(G.get_dim(), G.get_trusted(), G._weight, G._Alice, G._Bob) #GridGraph(G.get_dim(), G.get_trusted())
G3.set_nodes(G.get_trusted())
G3.set_edges(G.get_edges())
return G3, K, Kb, balance_inf
def R2_regular(G,K,Kb,finite = False, thresh = None):
old_K = deepcopy(K)
old_Kb = deepcopy(Kb)
for i in K:
for j in K:
if not K[i][j]:
continue
errors = Kb[i][j].count("1")
Q = float(errors/K[i][j])
#K[i][j] = max(0,int((1-2*binary_entropy(Q))*K[i][j]))
K[i][j] = cad_EC(Q, K[i][j])
Kb[i][j] = "0"*K[i][j]
try:
print(" {} - > {} had {} bits and {} errors, error rate of {} resulting in {} secret key bits".format(i, j,old_K[i][j],errors,Q, K[i][j]))
except:
print(" {} - > {} had {} bits and {} errors, error rate of {}".format(k, kb, k_errors[k][kb][0],k_errors[k][kb][1],0))
#print("+++++++++++++++++++++++++++++++++++++++++++++")
c=0
while True:
c+=1
#print("-------------------- Loop {} ------------".format(c))
# print(K)
start_nodes, end_nodes, capacities = [],[],[]
for i in K:
for j in K[i]: #chnaged k to kb
#if Kb[i][j]:
start_nodes.append(i)
end_nodes.append(j)
capacities.append(K[i][j])
# print(start_nodes)
# print(end_nodes)
# print(capacities)
if not (start_nodes and end_nodes and capacities):# or not min(K) in start_nodes or not max(K) in end_nodes:
return 0, 0, old_K, old_Kb
flow = maxflow_ortools(start_nodes, end_nodes, capacities, G._Alice, G._Bob)
##error stuff
flows = []
for i in range(flow.NumArcs()):
for j in range(i,flow.NumArcs()):
if flow.Head(i) == flow.Tail(j) and (flow.Head(i)!=flow.Tail(i)) and (flow.Flow(j) and flow.Flow(i)):
print(' %1s -> %1s %3s / %3s' % (flow.Tail(i),flow.Head(i),flow.Flow(i),flow.Capacity(i)))
print(' %1s -> %1s %3s / %3s' % (flow.Tail(j),flow.Head(j),flow.Flow(j),flow.Capacity(j)))
flows.append([flow.Tail(i), flow.Head(i), flow.Head(j), flow.Flow(j)])
#print(flows[-1])
# print("Flows is ", flows)
if len(flows) <= 1:
print(" Breaking flows")
break
for f in flows:
# print("consiering at", f)
if True or not (f[0] == G._Alice and f[1] == G._Bob):
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
break
if flows:
f= flows[0]
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
errors = Kb[G._Alice][G._Bob].count("1")
# print("Error string is " ,len(Kb[min(Kb)][max(Kb)]))
##reset K, Kb
Kb[G._Alice][G._Bob]=""
for i in range(flow.NumArcs()):
K[flow.Tail(i)][flow.Head(i)]-=flow.Flow(i)
#print(Kb)
#print(K)
# print("Flows", flows)
# print("maxflow", flow.OptimalFlow())
print("HERE")
return flow.OptimalFlow(), errors, K, Kb
def R2_regular_all(G, K_all, Kb_all, finite= False, thresh = None):
K = {i:{j: 0 for j in G.get_trusted()} for i in G.get_trusted()}
Kb = {i:{j: "" for j in G.get_trusted()} for i in G.get_trusted()}
print(K)
for x in Kb_all:
for y in Kb_all[x]:
if not K_all[x][y]:
continue
keys = dict()
for keybit in Kb_all[x][y]:
if keybit[1] in keys:
keys[keybit[1]][0] += 1
keys[keybit[1]][1] += int(keybit[0])
else:
keys[keybit[1]] = [0,0]
# print("{} -> {} decoherence rate: Keybits,error".format(x,y))
# print(keys)
for rate in keys:
try:
Q = keys[rate][1]/keys[rate][0]
except:
Q = 0
#K[x][y]+= max(0,int((1-2*binary_entropy(float(Q)))*keys[rate][0]))
K[x][y] += cad_EC(Q, keys[rate][0])
Kb[x][y] = "0"*K[x][y]
print(" {} - > {} had {} bits and resulted {} secret key bits".format(x, y,K_all[x][y], K[x][y]))
for rate in keys:
try:
Q = keys[rate][1]/keys[rate][0]
except:
Q = 0
print(" {} bits had expected error rate {} and real error rate {}, produced {} secret key bits,".format(keys[rate][0], rate, float(Q) , max(0,int((1-2*binary_entropy(float(Q)))*keys[rate][0]))))
#print("+++++++++++++++++++++++++++++++++++++++++++++")
c=0
while True:
c+=1
#print("-------------------- Loop {} ------------".format(c))
# print(K)
start_nodes, end_nodes, capacities = [],[],[]
for i in K:
for j in K[i]: #chnaged k to kb
#if Kb[i][j]:
start_nodes.append(i)
end_nodes.append(j)
capacities.append(K[i][j])
# print(start_nodes)
# print(end_nodes)
# print(capacities)
if not (start_nodes and end_nodes and capacities):# or not min(K) in start_nodes or not max(K) in end_nodes:
return 0, 0, old_K, old_Kb
flow = maxflow_ortools(start_nodes, end_nodes, capacities, G._Alice, G._Bob)
##error stuff
flows = []
for i in range(flow.NumArcs()):
for j in range(i,flow.NumArcs()):
if flow.Head(i) == flow.Tail(j) and (flow.Head(i)!=flow.Tail(i)) and (flow.Flow(j) and flow.Flow(i)):
print(' %1s -> %1s %3s / %3s' % (flow.Tail(i),flow.Head(i),flow.Flow(i),flow.Capacity(i)))
print(' %1s -> %1s %3s / %3s' % (flow.Tail(j),flow.Head(j),flow.Flow(j),flow.Capacity(j)))
flows.append([flow.Tail(i), flow.Head(i), flow.Head(j), flow.Flow(j)])
#print(flows[-1])
# print("Flows is ", flows)
if len(flows) <= 1:
print(" Breaking flows")
break
for f in flows:
# print("consiering at", f)
if True or not (f[0] == G._Alice and f[1] == G._Bob):
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
break
if flows:
f= flows[0]
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
errors = Kb[G._Alice][G._Bob].count("1")
# print("Error string is " ,len(Kb[min(Kb)][max(Kb)]))
##reset K, Kb
Kb[G._Alice][G._Bob]=""
for i in range(flow.NumArcs()):
K[flow.Tail(i)][flow.Head(i)]-=flow.Flow(i)
#print(Kb)
#print(K)
# print("Flows", flows)
# print("maxflow", flow.OptimalFlow())
print("HERE1", G._Bob)
print(flow.OptimalFlow())
return flow.OptimalFlow(), errors, K, Kb
def R2_simple(G,K,Kb, finite = False, thresh = None):
#print("+++++++++++++++++++++++++++++++++++++++++++++")
c=0
#print(K)
while True:
c+=1
#print("-------------------- Loop {} ------------".format(c))
# print(K)
start_nodes, end_nodes, capacities = [],[],[]
for i in K:
for j in K[i]:
if Kb[i][j]: #chnaged from K to kb, hopefullt fixes keybit error
start_nodes.append(i)
end_nodes.append(j)
capacities.append(K[i][j])
# print(K,Kb)
# print(start_nodes)
# print(end_nodes)
# print(capacities)
if start_nodes:
flow = maxflow_ortools(start_nodes, end_nodes, capacities), G._Alice, G._Bob
else:
#raise RuntimeError
return 0, 0, K, Kb
##error stuff
flows = []
for i in range(flow.NumArcs()):
for j in range(i,flow.NumArcs()):
if flow.Head(i) == flow.Tail(j) and (flow.Head(i)!=flow.Tail(i)) and (flow.Flow(j) and flow.Flow(i)):
#print('%1s -> %1s %3s / %3s' % (flow.Tail(i),flow.Head(i),flow.Flow(i),flow.Capacity(i)))
#print('%1s -> %1s %3s / %3s' % (flow.Tail(j),flow.Head(j),flow.Flow(j),flow.Capacity(j)))
flows.append([flow.Tail(i), flow.Head(i), flow.Head(j), flow.Flow(j)])
# #print(flows[-1])
# print("Flows is ", flows)
if len(flows) <= 1:
# print("Breaking flows")
break
for f in flows:
# print("consiering at", f)
if True or not (f[0] == G._Alice and f[1] == G._Bob):
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
break
if flows:
f= flows[0]
try:
new_str = "".join([str(int(Kb[f[0]][f[1]][i]) ^ int(Kb[f[1]][f[2]][i])) for i in range(f[3])])
# print("Looking at", f)
except Exception as e:
print("Error")
print("Flow", f)
print("Kb[{}][{}]".format(f[0],f[1]), Kb[f[0]][f[1]])
print("Kb[{}][{}]".format(f[1],f[2]), Kb[f[1]][f[2]])
print(e)
raise RuntimeError
# print("1", Kb[f[0]][f[1]])
# print("2", Kb[f[1]][f[2]])
# print("xor" ,new_str)
# print("old", Kb[f[0]][f[2]])
Kb[f[0]][f[1]] = Kb[f[0]][f[1]][f[3]:]
Kb[f[1]][f[2]] = Kb[f[1]][f[2]][f[3]:]
Kb[f[0]][f[2]] += new_str
K[f[0]][f[1]] -=f[3]
K[f[1]][f[2]] -=f[3]
K[f[0]][f[2]] +=f[3]
# print("old1",Kb[f[0]][f[1]])
# print("old2",Kb[f[1]][f[2]])
# print("new",Kb[f[0]][f[2]])
errors = Kb[G._Alice][G._Bob].count("1")
# print("Error string is " ,len(Kb[min(Kb)][max(Kb)]))
##reset K, Kb
Kb[G._Alice][G._Bob]=""
#print(K)
#for i in range(flow.NumArcs()):
# print(flow.Tail(i), flow.Head(i), flow.Flow(i))
# K[flow.Tail(i)][flow.Head(i)]-=flow.Flow(i)
K[G._Alice][G._Bob]-=flow.OptimalFlow()
#print(Kb)
#print(K)
#print(K, flow.OptimalFlow())
if finite:
pass
return flow.OptimalFlow(), errors, K, Kb
def maxflow_ortools(start_nodes, end_nodes, capacities, source, sink):
"""MaxFlow simple interface example."""
# Define three parallel arrays: start_nodes, end_nodes, and the capacities
# between each pair. For instance, the arc from node 0 to node 1 has a
# capacity of 20.
#start_nodes = [] #[0, 0, 0, 1, 1, 2, 2, 3, 3]
#end_nodes = [] #[1, 2, 3, 2, 4, 3, 4, 2, 4]
#capacities = [] #[20, 30, 10, 40, 30, 10, 20, 5, 20]
# Instantiate a SimpleMaxFlow solver.
max_flow = pywrapgraph.SimpleMaxFlow()
# Add each arc.
for i in range(0, len(start_nodes)):
max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i])
# Find the maximum flow between node 0 and node 4.
try:
if max_flow.Solve(source,sink ) == max_flow.OPTIMAL:
# print('Max flow:', max_flow.OptimalFlow())
# print('')
# print(' Arc Flow / Capacity')
# for i in range(max_flow.NumArcs()):
# print('%1s -> %1s %3s / %3s' % (
# max_flow.Tail(i),
# max_flow.Head(i),
# max_flow.Flow(i),
# max_flow.Capacity(i)))
# # print('Source side min-cut:', max_flow.GetSourceSideMinCut())
# print('Sink side min-cut:', max_flow.GetSinkSideMinCut())
pass
else:
print('There was an issue with the max flow input.')
print(start_nodes)
print(end_nodes)
print(capacities)
raise RuntimeError
except Exception as e:
print(start_nodes)
print(end_nodes)
print(capacities)
print(e)
raise RuntimeError
print("Tried to find a flow from {} to {} on {} {} {}".format(source, sink, start_nodes, end_nodes, capacities))
print("Got {}".format(max_flow.OptimalFlow()))
return max_flow
def finite_process_regular(K,Kb, K_fin, finite_block, override = False):
eps_bar = 1e-6
print(finite_block)
for k1 in K:
for k2 in K[k1]:
while K[k1][k2] > (finite_block if not override else 0):
print("nodes", k1,k2)
bits = int(min(finite_block, K[k1][k2]))
print("bits", bits)
K[k1][k2]-= bits
err_string = Kb[k1][k2][:bits]
Kb[k1][k2]=Kb[k1][k2][bits:]
shared_str = random.sample(err_string, int(finite_block/3))
print("errstr", "".join(shared_str))
print("errors", "".join(shared_str).count("1"))
QBER = shared_str.count("1") / float(len(shared_str))
print("calculated", QBER)
worst_case = math.sqrt((2*math.log(1/eps_bar)+2*math.log(1+(finite_block/3.)))/(finite_block/3.))
print("confidence interval", worst_case)
key_rate = max(0,1 - 2 *binary_entropy(QBER+worst_case))
print(key_rate)
exit(0)
def cad_opt(noise, cad):
#print("Doing CAD level {}".format(cad))
decs = []
x = 0
step = .00001
while x < noise:
decs.append(x)
x = min(x+step, noise)
decs.append(x)
maxkey = 5
QC = noise**cad
ec= QC/(QC+(1-noise)**cad)
minval = None
for l4 in decs:
Leq = ((1-3*noise+2*l4)/(1-noise))**cad
Ldiff = (abs(noise - 2*l4)/noise)**cad
# print("noise", "cad", "Leq", "Ldiff", "l4")
# print(noise, cad, Leq, Ldiff, l4)
# print(1-binary_entropy(ec)-(1-ec)*binary_entropy((1-Leq)/2) - ec*binary_entropy((1-Ldiff)/2))
#key = (1-binary_entropy(ec)-(1-ec)*binary_entropy((1-Leq)/2) - ec*binary_entropy((1-Ldiff)/2))
try:
key = ((1 - noise)**cad + noise**cad)*(1/cad)*(1-binary_entropy(ec)-(1-ec)*binary_entropy((1-Leq)/2.) - ec*binary_entropy((1-Ldiff)/2.))
except:
print("WARNING, CAD_OPT FAILED FOR NOISE {} AND CAD {} and l4 {}".format(noise, cad, l4))
key = 0
if key < maxkey:
maxkey=key
minval = l4
l4 = minval
Leq = ((1-3*noise+2*l4)/(1-noise))**cad
Ldiff = (abs(noise - 2*l4)/noise)**cad
# print("\tnoise = {}, \n\tcad = {}, \n\tl4 = {}, \n\tleq = {}, \n\tldiff = {}, \n\tec = {}, \n\trate ={}".format(noise, cad, l4, Leq, Ldiff, ec, maxkey))
# print(((1 - Q)**cad + Q**cad)*(1/cad)*(1-binary_entropy(ec)-(1-ec)*binary_entropy((1-Leq)/2) - ec*binary_entropy((1-Ldiff)/2)))
return maxkey
# global CAD
def cad_EC(noise, bits):
if not CAD:
return int(max(0,1-2*binary_entropy(noise))*bits)
print(" Doing CAD on noise {} with {} bits". format(noise, bits))
maxcad = 20 if CAD else 1
maxcad = maxcad if noise not in [0,1] else 1
keyrates = [max(0,1-2*binary_entropy(noise))]
for cad in range(2, maxcad+1):
keyrates.append(cad_opt(noise, cad))
# print("At CAD_level {} got keyrate {}".format(cad, keyrates[-1]))
#print("keyrates", keyrates)
print(" Did CAD on noise {} with {} bits got {} at CAD = {} getting {} more bits".format(noise, bits, int(max(keyrates)*bits), keyrates.index(max(keyrates))+1, int(max(keyrates)*bits) - int(keyrates[0]*bits)))
return int(max(keyrates)*bits)
seed1 = "gen"
seed2 = "ran"
seed3 = "ent"
seed4 = "qkd"
PRNG_gen = None
PRNG_ran = None
PRNG_ent = None
PRNG_qkd = None
# global filt
# filt = None
def main(N, n, T, p, q, d, Pz = 1/2, Px = 1/2, glob=False, dumb=False, simple = False, finite = False, finite_block = 1e5, topog = "grid"):
#print(N, n, T, p, q, d, Pz , Px , glob, dumb)
if T is None:
print("T=", T, "Aborting")
return -1,1
global PRNG_gen
global PRNG_ran
global PRNG_ent
global PRNG_qkd
PRNG_gen = random.Random(uuid.UUID(seed1) if type(seed1) is str else seed1)
PRNG_ran = random.Random(uuid.UUID(seed2) if type(seed2) is str else seed2)
PRNG_ent = random.Random(uuid.UUID(seed3) if type(seed3) is str else seed3)
PRNG_qkd = random.Random(uuid.UUID(seed4) if type(seed4) is str else seed4)
global prio_a
global prio_b
prio_a = prio_b = 0
#Set Up
(G,P,Q,D,K,Kb) = generate_network(n,T,p,q,d, topog)
if finite:
K_fin = deepcopy(K)
#G.show_graph()
G.print_graph()
#G.all_paths()
#print("Network Graph")
#G.show_graph()
#Ma in Loop
pathlength1 = 0
paths1 = 0
i = 0
channels = 0
decohered = 0
path_lengths ={}
discarded = 0
data_str = "Data for {} iterations, dim={} {}, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, n, topog, round(p,3), q, d, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
balance_inf = {i:{j: 0 for j in G.get_trusted()} for i in G.get_trusted()}
old_prioA = old_prioB = 0
while i < N:
#if i % 1000 == 0:
# print(' {0}\r'.format("Completed {} out of {}".format(i,N)))
i+=1
if i % (N/20) == 0 :
print('|',end="")
if i == N:
print("")
# print("-------Entanglement Graph-----------")
G1 = pair_ent(G,P)
#G1.show_graph()
# print("-------Routing Ent-----------")
#G1b = deepcopy(G1)
G2 = deepcopy(G1)
Pt = R1(G, G1,K, balance_inf) if glob else local_R1(G,G1,K,dumb, balance_inf) #for two trusted nodes old global R1 is actually better.
Pt2 = R1(G, G2,K, None) if glob else local_R1(G,G1,K,dumb) #for two trusted nodes old global R1 is actually better.
Pt = sorted(Pt, key = lambda x: len(x))
Pt2 = sorted(Pt2, key = lambda x: len(x))
print(Pt)
if (Pt or Pt2) and (prio_a > old_prioA or prio_b > old_prioB) and Pt != Pt2 :
old_prioB = prio_b
old_prioA = prio_a
# print()
# print("Pt1", ["{} - > {} len {}".format(x[0],x[-1], len(x) - 1) for x in sorted(Pt, key = lambda x: len(x))])
# print("Pt2", ["{} - > {} len {}".format(x[0],x[-1], len(x) - 1) for x in sorted(Pt2, key = lambda x: len(x))])
discarded += len(Pt)
#
if filt:
if filt == 1:
Pt = [x for x in Pt if .5*(1-(1-d)**(len(x)-1)) <=.11]
if filt == 2:
Pt = [x for x in Pt if len(x)-1 <11]
discarded -= len(Pt)
#print(Pt)
pathlength1 += sum([len(x)-1 for x in Pt])
paths1 += len(Pt)
for path in Pt:
if len(path)-1 in path_lengths:
path_lengths[len(path)-1] +=1
else:
path_lengths[len(path)-1] = 1
(G2, Ed, pathinf) = path_ent(G, Q, D, Pt)
channels+=len(Ed)
decohered += sum([x[-1] for x in Ed])
(G3, K, Kb, balance_inf) = attempt_QKD(G2, Ed, Pz, Px, K, Kb, pathinf, balance_inf)
if finite and not simple and not i % finite_block/2:
print("Checking for post-processing")
print(K)
if max([max(x.values()) for x in K.values()]) > finite_block:
K_fin = finite_process_regular(K,Kb, K_fin, finite_block)
if finite and not simple:
K_fin = finite_process_regular(K,Kb, K_fin, finite_block, True)
#print(Kb)
new_Kb_low = {i:{j: "" for j in G.get_trusted()} for i in G.get_trusted()}
new_Kb_high = {i:{j: "" for j in G.get_trusted()} for i in G.get_trusted()}
new_K_low = {i:{j: 0 for j in G.get_trusted()} for i in G.get_trusted()}
new_K_high = {i:{j: 0 for j in G.get_trusted()} for i in G.get_trusted()}
Kb_all = deepcopy(Kb)
K_all = deepcopy(K)
for x in Kb:
for y in Kb[x]:
counter = 0
acc = 0
se = dict()
for keybit in Kb[x][y]:
counter +=1
acc += keybit[1]
if keybit[1] in se:
se[keybit[1]] +=1
else:
se[keybit[1]]=0
if counter:
#print("Average for ",x,y, "is", acc/counter)
#print("{} to {} average error rate was {}, counts were {}".format(x,y,acc/counter, se))
for keybit in Kb[x][y]:
if keybit[1] < acc/counter:
new_Kb_high[x][y]+=keybit[0]
new_K_high[x][y]+=1
else:
new_Kb_low[x][y]+=keybit[0]
new_K_low[x][y]+=1
newlist = [keybit[0] for keybit in Kb[x][y]]
Kb[x][y] = "".join(newlist)
#print("Standard Processing")
(maxflow, errors, K, Kb) = (0,0,{},{})# R2_simple(G3, K, Kb) if simple else R2_regular(G3,K, Kb)
if simple:
print("Error, how to do segmenting with simple")
exit(0)
else:
#print("High Error Rate Bits")
(maxflow_low, errors_low, new_K_low, new_Kb_low) = (0,0,{},{}) #R2_regular(G3,new_K_low, new_Kb_low)
#print("Low Error Rate Bits ")
(maxflow_high, errors_high, new_K_high, new_Kb_high) = (0,0,{},{}) # R2_regular(G3,new_K_high, new_Kb_high)
print("Individual Error Rates PROC")
(maxflow_all, errors_all, K_all, Kb_all) = R2_regular_all(G3, K_all, Kb_all)
# print(maxflow_all, maxflow_low, maxflow_high, maxflow)
# print("COMPARE", maxflow_all, maxflow_low+maxflow_high, maxflow)
print("Balacing info")
print(balance_inf)
print("Final Stats: {} rounds resulted in {} {} key bits with {} errors with {} TNs at {}".format(i, maxflow, "secret" if not simple else "raw" , errors, len(G.trusted)-2, G.trusted))
print(" Results in {} secret key bits".format( max(0,int((1-2*binary_entropy(float(errors/maxflow)))*maxflow)) if maxflow else 0 ))
print("Stats")
print(" Total connections ", paths1)
print(" Average connections ", paths1/i)
print(" Average connection length ", pathlength1/paths1 if paths1 else 0)
print(" Total established channels", channels)
print(" Total decohered channels", decohered)
print(" Average channels", channels/i)
print(" Average decohered", decohered/channels if channels else 0)
print(" Path lengths and counts:")
for path in path_lengths:
print(" Length {}, Count {}, Expected E = {}".format(path, path_lengths[path], .5*(1-(1-d)**path)))
print(" Discarded {} paths".format(discarded))
try:
print(" Expected total error {} paths".format(sum([path_lengths[path]*.5*(1-(1-d)**path) for path in path_lengths])/sum([path_lengths[path] for path in path_lengths])))
except:
pass
# for k in k_errors:
# for kb in k_errors:
# if k_errors[k][kb][0]:
# try:
# print("pre- {} - > {} had {} bits and {} errors, error rate of {}".format(k, kb, k_errors[k][kb][0],k_errors[k][kb][1],k_errors[k][kb][1]/k_errors[k][kb][0]))
# except:
# print("pre- {} - > {} had {} bits and {} errors, error rate of {}".format(k, kb, k_errors[k][kb][0],k_errors[k][kb][1],0))
try:
print(" Overall had {} bits and {} errors, error rate of {}".format(maxflow, errors, errors/maxflow if maxflow else 0))
except:
print(" Overall had {} bits and {} errors, error rate of {}".format(maxflow, errors, 0))
print("")
print("Key rate without segmenting was {} with {} errors".format(maxflow/N, errors))
print("Key rate with half segmenting was {}".format("{} +{} = {}".format(maxflow_low/N, maxflow_high/N, (maxflow_low+maxflow_high)/N)))
print("Key rate with all segmenting was {}".format(maxflow_all / N))
print(maxflow_all, maxflow, maxflow_low+maxflow_high)
print("\nBEST KEY RATE WAS {}".format(max(maxflow_all, maxflow, maxflow_low+maxflow_high)/N))
return maxflow_all, errors
def write_data(filename, data):
with open(filename, "w+") as f:
f.write("L/N")
for key in data:
f.write("{},".format(key))
f.write("\n")
for key1 in data:
for key2 in data[key1]:
f.write("{},".format(key2))
for val in data[key1][key2]:
break
def binary_entropy(Q):
if abs(Q - 0) <= .000000001 or abs(Q - 1) <= .000000001:
return 0
try:
return -Q*log2(Q)-(1-Q)*log2(1-Q)
except ValueError:
print("Value error!")
print(Q)
raise RuntimeError
def print_data(data0, data1):
for key in data0:
print("Data for a {}x{} grid".format(key,key))
print("L, T0, T1")
for key2 in data0[key]:
print("{}{}, {}, {}".format(key2, " "* (len(str(max(data0[key]))) - len(str(key2))),
data0[key][key2], data1[key][key2]))
print("")
def print_and_write(string,file):
save = sys.stdout
sys.stdout = file
print(string)
sys.stdout.flush()
sys.stdout = save
print(string)
def print_save_data(data_array, header_array, data_str, var, file):
print_and_write("\"{}\"".format(data_str), file)
header = "{}, ".format(var) + ", ".join(header_array)
print_and_write(header, file)
for v in data_array[0].keys():
line = "{}, ".format(v) + ", ".join([str(d[v]) for d in data_array])
print_and_write(line, file)
return
def gather_data(glob, dumb, simple, fixed_len, N, size, L, Q, E, Pz, Px, var, file, asym = False, Trusted_Nodes = False):
if var != "S":
Trusted0 = [0, size*size-1]
Trusted1 = [0, int((size*size-1)/2), size*size-1]
Trusted2 = [0, size-1, size*(size-1), size*size-1]
Trusted3 = [0, math.floor(size/3)*(size+1),size*size-1-math.floor(size/3)*(size+1), size*size-1]
Trusted4 = [0, int((size*size-1)/2)-size-1, int((size*size-1)/2), size*size-1]
Trusted5 = [0, (size+1)*2, (size*size-1)-(size+1)*2, size*size-1]
if len(set(Trusted5)) == 3:
Trusted5 = [0, (size+1)*1, (size*size-1)-(size+1)*1, size*size-1]
#Trusted0 = None
# Trusted1 = None
Trusted2 = None
Trusted3 = None
Trusted4 = None
Trusted5 = None
#v = size
if Trusted_Nodes:
if len(Trusted_Nodes) < 5:
Trusted_Nodes+=[None]*5
Trusted0 = Trusted_Nodes[0]
Trusted1 = Trusted_Nodes[1]
Trusted2 = Trusted_Nodes[2]
Trusted3 = Trusted_Nodes[3]
Trusted4 = Trusted_Nodes[4]
Trusted5 = Trusted_Nodes[5]
alpha = .15
if var != "P" and var != "S":
P = 10**-(alpha*(L/size)/10) if fixed_len else 10**-(alpha*L/10)
#Trusted1 = [0, size*size-size, size*size-1]
t0 = {}
t1 = {}
t2 = {}
t3 = {}
t4 = {}
t5 = {}
if var == "P":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, "var", Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in L:
P = 10**-(alpha*(v/size)/10) if fixed_len else 10**-(alpha*v/10)
print("L={} P = {}".format(v, P))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t2[v] = main(N,size, Trusted2, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t3[v] = main(N,size, Trusted3, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t4[v] = main(N,size, Trusted4, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t5[v] = main(N,size, Trusted5, P, Q, E, Pz, Px, glob, dumb,simple)
elif var == "Q":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, round(L,3), "var", E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in Q:
print(" Q = {}".format(v))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, v ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size, Trusted2, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size, Trusted3, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size, Trusted4, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size, Trusted5, P, v, E, Pz, Px, glob, dumb, simple)
elif var == "E":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, round(L,3), Q, "var", Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in E:
print(" E = {}".format(v))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size, Trusted2, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size, Trusted3, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size, Trusted4, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size, Trusted5, P, Q, v, Pz, Px, glob, dumb, simple)
elif var == "S":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, "var", "var", L, Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in size:
Trusted0 = [0, v*v-1]
Trusted1 = [0, int((v*v-1)/2), v*v-1]
Trusted2 = [0, v-1, v*(v-1), v*v-1]
Trusted3 = [0, math.floor(v/3)*(v+1),v*v-1-math.floor(v/3)*(v+1), v*v-1]
Trusted4 = [0, int((v*v-1)/2)-v-1, int((v*v-1)/2), v*v-1]
Trusted5 = [0, (v+1)*2, (v*v-1)-(v+1)*2, v*v-1]
if len(set(Trusted5)) == 3:
Trusted5 = [0, (v+1)*1, (v*v-1)-(v+1)*1, v*v-1]
# Trusted0 = None
# Trusted1 = None
Trusted2 = None
Trusted3 = None
Trusted4 = None
Trusted5 = None
P = 10**-(alpha*(L/v)/10) if fixed_len else 10**-(alpha*L/10)
print(" Size = {}".format(v))
print(" ",end=""); t0[v] = main(N, v, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N, v, Trusted1, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N, v, Trusted2, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N, v, Trusted3, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N, v, Trusted4, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N, v, Trusted5, P, Q, E, Pz, Px, glob, dumb, simple)
elif var == None:
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}"\
.format(N, size, size, round(L,3), Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
v = "N/A"
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size, Trusted2, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size, Trusted3, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size, Trusted4, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size, Trusted5, P, Q, E, Pz, Px, glob, dumb, simple)
else:
print("{} data is not supported, can only vary P, Q, E, or S")
err0 = {v: t0[v][1]/max(t0[v][0],1) if t0[v][0] > 0 else "N/A" for v in t0}
err1 = {v: t1[v][1]/max(t1[v][0],1) if t1[v][0] > 0 else "N/A" for v in t1}
err2 = {v: t2[v][1]/max(t2[v][0],1) if t2[v][0] > 0 else "N/A" for v in t2}
err3 = {v: t3[v][1]/max(t3[v][0],1) if t3[v][0] > 0 else "N/A" for v in t3}
err4 = {v: t4[v][1]/max(t4[v][0],1) if t4[v][0] > 0 else "N/A" for v in t4}
err5 = {v: t5[v][1]/max(t5[v][0],1) if t5[v][0] > 0 else "N/A" for v in t5}
key_rate0 = {v: max(0,1-2*binary_entropy(err0[v])) if err0[v] != "N/A" else 0 for v in err0}
key_rate1 = {v: max(0,1-2*binary_entropy(err1[v])) if err1[v] != "N/A" else 0 for v in err1}
key_rate2 = {v: max(0,1-2*binary_entropy(err2[v])) if err2[v] != "N/A" else 0 for v in err2}
key_rate3 = {v: max(0,1-2*binary_entropy(err3[v])) if err3[v] != "N/A" else 0 for v in err3}
key_rate4 = {v: max(0,1-2*binary_entropy(err4[v])) if err4[v] != "N/A" else 0 for v in err4}
key_rate5 = {v: max(0,1-2*binary_entropy(err5[v])) if err5[v] != "N/A" else 0 for v in err5}
eff_rate0 = {v: key_rate0[v]*t0[v][0]/(4*N) for v in key_rate0}
eff_rate1 = {v: key_rate1[v]*t1[v][0]/(4*N) for v in key_rate1}
eff_rate2 = {v: key_rate2[v]*t2[v][0]/(4*N) for v in key_rate2}
eff_rate3 = {v: key_rate3[v]*t3[v][0]/(4*N) for v in key_rate3}
eff_rate4 = {v: key_rate4[v]*t4[v][0]/(4*N) for v in key_rate4}
eff_rate5 = {v: key_rate5[v]*t5[v][0]/(4*N) for v in key_rate5}
keybits_rate0 = {v: t0[v][0]/N for v in key_rate0}
keybits_rate1 = {v: t1[v][0]/N for v in key_rate1}
keybits_rate2 = {v: t2[v][0]/N for v in key_rate2}
keybits_rate3 = {v: t3[v][0]/N for v in key_rate3}
keybits_rate4 = {v: t4[v][0]/N for v in key_rate4}
keybits_rate5 = {v: t5[v][0]/N for v in key_rate5}
# header_array = ["keybits_rate0", "keybits_rate1", "keybits_rate2", "keybits_rate3","effective_keyrate0", "effective_keyrate1", "effective_keyrate2", "effective_keyrate3", "keyrate0", "keyrate1", "keyrate2", "keyrate3", "errrate0", "errate1","errrate2", "errate3", "keybits0, errors0", "keybits1, errors1", "keybits2, errors2", "keybits3, errors3"]
# data_array = [keybits_rate0, keybits_rate1, keybits_rate2, keybits_rate3,eff_rate0, eff_rate1, eff_rate2, eff_rate3, key_rate0, key_rate1,key_rate2, key_rate3, err0, err1,err2, err3, {p: t0[p][0] for p in t0},{p: t0[p][1] for p in t0}, {p: t1[p][0] for p in t1}, {p: t2[p][1] for p in t2}, {p: t3[p][0] for p in t3}]
header_array = ["NoTN", "Central", "Corner", "Diagonal", "Asym", "2Hops"]
data_array = [keybits_rate0, keybits_rate1, keybits_rate2, keybits_rate3, keybits_rate4, keybits_rate5]
print_save_data(data_array, header_array, data_str, var, file)
return eff_rate0, eff_rate1
def gather_data_center(glob, dumb, simple, fixed_len, N, size, L, Q, E, Pz, Px, var, file, asym = False, finite = False):
if var != "S":
Trusted0 = [0, size*size-1]
Trusted1 = [0, int((size*size-1)/2), size*size-1]
Trusted2 = [0+size+3, (size+2)*(size+2)-1-size-3]
Trusted3 = [0+size+3, int(((size+2)*(size+2)-1)/2), (size+2)*(size+2)-1-size-3]
# Trusted4 = [0+size+5, (size+4)*(size+4)-1-size-5]
# Trusted5 = [0+size+5, int(((size+4)*(size+4)-1)/2), (size+4)*(size+4)-1-size-5]
Trusted4 = [0+2*(size+5), (size+4)*(size+4)-1-2*(size+5)]
Trusted5 = [0+2*(size+5), int(((size+4)*(size+4)-1)/2), (size+4)*(size+4)-1-2*(size+5)]
# Trusted0 = None
# Trusted1 = None
# Trusted2 = None
# Trusted3 = None
# Trusted4 = None
# Trusted5 = None
#v = size
print(Trusted0)
print(Trusted1)
print(Trusted2)
print(Trusted3)
print(Trusted4)
print(Trusted5)
alpha = .15
if var != "P" and var != "S":
P = 10**-(alpha*(L/size)/10) if fixed_len else 10**-(alpha*L/10)
#Trusted1 = [0, size*size-size, size*size-1]
t0 = {}
t1 = {}
t2 = {}
t3 = {}
t4 = {}
t5 = {}
if var == "P":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, "var", Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in L:
P = 10**-(alpha*(v/size)/10) if fixed_len else 10**-(alpha*v/10)
print("L={} P = {}".format(v, P))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t2[v] = main(N,size+2, Trusted2, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t3[v] = main(N,size+2, Trusted3, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t4[v] = main(N,size+4, Trusted4, P, Q, E, Pz, Px, glob, dumb,simple)
print(" ",end=""); t5[v] = main(N,size+4, Trusted5, P, Q, E, Pz, Px, glob, dumb,simple)
elif var == "Q":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, round(L,3), "var", E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in Q:
print(" Q = {}".format(v))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, v ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size+2, Trusted2, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size+2, Trusted3, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size+4, Trusted4, P, v, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size+4, Trusted5, P, v, E, Pz, Px, glob, dumb, simple)
elif var == "E":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, size, size, round(L,3), Q, "var", Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in E:
print(" E = {}".format(v))
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size+2, Trusted2, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size+2, Trusted3, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size+4, Trusted4, P, Q, v, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size+4, Trusted5, P, Q, v, Pz, Px, glob, dumb, simple)
elif var == "S":
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}"\
.format(N, "var", "var", L, Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
for v in size:
Trusted0 = [0, v*v-1]
Trusted1 = [0, int((v*v-1)/2), v*v-1]
Trusted2 = [0, v-1, v*(v-1), v*v-1]
Trusted3 = [0, math.floor(v/3)*(v+1),v*v-1-math.floor(v/3)*(v+1), v*v-1]
Trusted4 = [0, int((v*v-1)/2)-v-1, int((v*v-1)/2), v*v-1]
Trusted5 = [0, (v+1)*2, (v*v-1)-(v+1)*2, v*v-1]
if len(set(Trusted5)) == 3:
Trusted5 = [0, (v+1)*1, (v*v-1)-(v+1)*1, v*v-1]
# Trusted0 = None
#Trusted1 = None
Trusted1 = [v+3, (v+2)*(v+2)-(v+4)]
Trusted2 = None
Trusted3 = None
Trusted4 = None
Trusted5 = None
P = 10**-(alpha*(L/v)/10) if fixed_len else 10**-(alpha*L/10)
print(" Size = {}".format(v))
print(" ",end=""); t0[v] = main(N, v, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N, v+2, Trusted1, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N, v, Trusted2, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N, v, Trusted3, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N, v, Trusted4, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N, v, Trusted5, P, Q, E, Pz, Px, glob, dumb, simple)
elif var == None:
data_str = "Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}"\
.format(N, size, size, round(L,3), Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
print(data_str)
v = "N/A"
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t1[v] = main(N,size, Trusted1, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t2[v] = main(N,size, Trusted2, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t3[v] = main(N,size, Trusted3, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t4[v] = main(N,size, Trusted4, P, Q, E, Pz, Px, glob, dumb, simple)
print(" ",end=""); t5[v] = main(N,size, Trusted5, P, Q, E, Pz, Px, glob, dumb, simple)
else:
print("{} data is not supported, can only vary P, Q, E, or S")
err0 = {v: t0[v][1]/max(t0[v][0],1) if t0[v][0] > 0 else "N/A" for v in t0}
err1 = {v: t1[v][1]/max(t1[v][0],1) if t1[v][0] > 0 else "N/A" for v in t1}
err2 = {v: t2[v][1]/max(t2[v][0],1) if t2[v][0] > 0 else "N/A" for v in t2}
err3 = {v: t3[v][1]/max(t3[v][0],1) if t3[v][0] > 0 else "N/A" for v in t3}
err4 = {v: t4[v][1]/max(t4[v][0],1) if t4[v][0] > 0 else "N/A" for v in t4}
err5 = {v: t5[v][1]/max(t5[v][0],1) if t5[v][0] > 0 else "N/A" for v in t5}
key_rate0 = {v: max(0,1-2*binary_entropy(err0[v])) if err0[v] != "N/A" else 0 for v in err0}
key_rate1 = {v: max(0,1-2*binary_entropy(err1[v])) if err1[v] != "N/A" else 0 for v in err1}
key_rate2 = {v: max(0,1-2*binary_entropy(err2[v])) if err2[v] != "N/A" else 0 for v in err2}
key_rate3 = {v: max(0,1-2*binary_entropy(err3[v])) if err3[v] != "N/A" else 0 for v in err3}
key_rate4 = {v: max(0,1-2*binary_entropy(err4[v])) if err4[v] != "N/A" else 0 for v in err4}
key_rate5 = {v: max(0,1-2*binary_entropy(err5[v])) if err5[v] != "N/A" else 0 for v in err5}
eff_rate0 = {v: key_rate0[v]*t0[v][0]/(4*N) for v in key_rate0}
eff_rate1 = {v: key_rate1[v]*t1[v][0]/(4*N) for v in key_rate1}
eff_rate2 = {v: key_rate2[v]*t2[v][0]/(4*N) for v in key_rate2}
eff_rate3 = {v: key_rate3[v]*t3[v][0]/(4*N) for v in key_rate3}
eff_rate4 = {v: key_rate4[v]*t4[v][0]/(4*N) for v in key_rate4}
eff_rate5 = {v: key_rate5[v]*t5[v][0]/(4*N) for v in key_rate5}
keybits_rate0 = {v: t0[v][0]/N for v in key_rate0}
keybits_rate1 = {v: t1[v][0]/N for v in key_rate1}
keybits_rate2 = {v: t2[v][0]/N for v in key_rate2}
keybits_rate3 = {v: t3[v][0]/N for v in key_rate3}
keybits_rate4 = {v: t4[v][0]/N for v in key_rate4}
keybits_rate5 = {v: t5[v][0]/N for v in key_rate5}
# header_array = ["keybits_rate0", "keybits_rate1", "keybits_rate2", "keybits_rate3","effective_keyrate0", "effective_keyrate1", "effective_keyrate2", "effective_keyrate3", "keyrate0", "keyrate1", "keyrate2", "keyrate3", "errrate0", "errate1","errrate2", "errate3", "keybits0, errors0", "keybits1, errors1", "keybits2, errors2", "keybits3, errors3"]
# data_array = [keybits_rate0, keybits_rate1, keybits_rate2, keybits_rate3,eff_rate0, eff_rate1, eff_rate2, eff_rate3, key_rate0, key_rate1,key_rate2, key_rate3, err0, err1,err2, err3, {p: t0[p][0] for p in t0},{p: t0[p][1] for p in t0}, {p: t1[p][0] for p in t1}, {p: t2[p][1] for p in t2}, {p: t3[p][0] for p in t3}]
# header_array = ["NoTN5x5", "CenterTN5x5", "NoTN7x7", "CenterTN5x5", "Asym", "2Hops"]
header_array = ["NoTN", "Central", "Corner", "Diagonal", "Asym", "2Hops"]
data_array = [keybits_rate0, keybits_rate1, keybits_rate2, keybits_rate3, keybits_rate4, keybits_rate5]
print_save_data(data_array, header_array, data_str, var, file)
return eff_rate0, eff_rate1
def gather_all_data(data_file, log_file, simple):
N = 10 #10,000 takes 530 seconds for all data
#~1 minute per thousand iterations
size = 5
L = 1 #15
Q = .85
E = .02
glob = False
dumb = True
fixed_len = False
simple = False
Pz = 1/2
Px = 1 - Pz
size_range = [5,7,9,11,13,15]
#size_range = [2,3,4,5,6,7,8,9,10]
L_range = [1,3,5,10,15]
Q_range = [1,.95, .85, .75, .65][::-1]
E_range = [.035, .05, .065]
#E_range = [0, .02, .035, .05, .065][::-1]
filename = data_file
with open(filename, "w+") as f:
pass
T0e, T1e = gather_data(glob, dumb, simple,fixed_len, N, size, L, Q, E_range, Pz, Px, "E", f)
# T0p, T1p = gather_data(glob, dumb, simple,fixed_len, N, size, L_range, Q, E, Pz, Px, "P", f)
# T0q, T1q = gather_data(glob, dumb, simple,fixed_len, N, size, L, Q_range, E, Pz, Px, "Q", f)
# T0e, T1e = gather_data(glob, dumb, simple,fixed_len, N, size_range, L, Q, E, Pz, Px, "S", f)
# T0e, T1e = gather_data(False, True, simple,fixed_len, N, size_range, L, Q, E, Pz, Px, "S", f)
# T0e, T1e = gather_data(False, False, simple,fixed_len, N, size_range, L, Q, E, Pz, Px, "S", f)
# T0e, T1e = gather_data(True, dumb, simple,fixed_len, N, size_range, L, Q, E, Pz, Px, "S", f)
def gather_balance_data(size, P,Q,E):
t0 = {}
t1 = {}
Trusted0 = [0, ((size*size)-1)/2 - (size+1) , size*size-1]
Trusted1 = [size+3, ((size+2)*(size+2)-1)/2-(size+3), (size+2)*(size+2)-1-(size+3)]
print(Trusted0)
print(Trusted1)
data_str = "Balance var Data for {} iterations, {}x{} Grid, L = {}, Q = {}, E = {}, Pz = {}, Global Info = {}, TN Type = {}".format(N, size, size, L, Q, E, Pz, glob if glob else "{}, Smart = {}".format(glob, not dumb), "regular" if not simple else "simple")
for v in B:
print(" Balance = {}".format(v))
print(data_str)
balance = v
print(" ",end=""); t0[v] = main(N,size, Trusted0, P, Q ,E, Pz, Px, glob, dumb, Simple)
print(" ",end=""); t1[v] = main(N,size+2, Trusted1, P, Q ,E, Pz, Px, glob, dumb, Simple)
import sys
import uuid
seed1 = uuid.uuid4()
seed2 = uuid.uuid4()
seed3 = uuid.uuid4()
seed4 = uuid.uuid4()
# seed1 = "cdf2c994-2584-4327-98c3-17f476fee6ae"
# seed2 = "9492208f-8f46-4d9c-900f-3345114daad1"
# seed3 = "67d23430-e345-45ef-9b83-b8e6d6f1bdbe"
# seed4 = "9c379b36-9b29-4ef9-83e9-bde9f1bfc76b"
seed1 = "b41cfa2e-611e-4f35-81bb-309187bdbbb5"
seed2 = "bb37ddc8-7acc-4b68-b6e0-39eabf9a87f3"
seed3 = "09f08618-f17b-4c4c-b164-64276f092d7b"
seed4 = "60c3ac4e-5387-4caa-89dc-15bf3ffadd89"
print("seed1 = \"{}\" ".format(seed1))
print("seed2 = \"{}\" ".format(seed2))
print("seed3 = \"{}\" ".format(seed3))
print("seed4 = \"{}\" ".format(seed4))
main(10, 3, [0,8], 10.**(-.15/10),1,0, glob=True, dumb = False, topog = "grid")
main(10, 10, [], 10.**(-.15/10),1,0, glob=True, dumb = False, topog = "ring")
main(10, 10, [11], 10.**(-.15/10),1,0, glob=True, dumb = False, topog = "ring")
balance = None
CAD = True
if __name__ == 'x__main__':
print("in main")
N = int(1e6)
b = 1.2
size = 7
L = 1
Q = .85
E = .02
glob = False
dumb = False
fixed_len = False
simple = False
Pz = 1/2
Px = 1 - Pz
P = 10**-(.15*(L/10) )
size_range = [5,7,9,11,13]
L_range = [1,3,5,10,15]
Q_range = [1,.95, .85, .75, .65][::-1]
E_range = [0, .02, .035, .05, .065, .075, .085, .095, .11][::-1]
# Central = [8,24,40]
# Unbalanced = [8,16,40]
Central = [10, 40, 70]
Central = [10, 30, 70]
if sys.argv[2] == "CAD":
CAD = True
else:
CAD = False
filename = "balance{}{}{}{}.csv".format(b,sys.argv[1],"CAD" if CAD else "")
file = open(filename, "w+")
print(sys.argv)
Trusted_Nodes = [Central, Unbalanced]
if sys.argv[1] == "L":
print("Doing L")
balance = None
file.write("Balance = {} Global CAD = {} \n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L_range, Q, E, Pz, Px, "P", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {} \n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L_range, Q, E, Pz, Px, "P", file, False, Trusted_Nodes)
balance = b
file.write("Balance = {} Global CAD = {} \n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L_range, Q, E, Pz, Px, "P", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {} \n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L_range, Q, E, Pz, Px, "P", file, False, Trusted_Nodes)
if sys.argv[1] == "Q":
balance = None
file.write("Balance = {} Global CAD = {}\n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L, Q_range, E, Pz, Px, "Q", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {}\n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L, Q_range, E, Pz, Px, "Q", file, False, Trusted_Nodes)
balance = b
file.write("Balance = {} Global CAD = {}\n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L, Q_range, E, Pz, Px, "Q", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {}\n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L, Q_range, E, Pz, Px, "Q", file, False, Trusted_Nodes)
if sys.argv[1] == "E":
balance = None
file.write("Balance = {} Global CAD = {}\n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L, Q, E_range, Pz, Px, "E", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {}\n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L, Q, E_range, Pz, Px, "E", file, False, Trusted_Nodes)
balance = b
file.write("Balance = {} Global CAD = {}\n".format(balance, CAD))
gather_data(True, False, simple, fixed_len, N, size+2, L, Q, E_range, Pz, Px, "E", file, False, Trusted_Nodes)
file.write("Balance = {} Smart CAD = {}\n".format(balance, CAD))
gather_data(False, False, simple, fixed_len, N, size+2, L, Q, E_range, Pz, Px, "E", file, False, Trusted_Nodes)
if __name__ == 'x__main__':
# main(100000, 3, [0,8], 10.**(-.15/10),.75,.02, glob=True, dumb = False)
# main(100000, 3, [0,8], 10.**(-.15/10),.75,.02, glob=True, dumb = False)
# exit(0)
# if len(sys.argv) < 2:
# print("No input")
# import time
# #time.sleep(3)
# sys.argv.append("1")
# sys.argv[1] = int(sys.argv[1])
sys.argv.append(0)
filename = "prelim_data{}.csv".format(sys.argv[1])
filt = sys.argv[1]
print("Filtering type", filt)
with open(filename, "w+") as f:
N = int(1e6) #10,000 takes 530 seconds for all data
#~1 minute per thousand iterations [Finished in 2547.8s]
b = 1.2
size = 5
L = 1
Q = 1
E = .03
glob = True
dumb = False
fixed_len = False
simple = False
Pz = 1/2
Px = 1 - Pz
P = 10**-(.15*(L/10) )
size_range = [5,7,9,11,13]
L_range = [1,3,5,10,15]
Q_range = [1,.95, .85, .75, .65][::-1]
E_range = [0, .02, .035, .05, .065][::-1]
E_range = [.005]
# balance = None
# main(N, size, [0,6,24], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("unBalanced 5x5, non-embedded")
# balance = b
# main(N, size, [0,6,24], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, non-embedded")
main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, False, False, False)
print("Balance is, ", balance)
print("Balanced 5x5, embedded")
print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
balance = 1.1
main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, False, False, False)
print("Balance is, ", balance)
print("Balanced 5x5, embedded")
print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
# balance = 1.2
# main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, embedded")
# print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
# balance = 1.3
# main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, embedded")
# print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
# balance = 1.4
# main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, embedded")
# print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
# balance = 1.5
# main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, embedded")
# print("Prioritized a {} times and prioritized b {} times".format(prio_a,prio_b))
# # balance = 1.275
# main(N, size+2, [8,16,40], P, Q ,E, Pz, Px, True, False, False)
# print("Balance is, ", balance)
# print("Balanced 5x5, embedded")
# # noise = .046658
# # bits = 96725
# # x1,minvalx1 = cad_opt(noise, 1)
# # print(bits*x1)
# # x2, minvalx2 = cad_opt(noise, 2)
# # print(bits*x2)
# # x3, minvalx3 = cad_opt(noise, 3)
# # print(bits*x3)
# # x4,minvalx4 = cad_opt(noise, 4)
# # print(bits*x4)
# # print("-----------------------")
# # print(x1,minvalx1, bits*x1)
# # print(x2,minvalx2, bits*x2)
# # print(x3,minvalx3, bits*x3)
# # print(x4,minvalx4, bits*x4)
# # noise = .0993528
# # bits = 96726
# # x1, minvalx1 = cad_opt(noise, 1)
# # print(bits*x1)
# # x2, minvalx2 = cad_opt(noise, 2)
# # print(bits*x2)
# # x3, minvalx3 = cad_opt(noise, 3)
# # print(bits*x3)
# # x4, minvalx4 = cad_opt(noise, 4)
# # print(minvalx4,bits*x4)
# # print(x1, minvalx1,bits*x1)
# # print(x2,minvalx2, bits*x2)
# # print(x3,minvalx3,bits*x3)
# # print(x4,minvalx4,bits*x4)
# main(N, size, [0,12,24], P, Q ,E, Pz, Px, True, False, False)
# print("central 5x5, non-embedded")
# main(N, size+2, [8,24,40], P, Q ,E, Pz, Px, True, False, False)
# print("Central 5x5, embedded")
# main(N, 7, [0,24,48], P, Q ,E, Pz, Px, True, False, False)
# print("central 7x7, non-embedded")
# main(N, 9, [10,40,70], P, Q ,E, Pz, Px, True, False, False)
# print("central 7x7, embedded")
# main(N, size, [0,12,24], P, .65 ,E, Pz, Px, True, False, False)
# print("central 5x5, non-embedded")
# main(N, size+2, [8,24,40], P, .65 ,E, Pz, Px, True, False, False)
# print("Central 5x5, embedded")
# main(N, size, [0,12,24], P, Q ,E, Pz, Px, True, False, False)
# print("central 5x5, non-embedded")
# main(N, size+2, [8,24,40], P, Q ,E, Pz, Px, True, False, False)
# print("Central 5x5, embedded")
#gather_data_center(False, True, False,False , N, size, L, Q, E_range, Pz, Px, "E", f)
exit(0)