In [2]:
%matplotlib inline
import networkx as nx
#import pygraphviz
import pyparsing
import numpy as np
import matplotlib.pylab as plt

from IPython.display import Math

In [3]:
A = np.array([[0,1,1],[0,0,1],[1,0,0]])
G = nx.Graph(A)

labels = {0: "a", 1:"b", 2:"c"}
pos = [(0,0),(3,1),(1,0)]
plt.figure(figsize=(12,2.5))
nx.draw(G, pos, cmap='jet', edge_color=[0.1,0.7,0.9], node_color="white", node_size=500, labels=labels, font_size=10, arrows=True)
#nx.draw(G, pos, node_color="white", node_size=500, arrows=False)
#nx.draw_graphviz(G,node_size=500, labels=labels, font_size=24, arrows=True)
plt.show()

#nx.draw_networkx()


/Users/cemgil/anaconda/envs/py27/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py:126: MatplotlibDeprecationWarning: pyplot.hold is deprecated.
    Future behavior will be consistent with the long-time default:
    plot commands add elements without first clearing the
    Axes and/or Figure.
  b = plt.ishold()
/Users/cemgil/anaconda/envs/py27/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py:138: MatplotlibDeprecationWarning: pyplot.hold is deprecated.
    Future behavior will be consistent with the long-time default:
    plot commands add elements without first clearing the
    Axes and/or Figure.
  plt.hold(b)
/Users/cemgil/anaconda/envs/py27/lib/python2.7/site-packages/matplotlib/__init__.py:917: UserWarning: axes.hold is deprecated. Please remove it from your matplotlibrc and/or style files.
  warnings.warn(self.msg_depr_set % key)
/Users/cemgil/anaconda/envs/py27/lib/python2.7/site-packages/matplotlib/rcsetup.py:152: UserWarning: axes.hold is deprecated, will be removed in 3.0
  warnings.warn("axes.hold is deprecated, will be removed in 3.0")

In [5]:
from itertools import product

M = 6;
N = 6
Z = 1.7
NN = M*N

A = np.zeros((NN,NN))
X = np.zeros((NN))
Y = np.zeros((NN))

sig = 0.1;
coords = []
#cols = ("blue","red","yellow","black")
cols = ("black","black")
col = []
for i,j in product(range(N),range(M)):
    ex = np.random.randn(1)*sig
    ey = np.random.randn(1)*sig
    coords.append((j,i))
    X[i*M+j] = i+ex
    Y[i*M+j] = j+ey
    col.append(np.random.choice(cols))
    
    
    
for k,r in product(range(NN),range(NN)):
    if k != r:
        d = (X[k]-X[r])**2 + (Y[k]-Y[r])**2
        A[k,r] = 1 if d < Z else 0

G = nx.Graph(A)

plt.figure(figsize=(M,N))
#nx.draw(G, pos, node_color="white", node_size=500, labels=labels, font_size=10, arrows=True)
nx.draw(G, coords, node_color='black', node_size=200, arrows=False, linewidths=14.)
nx.draw_networkx_nodes(G, coords, node_color='white', node_size=200, arrows=False, linewidths=11., linecolors='black')
#nx.draw_graphviz(G,node_size=500, labels=labels, font_size=24, arrows=True)
plt.show()



In [6]:
#t = nx.dfs_tree(G,17)
t = nx.bfs_tree(G,1)
#t = nx.prim_mst(G)
plt.figure(figsize=(M,N))
nx.draw(t, coords, node_size=200,node_color="black",linewidths=14.)
nx.draw_networkx_nodes(t, coords, node_color="white", node_size=200,linewidths=11.)

plt.show()



In [7]:
#nx.view_pygraphviz(G)
N = 20
#H = nx.random_graphs.watts_strogatz_graph(N,5,0.1)
H = nx.random_graphs.random_regular_graph(3,N)

lbl = {e:e for e in range(N)}
#nx.view_pygraphviz(H)
nx.draw_networkx_nodes(H,node_color="black",alpha=1, node_size=500, pos=nx.spectral_layout(H))
nx.draw(H,labels=lbl,node_color="white",alpha=1, node_size=400, pos=nx.spectral_layout(H))



In [10]:
G = nx.Graph()

d = 10
G.add_node(0)
coord = [(0.5,0)]
depth = [0]

for n in range(2,256*4):
    G.add_node(n-1)
    p = int(np.floor(n/2))
    depth.append(depth[p-1]+1)
    if 2*p==n: # left child
        ep = -(1.0/(2**(depth[p-1]+2)))
    else:
        ep = 1.0/(2**(depth[p-1]+2)) 
    coord.append((coord[p-1][0]+ep,-(depth[p-1]+1)))
    G.add_edge(n-1,p-1)

plt.figure(figsize=(35,6))
nx.draw(G, coord, node_size=50, node_color='black')
#nx.draw_shell



In [7]:
import heapq
import numpy as np

N = 50
thr = 0.35
lb = 0.1
X = np.random.rand(N,2)
D = np.zeros((N,N))

for i,j in product(range(N),range(N)):
    D[i,j] = np.sqrt((X[i,0]-X[j,0])**2 + (X[i,1]-X[j,1])**2)
    if D[i,j]>thr or D[i,j]<lb :
        D[i,j] = np.Inf

visited = np.empty(N,dtype=bool); visited.fill(False)

root = 0
visited[root] = True
numvis = 1;
spt = np.empty(N,dtype=int)
spt.fill(-1)
spt[root] = -1

q = []


for j in range(N):
    if np.isfinite(D[root,j]):
        heapq.heappush(q, (D[root,j], root, j))


while numvis<N:
    if len(q)==0:
        break;
    d,i,j = heapq.heappop(q)
    while len(q)>0 and visited[j]:
        d,i,j = heapq.heappop(q)
        
    spt[j] = i
    visited[j] = True
    numvis+=1
    
    for k in range(N):
        if np.isfinite(D[j,k]) and not visited[k]:
            heapq.heappush(q, (D[j,k], j, k))
    
print(spt)
    
plt.figure(figsize=(10,10))
plt.plot(X[:,0],X[:,1],'o')
for i,j in product(range(N),range(N)):
    if not np.isinf(D[i,j]):
        plt.plot(X[[i,j],0],X[[i,j],1],'k:')
        
for u in range(N):
    if spt[u]!=-1:
        plt.plot(X[[u,spt[u]],0],X[[u,spt[u]],1],'r-')
    


plt.show()


[-1  0 49 11 28 26 36 14 29 41 20  1 20 49 48 35 22  0  2 40 36 11 12 13  3
 21 43 16 38  0 45 41 36 36 23  3 28 29 15 18 44 26  4  7 38  5 24 19 18 21]

In [3]:
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import math

min_radius = 0.1
N = 100

x = np.random.rand(N)
y = np.random.rand(N)

# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)

# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
triang.set_mask(mask)

# Plot the triangulation.
plt.figure(figsize=(5,5))
plt.gca().set_aspect('equal')
plt.triplot(triang, 'bo-')
plt.title('triplot of Delaunay triangulation')
plt.show()


  • Traveling Salesman
  • Complete Binary tree
  • Spanning Tree
  • Bipartite Graph
  • Shortest Path Tree

In [1]:
import pygraphviz as pgv
from IPython.display import Image
from IPython.display import display

In [9]:
def random_alphabet(N=20, first_letter='A'):
    """Generates unique strings to be used as index_names"""
    if N<27:
        alphabet = [chr(i+ord(first_letter)) for i in range(N)]
    else:
        alphabet = ['X'+str(i) for i in range(N)]    
    return alphabet

def random_parents(alphabet, max_indeg=3):
    """Random DAG generation"""
    N = len(alphabet)
    print(alphabet)
    indeg = lambda: np.random.choice(range(1,max_indeg+1))
    parents = {a:[b for b in np.random.choice(alphabet[0:(1 if i==0 else i)], replace=False, size=min(indeg(),i))] for i,a in enumerate(alphabet)}
    return parents

def show_dag_image(index_names, parents, imstr='_BJN_tempfile.png', prog='dot'):
    name2idx = {name: i for i,name in enumerate(index_names)}
    A = pgv.AGraph(directed=True)
    for i_n in index_names:
        A.add_node(name2idx[i_n], label=i_n)
        for j_n in parents[i_n]:
            A.add_edge(name2idx[j_n], name2idx[i_n])
    A.layout(prog=prog)
    A.draw(imstr)
    display(Image(imstr))
    return 

index_names = random_alphabet(10)
parents = random_parents(index_names, 3)
show_dag_image(index_names, parents, prog='neato')


['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

Road Network

We will build a 2D square grid where neighbors are connected

Remove Random junctions for a more realistic view Compute a smooth height z by a linear dynamics Transform x,y,z and print


In [139]:
import numpy as np
import scipy as sc
import pandas as pd

from itertools import product

def ind2idx(i,j, M, N):
    return i + M*j

def idx2ind(k, M, N):
    return k % M, k//M

def neigh(i,j, M, N):    
    ng = {'n': None, 's': None, 'w': None, 'e': None}
    
    # north
    if i>0:
        ng['n'] = ind2idx(i-1,j,M,N)
    # south
    if i<M-1:
        ng['s'] = ind2idx(i+1,j,M,N)
    
    # west
    if j>0:
        ng['w'] = ind2idx(i,j-1,M,N)

    #east
    if j<N-1:
        ng['e'] = ind2idx(i,j+1,M,N)
    
    return ng

# Build a grid of junctions
M, N = 12,15

#ng = neigh(0,0,M,N)
#print(ng)
        
## Build the Adjecency list of the undirected graph
Adj = [[] for i in range(M*N)]


for j in range(N):
    for i in range(M):
        k = ind2idx(i,j,M,N)
        ng = neigh(i,j,M,N)
        
        south = ng['s']  
        if south is not None:
            Adj[k].append(south)
            Adj[south].append(k)
        
        if np.random.rand()<0.8:
            east = ng['e']
            if east is not None:
                Adj[k].append(east)
                Adj[east].append(k)
        
        # print(k,Adj[k])
        
# Kill a fraction of nodes randomly
kill = np.random.choice(range(M*N), size=M*N//10)
for k in kill:
    for u in Adj[k]:
        Adj[u].remove(k)
    Adj[k] = []
    
## Place nodes on a perturbed grid
X = 0.9*np.random.rand(N) + np.arange(0, N)
Y = 0.9*np.random.rand(M) + np.arange(0, M)

Coords = np.zeros((M*N, 3))

for k in range(M*N):
    i, j = idx2ind(k, M, N)
    Coords[k, 0] = X[j]+0.1*np.random.randn()
    Coords[k, 1] = Y[i]+0.1*np.random.randn()
    Coords[k, 2] = np.random.rand()

## Iterate to get a smooth terrain  
EPOCHS = 30

for e in range(EPOCHS):
    perm = np.random.permutation(M*N)
    for k in perm:
        if Adj[k]:
            Coords[k,2] = 0.9*Coords[k,2] + 0.1*np.mean(Coords[Adj[k],2])

In [136]:
plot_topology(Adj, M, N)



In [140]:
merge = np.random.choice(range(M*N), replace=False, size=30)
for u in merge:
    if Adj[u]:
        v = np.random.choice(Adj[u])
        
        # Disconnect v from u
        Adj[v].remove(u)
        Adj[u].remove(v)
        
        ## transfer all the remaining edges to v
        for w in Adj[u]:
            if w not in Adj[v]:
                Adj[v].append(w)
                Adj[w].append(v)
            Adj[w].remove(u)
                

        Adj[u] = []

In [141]:
plot_topology(Adj, M, N)



In [96]:
## Print node coordinates
for k in range(M*N):
    print("%2.1f, %2.1f, %2.1f" % (Coords[k, 0], Coords[k, 1], Coords[k, 0]))
    
# Print Edges
for k in range(M*N):
    for u in Adj[k]:
        print('%d,%d' % (k,u))


0.6, 0.1, 0.6
0.5, 1.6, 0.5
0.6, 2.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.1
12.1, 5.6, 12.1
12.1, 6.2, 12.1
12.0, 7.2, 12.0
12.2, 8.9, 12.2
12.3, 9.7, 12.3
12.0, 10.0, 12.0
12.2, 11.4, 12.2
13.2, -0.0, 13.2
13.1, 1.7, 13.1
13.0, 2.3, 13.0
12.9, 3.1, 12.9
13.1, 4.5, 13.1
13.2, 5.4, 13.2
13.2, 6.3, 13.2
13.1, 7.2, 13.1
13.0, 8.8, 13.0
13.2, 9.8, 13.2
13.1, 10.2, 13.1
13.0, 11.3, 13.0
14.9, 0.2, 14.9
14.8, 1.5, 14.8
14.6, 2.1, 14.6
14.7, 3.3, 14.7
14.8, 4.5, 14.8
14.6, 5.6, 14.6
14.6, 6.4, 14.6
14.6, 7.1, 14.6
14.8, 8.7, 14.8
14.9, 9.9, 14.9
14.9, 10.3, 14.9
14.8, 11.4, 14.8
0,1
1,0
1,2
1,25
2,1
2,14
2,15
4,5
4,16
4,15
5,4
5,6
5,29
6,5
6,7
6,18
7,6
7,8
7,19
8,7
8,9
9,8
9,10
9,21
10,9
10,11
10,22
11,10
12,24
12,25
14,2
14,15
14,26
14,25
15,14
15,16
15,27
15,2
15,4
16,4
16,15
16,28
16,29
18,6
18,19
18,30
18,29
19,7
19,18
19,20
20,19
20,21
20,32
21,9
21,20
21,22
21,33
22,10
22,21
22,23
22,34
23,22
23,35
24,12
24,25
24,36
25,24
25,26
25,1
25,12
25,14
26,14
26,25
26,27
27,15
27,26
27,28
27,39
28,16
28,27
28,29
29,28
29,30
29,41
29,5
29,16
29,18
30,18
30,29
30,31
30,42
31,30
31,32
31,43
32,20
32,31
32,33
32,44
33,21
33,32
33,34
33,45
34,22
34,33
34,35
34,46
35,23
35,34
36,24
36,48
38,39
38,50
39,27
39,38
39,51
41,29
41,42
41,53
42,30
42,41
42,43
42,54
43,31
43,42
43,44
43,55
44,32
44,43
44,45
44,56
45,33
45,44
45,46
46,34
46,45
48,36
48,49
48,60
49,48
49,50
49,61
50,38
50,49
50,51
51,39
51,50
51,63
53,41
53,54
53,65
54,42
54,53
54,55
54,66
55,43
55,54
55,56
55,67
56,44
56,55
56,57
56,68
57,56
57,69
59,71
60,48
60,61
60,72
61,49
61,60
61,62
62,61
62,63
63,51
63,62
63,64
64,63
64,65
64,77
64,88
65,53
65,64
65,66
66,54
66,65
66,67
66,78
67,55
67,66
67,68
67,79
68,56
68,67
68,69
68,80
69,57
69,68
69,70
70,69
70,71
70,82
71,59
71,70
71,83
72,60
72,73
72,84
73,72
73,85
77,78
77,89
77,64
78,66
78,77
78,79
79,67
79,78
79,80
79,91
80,68
80,79
80,81
81,80
81,82
82,70
82,81
82,83
82,94
83,71
83,82
83,95
84,72
84,85
84,96
85,73
85,84
85,86
85,109
86,85
86,87
87,86
87,88
87,99
88,87
88,89
88,64
89,77
89,88
91,79
91,92
91,103
92,91
92,116
94,82
94,95
95,83
95,94
96,84
96,108
96,109
98,99
98,110
98,109
99,87
99,98
101,102
102,101
102,103
102,114
103,91
103,102
103,115
103,116
105,117
105,116
107,119
108,96
108,109
108,120
109,108
109,110
109,121
109,85
109,96
109,98
110,98
110,109
110,111
111,110
111,112
111,123
112,111
114,102
114,115
114,126
115,103
115,114
115,116
116,115
116,117
116,128
116,92
116,103
116,105
117,105
117,116
117,118
117,129
118,117
118,119
119,107
119,118
119,131
120,108
120,121
120,132
121,109
121,120
121,122
121,133
122,121
122,123
122,134
123,111
123,122
123,124
123,135
124,123
124,125
124,135
124,137
125,124
125,126
125,137
126,114
126,125
126,127
126,138
127,126
127,128
127,139
128,116
128,127
128,129
129,117
129,128
129,130
129,141
130,129
130,131
130,142
131,119
131,130
131,143
132,120
132,133
133,121
133,132
133,134
133,145
134,122
134,133
134,135
134,146
135,123
135,134
135,147
135,124
137,125
137,138
137,124
138,126
138,137
138,139
138,150
139,127
139,138
139,151
141,129
141,142
142,130
142,141
142,143
142,154
143,131
143,142
143,155
144,145
144,156
145,133
145,144
145,146
145,157
146,134
146,145
146,147
146,158
147,135
147,146
147,159
150,138
150,151
150,162
151,139
151,150
151,152
151,163
152,151
152,153
153,152
153,154
153,165
154,142
154,153
154,155
154,166
155,143
155,154
156,144
156,157
156,169
157,145
157,156
157,158
157,169
158,146
158,157
158,159
158,170
159,147
159,158
159,160
160,159
160,161
160,172
161,160
161,162
161,173
162,150
162,161
162,163
163,151
163,162
163,164
164,163
164,165
164,176
165,153
165,164
165,166
165,177
166,154
166,165
169,157
169,170
169,156
170,158
170,169
170,171
171,170
171,172
172,160
172,171
172,173
173,161
173,172
173,174
174,173
174,175
175,174
175,176
176,164
176,175
176,177
177,165
177,176
177,178
178,177

In [112]:
import matplotlib.pylab as plt

def plot_topology(Adj, M, N):
    plt.figure(figsize=(10,10))
    for k,ls in enumerate(Adj):
        i,j = idx2ind(k, M,N)
        for u in ls:
            i_target, j_target = idx2ind(u, M,N)
            plt.plot([j, j_target ],[i, i_target],'k')

        if Adj[k]:
            plt.plot(j, i,'ro')

    plt.show()
    
plot_topology(Adj, M, N)



In [98]:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')

for k,ls in enumerate(Adj):
    for u in ls:
        ax.plot([Coords[k,0], Coords[u,0] ],[Coords[k,1], Coords[u,1] ], [Coords[k,2], Coords[u,2] ],'k')
      
    if Adj[k]:
        ax.plot([Coords[k,0]], [Coords[k,1]], [Coords[k,2]], 'ro')
    

ax.set_zlim([0, 1])
    
plt.show()



In [69]:
for k in range(M*N):
    print("%2.1f, %2.1f, %2.1f" % (Coords[k, 0], Coords[k, 1], Coords[k, 0]))
    
for k in range(M*N):
    for u in Adj[k]:
        print('%d,%d' % (k,u))


0.8, 0.3, 0.8
0.8, 1.4, 0.8
0.8, 2.6, 0.8
0.8, 3.1, 0.8
0.8, 4.5, 0.8
0.8, 5.4, 0.8
0.7, 6.0, 0.7
0.6, 7.6, 0.6
0.9, 8.2, 0.9
0.8, 9.3, 0.8
1.5, 0.3, 1.5
1.5, 1.5, 1.5
1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, 5.4, 8.0
8.1, 6.0, 8.1
8.2, 7.7, 8.2
8.3, 8.5, 8.3
8.1, 9.4, 8.1
9.4, 0.1, 9.4
9.3, 1.4, 9.3
9.4, 2.5, 9.4
9.3, 3.0, 9.3
9.4, 4.6, 9.4
9.6, 5.4, 9.6
9.4, 6.1, 9.4
9.2, 7.6, 9.2
9.6, 8.4, 9.6
9.4, 9.3, 9.4
1,2
1,11
2,1
2,12
4,5
4,14
5,4
5,6
5,15
6,5
6,7
6,16
7,6
7,17
9,19
10,11
11,1
11,10
11,12
11,21
12,2
12,11
12,13
12,22
13,12
13,14
13,23
14,4
14,13
14,15
14,24
15,5
15,14
15,16
15,25
16,6
16,15
16,17
17,7
17,16
17,18
17,27
18,17
18,19
18,28
19,9
19,18
19,29
20,21
20,30
21,11
21,20
21,22
21,31
22,12
22,21
22,23
23,13
23,22
23,24
23,33
24,14
24,23
24,25
25,15
25,24
25,26
25,35
26,25
26,27
26,36
27,17
27,26
27,28
27,37
28,18
28,27
28,29
29,19
29,28
29,39
30,20
30,31
30,40
31,21
31,30
31,41
33,23
33,34
33,43
34,33
34,35
34,44
35,25
35,34
35,36
36,26
36,35
36,37
37,27
37,36
37,38
37,47
38,37
38,39
38,48
39,29
39,38
39,49
40,30
40,41
40,50
41,31
41,40
43,33
43,44
43,53
44,34
44,43
44,45
45,44
45,46
45,55
46,45
46,47
46,56
47,37
47,46
47,48
47,57
48,38
48,47
48,49
49,39
49,48
49,59
50,40
50,51
50,60
51,50
51,52
51,61
52,51
52,53
52,62
53,43
53,52
53,54
54,53
54,55
54,64
55,45
55,54
55,56
55,65
56,46
56,55
56,57
56,66
57,47
57,56
57,58
57,67
58,57
58,59
58,68
59,49
59,58
59,69
60,50
60,61
60,70
61,51
61,60
61,62
61,71
62,52
62,61
62,72
64,54
64,65
64,74
65,55
65,64
65,66
65,75
66,56
66,65
66,67
67,57
67,66
67,68
67,77
68,58
68,67
68,69
68,78
69,59
69,68
69,79
70,60
70,71
71,61
71,70
71,72
72,62
72,71
72,73
73,72
73,74
73,83
74,64
74,73
74,75
74,84
75,65
75,74
75,76
75,85
76,75
76,77
77,67
77,76
77,78
78,68
78,77
78,79
79,69
79,78
79,89
82,83
82,92
83,73
83,82
83,84
83,93
84,74
84,83
84,85
84,94
85,75
85,84
85,95
87,88
87,97
88,87
88,89
88,98
89,79
89,88
89,99
92,82
92,93
93,83
93,92
93,94
94,84
94,93
94,95
95,85
95,94
95,96
96,95
96,97
97,87
97,96
97,98
98,88
98,97
98,99
99,89
99,98

In [11]:
G = nx.Graph(A)

plt.figure(figsize=(M,N))
#nx.draw(G, pos, node_color="white", node_size=500, labels=labels, font_size=10, arrows=True)
nx.draw(G, coords, node_color='black', node_size=200, arrows=False, linewidths=14.)
nx.draw_networkx_nodes(G, coords, node_color='white', node_size=200, arrows=False, linewidths=11., linecolors='black')
#nx.draw_graphviz(G,node_size=500, labels=labels, font_size=24, arrows=True)
plt.show()



In [7]:
import itertools
import numpy as np
import matplotlib.pylab as plt
import daft

# Instantiate the PGM.
pgm = daft.PGM([3.6, 3.6], origin=[0.7, 0.7], node_unit=0.4, grid_unit=1,
        directed=False)

for i, (xi, yi) in enumerate(itertools.product(range(1, 5), range(1, 5))):
    pgm.add_node(daft.Node(str(i), "", xi, yi))


for e in [(4, 9), (6, 7), (3, 7), (10, 11), (10, 9), (10, 14),
        (10, 6), (10, 7), (1, 2), (1, 5), (1, 0), (1, 6), (8, 12), (12, 13),
        (13, 14), (15, 11)]:
    pgm.add_edge(str(e[0]), str(e[1]))

# Render and save.
pgm.render()
#pgm.figure.savefig("mrf.pdf")
#pgm.figure.savefig("mrf.png", dpi=150)


plt.show(pgm.ax)



In [9]:
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)

import daft

pgm = daft.PGM([3.6, 2.4], origin = [1.15, 0.8], node_ec="none")
pgm.add_node(daft.Node("cloudy", r"cloudy", 3, 3))
pgm.add_node(daft.Node("rain", r"rain", 2, 2))
pgm.add_node(daft.Node("sprinkler", r"sprinkler", 4, 2))
pgm.add_node(daft.Node("wet", r"grass wet", 3, 1))
pgm.add_edge("cloudy", "rain")
pgm.add_edge("cloudy", "sprinkler")
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()

plt.show(pgm.ax)



In [11]:
from matplotlib import rc

ff = "comic sans ms"
# ff = "impact"
# ff = "times new roman"

rc("font", family=ff, size=12)
rc("text", usetex=False)

import daft

pgm = daft.PGM([3.6, 1.8], origin=[2.2, 1.6], aspect=2.1)
pgm.add_node(daft.Node("confused", r"confused", 3.0, 3.0))
pgm.add_node(daft.Node("ugly", r"ugly font", 3.0, 2.0, observed=True))
pgm.add_node(daft.Node("bad", r"bad talk", 5.0, 2.0, observed=True))
pgm.add_edge("confused", "ugly")
pgm.add_edge("ugly", "bad")
pgm.add_edge("confused", "bad")
pgm.render()
plt.show(pgm.ax)



In [12]:
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)

import daft

# Instantiate the PGM.
pgm = daft.PGM([2.3, 2.05], origin=[0.3, 0.3])

# Hierarchical parameters.
pgm.add_node(daft.Node("alpha", r"$\alpha$", 0.5, 2, fixed=True))
pgm.add_node(daft.Node("beta", r"$\beta$", 1.5, 2))

# Latent variable.
pgm.add_node(daft.Node("w", r"$w_n$", 1, 1))

# Data.
pgm.add_node(daft.Node("x", r"$x_n$", 2, 1, observed=True))

# Add in the edges.
pgm.add_edge("alpha", "beta")
pgm.add_edge("beta", "w")
pgm.add_edge("w", "x")
pgm.add_edge("beta", "x")

# And a plate.
pgm.add_plate(daft.Plate([0.5, 0.5, 2, 1], label=r"$n = 1, \cdots, N$",
    shift=-0.1))

# Render and save.
pgm.render()
plt.show(pgm.ax)



In [13]:
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)

import daft

# Colors.
p_color = {"ec": "#46a546"}
s_color = {"ec": "#f89406"}

pgm = daft.PGM([3.6, 3.5], origin=[0.7, 0])

n = daft.Node("phi", r"$\phi$", 1, 3, plot_params=s_color)
n.va = "baseline"
pgm.add_node(n)
pgm.add_node(daft.Node("speckle_coeff", r"$z_i$", 2, 3, plot_params=s_color))
pgm.add_node(daft.Node("speckle_img", r"$x_i$", 2, 2, plot_params=s_color))

pgm.add_node(daft.Node("spec", r"$s$", 4, 3, plot_params=p_color))
pgm.add_node(daft.Node("shape", r"$g$", 4, 2, plot_params=p_color))
pgm.add_node(daft.Node("planet_pos", r"$\mu_i$", 3, 3, plot_params=p_color))
pgm.add_node(daft.Node("planet_img", r"$p_i$", 3, 2, plot_params=p_color))

pgm.add_node(daft.Node("pixels", r"$y_i ^j$", 2.5, 1, observed=True))

# Edges.
pgm.add_edge("phi", "speckle_coeff")
pgm.add_edge("speckle_coeff", "speckle_img")
pgm.add_edge("speckle_img", "pixels")

pgm.add_edge("spec", "planet_img")
pgm.add_edge("shape", "planet_img")
pgm.add_edge("planet_pos", "planet_img")
pgm.add_edge("planet_img", "pixels")

# And a plate.
pgm.add_plate(daft.Plate([1.5, 0.2, 2, 3.2], label=r"exposure $i$",
    shift=-0.1))
pgm.add_plate(daft.Plate([2, 0.5, 1, 1], label=r"pixel $j$",
    shift=-0.1))

# Render and save.
pgm.render()
plt.show(pgm.ax)



In [33]:
%connect_info


{
  "stdin_port": 57484, 
  "ip": "127.0.0.1", 
  "control_port": 57485, 
  "hb_port": 57486, 
  "signature_scheme": "hmac-sha256", 
  "key": "062534bd-ecab-4960-b66c-4bdacfd6b692", 
  "shell_port": 57482, 
  "transport": "tcp", 
  "iopub_port": 57483
}

Paste the above JSON into a file, and connect with:
    $> ipython <app> --existing <file>
or, if you are local, you can connect with just:
    $> ipython <app> --existing /Users/cemgil/Library/Jupyter/runtime/kernel-28aae665-e995-49c2-a35c-c1740b4d8c4f.json 
or even just:
    $> ipython <app> --existing 
if this is the most recent IPython session you have started.