Created
May 1, 2019 15:39
-
-
Save ktychan/5d64a1b0476182e766a48452ff0b8a99 to your computer and use it in GitHub Desktop.
Tikz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
N = (0,1) | |
E = (1,0) | |
def normalize(path): | |
""" convert path to a list of (0,1) and (1,0) """ | |
l = len(path) | |
if l % 2 != 0: | |
raise ValueError("Not a lattice path: len(path)=%d is not even." % l) | |
if type(path) == type("NE"): | |
p = map( lambda step: {"N": N, "E": E}[step], path) | |
elif type(path) == type([N,E]): | |
p = path | |
else: | |
raise ValueError("Unknown type") | |
return (p, int(l/2)) | |
def lattice_path(path, label=[]): | |
p,n = normalize(path) | |
labelled_path = [] | |
label = label + ['' for i in range(n-len(label))] | |
i = 0 | |
for step in p: | |
if step == N: | |
labelled_path.append((step,label[i])) | |
i = i + 1 | |
else: | |
labelled_path.append((step, '')) | |
return labelled_path | |
def tikz_to_step( (dx,dy), node=''): | |
""" '-- ++(dx,dy)' with an optional node. """ | |
return "-- ++(%d,%d)%s" % (dx,dy,node) | |
def tikz_to_point( (x,y), node=''): | |
""" '-- (x,y)' with an optional node. """ | |
return "-- (%d,%d)%s" % (x,y,node) | |
def tikz_grid((x0,y0),(x1,y1)): | |
return "(%d,%d) grid (%d,%d)" % (x0,y0,x1,y1) | |
def tikz_draw(path, options): | |
return "\\draw[%s] %s;" % (options, path) | |
def tikz_draw_grid(start, end, options=''): | |
return tikz_draw(tikz_grid(start,end), options) | |
def tikz_draw_lattice_path(path, grid=True, diagonal=True, scale=1): | |
""" draw a lattice path with specified steps given by (direction, label) """ | |
n = int(len(path)/2) | |
format_step = lambda (s,label): tikz_to_step(s, "node[below left] {%s}" % str(label)) | |
lines = [ | |
"\\begin{tikzpicture}[every node/.style={transform shape}, scale=%.1f]" % scale, | |
(not grid and ' ') or tikz_draw_grid((0,0), (n,n), 'dotted, very thin'), | |
(not diagonal and ' ') or tikz_draw('(0,0) -- (%d,%d)' % (n,n), 'thin'), | |
tikz_draw(' '.join(['(0,0)'] + map(format_step, path)), 'very thick'), | |
"\\end{tikzpicture}" | |
] | |
return "\n".join([ line for line in lines if line != ' ']) # leave out blank lines | |
p = lattice_path("NNEENNEE", [1,2,3]) | |
print tikz_draw_lattice_path(p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment