Skip to content

Commit

Permalink
conduction only works when there are no disconnected intersects
Browse files Browse the repository at this point in the history
  • Loading branch information
leobrowning92 committed Mar 21, 2018
1 parent 2ac31f1 commit e3e4ddd
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 38 deletions.
34 changes: 20 additions & 14 deletions network.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import argparse
import numpy as np
import networkx as nx
import matplotlib
Expand Down Expand Up @@ -44,7 +45,7 @@ def update_conductivity(self):
def make_G(self):
"""Generates the adjacency matrix of the graph as a numpy array and then sets the diagonal elements as the -ve sum of the conductances that attach to it.
"""
G=np.array(nx.to_numpy_matrix(self.graph,nodelist=sorted(self.graph.nodes()),weight='conductance'))
G=np.array(nx.to_numpy_matrix(self.graph,nodelist=self.graph.nodes(),weight='conductance'))
for i in range(self.network_size):
for j in range(self.network_size):
if i==j:
Expand All @@ -59,6 +60,8 @@ def make_A(self, G):
BTD=np.append(B.T,D,axis=1)
A=np.append(np.append(G,B,axis=1),BTD,axis=0)
A=np.delete(np.delete(A,self.ground_nodes,0),self.ground_nodes,1)
plt.matshow(A,vmin=-1,vmax=1)
plt.show()
return A
def make_z(self):
z = np.append(np.zeros((self.network_size-len(self.ground_nodes),1)), self.voltage_sources[:,1][:,None], axis=0)
Expand Down Expand Up @@ -95,18 +98,21 @@ def show_network(self,v=False):
ax1=plt.subplot(111)
self.plot_network(ax1,v=v)
plt.show()
def show_device(self,v=False):
fig = plt.figure(figsize=(10,10),facecolor='white')
ax1=plt.subplot(111)
self.plot_network(ax1,v=v)
self.plot_regions(ax1)
ax1.legend()
plt.show()
def show_device(self,v=False,ax=False):
if not(ax):
fig = plt.figure(figsize=(10,10),facecolor='white')
ax=plt.subplot(111)
self.plot_network(ax,v=v)
self.plot_regions(ax)
ax.legend()
if not(ax):
plt.show()
def plot_regions(self,ax):
for a in self.gate_areas:
ax.add_patch(patches.Rectangle( (a[0][0]-a[0][2]/2,a[0][1]-a[0][3]/2), a[0][2],a[0][3], edgecolor='b', fill=False, label="Local $V_G$ = {} V".format(a[1])))
ax.add_patch(patches.Rectangle( (-0.02,.48), 0.04,0.04, edgecolor='r', fill=False,label="Source = {} V".format(self.vds)))
ax.add_patch(patches.Rectangle( (.98,0.48), 0.04,0.04, edgecolor='k', fill=False, label="GND = 0 V"))
ax.add_patch(patches.Rectangle( (.98,0.48), 0.04,0.04, edgecolor='k',
fill=False, label="GND = 0 V"))
def plot_network(self,ax1,v=False):
pos={k:self.graph.nodes[k]['pos'] for k in self.graph.nodes}
# for i in range(self.network_rows):
Expand All @@ -124,11 +130,11 @@ def plot_network(self,ax1,v=False):
edgecurrents=nx.get_edge_attributes(self.graph,'current')
edgeresistance=nx.get_edge_attributes(self.graph,'resistance')
nx.draw_networkx_edge_labels(self.graph,pos, edge_labels={k:'{:.1e}A\n{:.1e}$\Omega$'.format(edgecurrents[k], edgeresistance[k]) for k in edgecurrents})
divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes('right', size='5%', pad=0.5)
cax2 = divider1.append_axes('right', size='5%', pad=0.5)
plt.colorbar(edges,label="Current A",cax=cax2)
plt.colorbar(nodes,label="Node Voltage V",cax=cax1)
# divider1 = make_axes_locatable(ax1)
# cax1 = divider1.append_axes('right', size='5%', pad=0.5)
# cax2 = divider1.append_axes('right', size='5%', pad=0.5)
# plt.colorbar(edges,label="Current A",cax=cax2)
# plt.colorbar(nodes,label="Node Voltage V",cax=cax1)
def set_global_gate(self,voltage):
for edge in self.graph.edges:
self.graph.edges[edge]['component'].gate_voltage=voltage
Expand Down
104 changes: 80 additions & 24 deletions percolation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import argparse
import numpy as np
import pandas as pd
import matplotlib
Expand All @@ -8,10 +9,10 @@
import networkx as nx

class StickCollection(object):
def __init__(self,n,l,sticks=None):
def __init__(self,n,l,sticks=None,pm=0,scaling=1):
if sticks:
self.sticks, self.intersects = self.make_clusters(sticks)
self.sticks, self.intersects = self.make_clusters(self.make_sticks(n,l=l))
self.sticks, self.intersects = self.make_clusters(self.make_sticks(n,l=l,pm=pm,scaling=scaling))

def check_intersect(self, s1,s2):
#assert that x intervals overlap
Expand Down Expand Up @@ -41,13 +42,15 @@ def get_ends(self, row):
y2=yc-length/2*np.sin(angle)
return np.array([ [x1,y1],[x2,y2] ])

def make_stick(self,l=None,kind='s'):
def make_stick(self,l=None,kind='s',pm=0,scaling=1):
"""makes a stick with [xc, yc, angle, length, kind, endarray]
the end array is of the form [ [x1,y1],[x2,y2] ]"""
if np.random.rand()<=pm:
kind='m'
if l:
stick=[np.random.rand(), np.random.rand(), np.random.rand()*2*np.pi, l,kind]
stick=[np.random.rand(), np.random.rand(), np.random.rand()*2*np.pi, l/scaling,kind]
else:
stick= [np.random.rand(), np.random.rand(), np.random.rand()*2*np.pi, abs(np.random.normal(0.66,0.44))/60,kind]
stick= [np.random.rand(), np.random.rand(), np.random.rand()*2*np.pi, abs(np.random.normal(0.66,0.44))/scaling,kind]
stick.append(self.get_ends(stick))
return stick

Expand All @@ -73,19 +76,52 @@ def make_clusters(self, sticks):
if intersection and 0<=intersection[0]<=1 and 0<=intersection[1]<=1:
sticks.loc[sticks.cluster==sticks.loc[j,'cluster'],'cluster'] = sticks.loc[i,'cluster']
intersects.append([i,j,*intersection, sticks.iloc[i].kind+sticks.iloc[j].kind])
self.percolating=sticks.loc[0,"cluster"]==sticks.loc[len(sticks)-1,"cluster"]
return sticks,pd.DataFrame(intersects, columns=["stick1",'stick2','x','y','kind'])

def show_sticks(self,intersects=True):
def show_system(self,clustering=True,junctions=True,conduction=True):
fig = plt.figure(figsize=(15,5))
axes=[fig.add_subplot(1,3,i+1) for i in range(3)]
if clustering:
self.show_clusters(ax=axes[0])
if junctions:
self.show_sticks(ax=axes[1])
if conduction and self.percolating:
self.solve_cnet()
self.cnet.show_device(ax=axes[2])
plt.show()
def show_clusters(self,intersects=True,ax=False):
sticks=self.sticks
fig=plt.figure(figsize=(5,5))
ax=fig.add_subplot(111)
if not(ax):
fig=plt.figure(figsize=(5,5))
ax=fig.add_subplot(111)
colors=np.random.rand(len(sticks),3)
colorpattern=[colors[i] for i in sticks.cluster.values]
collection=LineCollection(sticks.endarray.values,linewidth=0.5,colors=colorpattern)
ax.add_collection(collection)
# if intersects:
# ax.scatter(self.intersects.x, self.intersects.y, c="r", s=30, linewidth=0.8, marker="x")
ax.set_xlim((-0.02,1.02))
ax.set_ylim((-0.02,1.02))
ax.set_title("$n_{{clusters}}$={}\nConnected={}".format(len(self.sticks.cluster.drop_duplicates()),str(self.percolating)))
if not(ax):
plt.show()
def show_sticks(self,intersects=True,ax=False):
sticks=self.sticks
if not(ax):
fig=plt.figure(figsize=(5,5))
ax=fig.add_subplot(111)
stick_cmap={'s':'b','m':'r','v':'y','g':'k'}
stick_colors=[stick_cmap[i] for i in sticks.kind]
collection=LineCollection(sticks.endarray.values,linewidth=0.5,colors=stick_colors)
ax.add_collection(collection)
isect_cmap={'ms':'g','sm':'g', 'mm':'k','ss':'k', 'vs':'k','vm':'k', 'sg':'k','mg':'k'}
isect_colors=[isect_cmap[i] for i in self.intersects.kind]
if intersects:
ax.scatter(self.intersects.x, self.intersects.y, c="r", s=30, linewidth=0.8, marker="x")
plt.show()
ax.scatter(self.intersects.x, self.intersects.y, c=isect_colors, s=20, linewidth=1, marker="x")
ax.set_xlim((-0.02,1.02))
ax.set_ylim((-0.02,1.02))
if not(ax):
plt.show()

def make_test_sticks(self):
source=[0.01, 0.5,np.pi/2-1e-6,1,'v']
Expand All @@ -96,13 +132,18 @@ def make_test_sticks(self):
st1.append(self.get_ends(st1))
st2=[0.7, 0.5,-np.pi/4,1,'s']
st2.append(self.get_ends(st2))
sticks=pd.DataFrame([source]+[st1]+[st2]+[drain],columns=[ "xc", "yc", "angle", "length",'kind', "endarray"])
st3=[0.5, 0.5,-np.pi/4,0.1,'s']
st3.append(self.get_ends(st3))
st4=[0.5, 0.5,np.pi/4,0.1,'s']
st4.append(self.get_ends(st4))
sticks=pd.DataFrame([source]+[st1]+[st2]+[st3]+[st4]+[drain],columns=[ "xc", "yc", "angle", "length",'kind', "endarray"])
self.sticks, self.intersects = self.make_clusters(sticks)

def make_graph(self):
self.graph=nx.from_pandas_edgelist(self.intersects, source='stick1',target='stick2',edge_attr=True)
self.ground_nodes=[0]
self.voltage_sources=[[len(self.sticks)-1,0.1]]

self.ground_nodes=[len(self.graph)-1]
self.voltage_sources=[[0,0.1]]
self.populate_graph()
for node in self.graph.nodes():
self.graph.nodes[node]['pos'] = [self.sticks.loc[node,'xc'], self.sticks.loc[node,'yc']]
Expand All @@ -116,19 +157,34 @@ def populate_graph(self):


def solve_cnet(self):
assert self.percolating, "The network is not conducting!"
self.cnet=ConductionNetwork(*self.make_graph())
# print(self.cnet.make_G(),'\n')
# print(self.cnet.make_A(self.cnet.make_G()))
self.cnet.set_global_gate(0)
self.cnet.set_local_gate([0.5,.7,0.4,1], 10)
# self.cnet.set_local_gate([0.5,.7,0.4,1], 10)
self.cnet.update()
print(self.cnet.source_currents)
self.cnet.show_device()
# show_sticks(make_sticks(10,l=1))
# print(self.cnet.source_currents)


# show_sticks(make_sticks(10,l=1))

collection=StickCollection(100,l=0.5)
collection.show_sticks()
# collection.make_test_sticks()
# print(len(collection.sticks.cluster.drop_duplicates()))
collection.solve_cnet()
# collection.show_sticks()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("number",type=int)
parser.add_argument("--pm",type=float,default=0.135)
parser.add_argument("--length",type=float,default=0)
parser.add_argument("--scaling",type=float,default=5)
parser.add_argument("-t", "--test", action="store_true")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
if args.test:
collection=StickCollection(10,l=1,pm=args.pm,scaling=1)
collection.make_test_sticks()
collection.show_system(conduction=False)
collection.solve_cnet()
else:
collection=StickCollection(args.number,l=args.length,pm=args.pm,scaling=args.scaling)
collection.show_system(conduction=False)
collection.solve_cnet()
# print(len(collection.sticks.cluster.drop_duplicates()))

0 comments on commit e3e4ddd

Please sign in to comment.