Skip to content

Instantly share code, notes, and snippets.

@ghamarian
Created March 16, 2019 20:51
Show Gist options
  • Select an option

  • Save ghamarian/0ad5d04f07426eb672d806612f68b368 to your computer and use it in GitHub Desktop.

Select an option

Save ghamarian/0ad5d04f07426eb672d806612f68b368 to your computer and use it in GitHub Desktop.
only one sided but with image generator
import bezier
import networkx as nx
from matplotlib import pyplot as plt
from itertools import product
import numpy as np, numpy.random
# print(np.round(np.random.dirichlet(np.ones(10), size=1) * 170))
from matplotlib.figure import Figure
def distribute(value, nodes, max_number):
while nodes >= 1:
if nodes == 1:
yield value
return
next = np.random.randint(0, min(value + 1, max_number))
yield next
value -= next
nodes -= 1
def gen(fat_nodes, total, extra, max_number=3):
assert extra >= fat_nodes, "number of extra values must be larger than fat_nodes"
potential = np.random.choice(np.arange(total), fat_nodes, replace=False)
rand_gen = distribute(extra - fat_nodes, fat_nodes, max_number - 1)
result = np.ones(total, dtype=np.int8)
for idx, value in zip(potential, rand_gen):
result[idx] = value + 2 # The fat_nodes get two at least.
return result
def create_nodes(prefix, ids):
return [[f'{prefix}-{idx}-{k}' for k in range(value)] for idx, value in enumerate(ids)]
def neighbours(nodes, index):
neighbour_index = [index]
if index > 0:
neighbour_index.append(index - 1)
if index < len(nodes) - 1:
neighbour_index.append(index + 1)
result = []
for id in neighbour_index:
result += nodes[id]
return result
def add_layer_nodes(graph, name, fat_nodes, total, extra, max_number=3):
node_names = gen(fat_nodes, total, extra, max_number)
nodes = create_nodes(name, node_names)
for column in nodes:
graph.add_nodes_from(column)
return nodes
def flatten(nodes):
return [n for layer in nodes for n in layer]
def filter(side, node):
for grp in side:
if node in grp:
grp.remove(node)
return side
def create_side_graph(fat_nodes, total, extra, max_number=3):
G = nx.Graph()
outer = add_layer_nodes(G, 'o', fat_nodes, total, extra, max_number)
inner = add_layer_nodes(G, 'i', fat_nodes, total, extra, max_number)
pos = create_layout(inner, outer, total, 1.5)
for i, nodes in enumerate(outer):
for src in nodes:
nbrs = neighbours(inner, i)
if len(nbrs) > 0:
tgt = nbrs[np.random.randint(0, len(nbrs))]
edge = (src, tgt)
G.add_edge(*edge)
inner = filter(inner, tgt)
return G, pos
def create_layout(inner, outer, nr_nodes, distance):
shift = nr_nodes - (nr_nodes / 2) * distance
shift /= distance
pos = dict()
for i, grp in enumerate(inner):
for idx, node in enumerate(grp):
pos[node] = np.array([i, -idx - 1])
for i, grp in enumerate(outer):
for idx, node in enumerate(grp):
pos[node] = np.array([(i - shift) * distance, idx + 2])
return pos
G, pos = create_side_graph(15, 25, 25, 3)
print(G.nodes())
print(G.edges())
#
def plot(curve, num_pts=256, color=None, alpha=None, ax=None):
if curve._dimension != 2:
raise NotImplementedError(
"2D is the only supported dimension",
"Current dimension",
curve._dimension,
)
s_vals = np.linspace(0.0, 1.0, num_pts)
points = curve.evaluate_multi(s_vals)
if ax is None:
figure = plt.figure()
ax = figure.gca()
ax.plot(points[0, :],
points[1, :],
linewidth=4,
solid_capstyle='round',
color=color,
alpha=alpha)
return ax
#
# plt.subplot(111)
edgelist = list(G.edges())
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
# from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
# from matplotlib.figure import Figure
fig = plt.figure()
# canvas = FigureCanvas(fig)
ax = fig.gca()
for src, tgt in edge_pos:
xs, ys = src
xt, yt = tgt
nodes = np.asfortranarray([
[xs, xt + 0.5, xt], [ys, yt + 0.5, yt]
])
curve = bezier.Curve.from_nodes(nodes)
ax = plot(curve, ax=ax, color='black')
plt.axis('off')
# nx.draw(G, pos, with_labels=True)
# canvas.draw() # draw the canvas, cache the renderer
# image = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
fig.savefig('amir.png')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment