Skip to content

Instantly share code, notes, and snippets.

@fpom
Last active August 4, 2023 02:05
Show Gist options
  • Save fpom/1e9c58d614c97cd268ef507c743bc5ec to your computer and use it in GitHub Desktop.
Save fpom/1e9c58d614c97cd268ef507c743bc5ec to your computer and use it in GitHub Desktop.
Animate C code and data structures for LaTeX/beamer (replaced with https://github.com/fpom/codanim)
import collections
from inspect import Signature, Parameter, cleandoc
from pygments import highlight as _pygmentize
import pygments.lexers, pygments.formatters
##
## code pretty-printing
##
_lexer = pygments.lexers.get_lexer_by_name("C")
_formatter = pygments.formatters.get_formatter_by_name("latex")
def pygmentize (src) :
return "\n".join("\n".join(_pygmentize(line, _lexer, _formatter).splitlines()[1:-1])
for line in src.split("\n"))
##
## simulation environment
##
class Env (dict) :
def __init__ (self, *l, **k) :
super().__init__(*l, **k)
def __setitem__ (self, key, val) :
old = self.get(key, None)
if isinstance(old, Value) :
old.set(val)
else :
super().__setitem__(key, val)
def __getitem__ (self, key) :
old = self.get(key, None)
if isinstance(old, Value) :
return old.get()
else :
return super().__getitem__(key)
class CAni (object) :
_env = Env()
@property
def IP (self) :
return self._env.get("IP", 1)
@IP.setter
def IP (self, val) :
self._env["IP"] = val
class Anim (object) :
def __init__ (self) :
self.steps = collections.defaultdict(list)
def __getitem__ (self, key) :
return self.steps[key]
def range_iter (self) :
last_step, last_info = None, None
for step, info in sorted(self.steps.items()) :
if last_step is None :
last_step, last_info = step, info
elif last_info == info :
pass
else :
yield last_step, step-1, last_info
last_step, last_info = step, info
yield last_step, step, last_info
def steps_iter (self) :
inv = collections.defaultdict(set)
for step, info in self.steps.items() :
inv[tuple(info)].add(step)
def minstep (item) :
return tuple(sorted(item[1]))
for info, steps in sorted(inv.items(), key=minstep) :
yield list(sorted(steps)), list(info)
##
## data structures
##
class Value (CAni) :
def __init__ (self, init=None) :
self.hist = [[init, self.IP, None]]
self.show = set()
def get (self) :
self.show.add(self.IP)
return self.hist[-1][0]
def set (self, val) :
self.show.add(self.IP)
if self.IP == self.hist[-1][1] :
self.hist[-1][0] = val
else :
self.hist[-1][2] = self.IP-1
self.hist.append([val, self.IP, None])
def stop (self) :
self.hist[-1][2] = self.IP-1
def tex (self, w=1, h=1, x=0, y=0) :
tpl = r"""\coordinate ({id}) at ({_x},{y});
\draw[very thick,opacity=0] ({_x},{_y}) rectangle ++({w},{h});
\draw ({_x},{_y}) rectangle ++({w},{h});
{access}%% values
{states}
"""
self.stop()
if self.show :
access = cleandoc(r"""\only<{access}>{{
\draw[very thick,blue!50!black,fill=blue!20] ({_x},{_y}) rectangle ++({w},{h});
}}
""").format(w=w, h=h, x=x, y=y, _x=x-.5*w, _y=y-.5*h,
access=",".join(str(s) for s in sorted(self.show)))
else :
access = ""
return cleandoc(tpl).format(w=w, h=h, x=x, y=y, _x=x-.5*w, _y=y-.5*h,
id=self.ptrto(),
access=access,
states="\n".join(self._states(x, y)))
def ptrto (self) :
return str(id(self)).replace("-", "_")
def _states (self, x, y) :
for value, start, stop in self.hist :
if value is not None :
yield (r"\only<{start}-{stop}>{{ {state} }}"
r"").format(start=start or 1,
stop=stop or "",
state=self.tex_state(value, x, y))
def tex_state (self, value, x, y) :
return f"\\node at ({x},{y}) {{{value}}};"
class Pointer (Value) :
def __init__ (self, init=None) :
super().__init__(init)
def tex_state (self, value, x, y) :
return cleandoc(r"""\draw[thick,-latex] ({x},{y}) -- ({tgt});
\node[fill,circle,inner sep=1.5pt] at ({x},{y}) {{}};"""
"").format(x=x, y=y, tgt=value.ptrto())
class Array (CAni) :
def __init__ (self, init, index=[]) :
self.idx = {}
if isinstance(init, int) :
data = [None] * init
else :
data = list(init)
self.data = [Value(v) for v in data]
for name in index :
self.index(name)
def index (self, name, init=None) :
self.idx[name] = self._env[name] = Value(init)
def ptrto (self) :
return str(id(self)).replace("-", "_")
def __len__ (self) :
return len(self.data)
def __getitem__ (self, idx) :
return self.data[idx].get()
def __setitem__ (self, idx, val) :
self.data[idx].set(val)
def tex (self, w=1, h=1) :
tpl = r"""%% array grid
\begin{{scope}}[shift={{(-.5,-.5)}}]
\coordinate ({id}) at (0,.5);
\draw[very thick,opacity=0] (0,0) grid ({len},1);
\draw (0,0) grid ({len},1);
\end{{scope}}
\foreach \x in {{0,...,{len_1}}} {{
\node[below] at (\x,-.5) {{\relsize{{-2}}\color{{gray}}\texttt{{\x}}}};
}}
%% index
{index}
%% access
{access}
%% values
{states}
"""
return cleandoc(tpl).format(len=len(self),
len_1=len(self) - 1,
id=self.ptrto(),
index="\n".join(self._index()),
access="\n".join(self._access()),
states="\n".join(self._states()))
def _index (self) :
anim = Anim()
for name, cell in self.idx.items() :
cell.stop()
for value, start, stop in cell.hist :
for step in range(start, stop+1) :
anim[step].append((name, value))
for start, stop, info in anim.range_iter() :
xpos = collections.defaultdict(list)
for name, value in info :
if value is not None :
xpos[value].append(name)
if not xpos :
continue
yield (r"\uncover<{start}-{stop}>{{"
r"").format(start=start, stop=stop)
for value, names in xpos.items() :
yield (r" \node[above] at ({xpos},.5) {{\texttt{{{label}}}}};"
r"").format(xpos=value, label=",".join(names))
yield "}"
def _access (self) :
anim = Anim()
for pos, cell in enumerate(self.data) :
cell.stop()
for step in cell.show :
anim[step].append(pos)
for steps, info in anim.steps_iter() :
yield (r"\only<{steps}>{{"
r"").format(steps=",".join(str(s) for s in steps))
for pos in info :
yield (r" \draw[very thick,blue!50!black,fill=blue!20] "
r"({x},-.5) rectangle ++(1,1);"
r"").format(x=pos-.5)
yield "}"
def _states (self) :
anim = collections.defaultdict(list)
for pos, cell in enumerate(self.data) :
cell.stop()
for value, start, stop in cell.hist :
anim[start,stop].append((pos, value))
def firstlargest (item) :
return (item[0][0], -item[0][1])
for (start, stop), info in sorted(anim.items(), key=firstlargest) :
yield (r"\only<{start}-{stop}>{{"
r"").format(start=start, stop=stop)
for pos, value in info :
yield r" \node at ({x},0) {{{val}}};".format(x=pos, val=value)
yield "}"
class Struct (CAni) :
def __init__ (self, **members) :
self.__dict__["_members"] = dict(members)
def __getattr__ (self, name) :
if name in self._members :
return self._members[name].get()
else :
return super().__getattr__(name)
def __setattr__ (self, name, value) :
if name in self._members :
self._members[name].set(value)
else :
super.__setattr__(name, value)
def tex (self, w=1, h=1) :
return "\n".join(self._tex(w, h))
def _tex (self, w, h) :
pos = (len(self._members) - 1) * h
for name, cell in self._members.items() :
yield f"%% .{name}"
yield cell.tex(w=w, h=h, x=0, y=pos)
yield r"\node[left] at ({pos}) {{.{name}}};".format(pos=cell.ptrto(),
name=name)
pos -= h
class Data (CAni) :
def __init__ (self, *content) :
self.content = list(content)
def tex (self, *args) :
return "\n".join(self._tex(args))
def _tex (self, args) :
args = list(args)
args.extend({} for i in range(len(self.content) - len(args)))
for a, d in zip(args, self.content) :
yield r"\begin{{scope}}[{args}]".format(args=",".join("%s=%s" % i
for i in a.items()))
for line in d.tex().splitlines() :
yield " " + line
yield r"\end{scope}"
##
## code blocks
##
class _CODE (CAni) :
_fields = []
_options = []
def __init__ (self, *l, **k) :
params = []
for i, name in enumerate(self._fields) :
if name[0] == "*" :
self._fields = self._fields[:]
self._fields[i] = name[1:]
params.append(Parameter(name[1:], Parameter.VAR_POSITIONAL))
else :
params.append(Parameter(name, Parameter.POSITIONAL_OR_KEYWORD))
for name in self._options :
params.append(Parameter(name, Parameter.POSITIONAL_OR_KEYWORD, default=None))
params.append(Parameter("src", Parameter.KEYWORD_ONLY, default=None))
sig = Signature(params)
args = sig.bind(*l, **k)
args.apply_defaults()
for key, val in args.arguments.items() :
setattr(self, key, val)
self._at = set()
@property
def last (self) :
return self._env.get("LAST", None)
def __str__ (self) :
content = []
for key, val in self.items() :
if isinstance(val, _CODE) :
content.append((key, str(val)))
else :
content.append((key, repr(val)))
return "%s(%s)" % (self.__class__.__name__,
", ".join("%s=%r" % item for item in content))
def items (self) :
for field in self._fields :
yield field, getattr(self, field)
for field in self._options :
member = getattr(self, field, None)
if member is not None :
yield field, member
def source (self) :
sub = {}
for key, val in self.items() :
if isinstance(val, _CODE) :
sub[key] = val.source()
else :
sub[key] = val
return self.src.format(**sub)
def tex (self) :
sub = self.src.format(**{key : "$" for key, val in self.items()}).split("$")
parts = [pygmentize(sub[0])]
for (key, val), txt in zip(self.items(), sub[1:]) :
if isinstance(val, _CODE) :
parts.append(val.tex())
else :
parts.append(pygmentize(str(val)))
parts.append(pygmentize(txt))
tex = "".join(parts)
if self._at :
return r"\onlyhl{%s}{" % ",".join(str(i) for i in self._at) + tex + "}"
else :
return tex
class BLOCK (_CODE) :
_fields = ["*body"]
def __call__ (self) :
self._at.add(self.IP)
for code in self.body :
code()
def source (self) :
return "".join(b.source() for b in self.body)
def tex (self) :
return "".join(b.tex() for b in self.body)
class STMT (_CODE) :
_fields = ["*steps"]
def __call__ (self) :
for s in self.steps :
self._at.add(self.IP)
exec(s, self._env, self._env)
self.IP += 1
class EXPR (_CODE) :
_fields = ["expr"]
def __init__ (self, *l, **k) :
super().__init__(*l, **k)
if self.src is None :
self.src = self.expr
def __call__ (self) :
self._at.add(self.IP)
self._env["LAST"] = eval(self.expr, self._env, self._env)
self.IP += 1
class PY (_CODE) :
_fields = ["py"]
def __call__ (self) :
exec(self.py, self._env)
def tex (self) :
return ""
def source (self) :
return ""
class ENV (_CODE) :
_fields = ["name", "value"]
def __call__ (self) :
self._env[self.name] = self.value
def tex (self) :
return ""
def source (self) :
return ""
class WS (_CODE) :
_fields = []
def __init__ (self, src) :
super().__init__(src=src)
def __call__ (self) :
pass
def tex (self) :
return self.src
class DECL (_CODE) :
_fields = ["name"]
_options = ["init", "animate"]
def __init__ (self, *l, **k) :
super().__init__(*l, **k)
if self.animate is not None :
self._cell = self._env[self.name] = Value()
def __call__ (self) :
if self.init is not None :
self.init()
self._env[self.name] = self.last
else :
self._env[self.name] = None
self._at.add(self.IP)
self.IP += 1
def tex (self) :
src = super().tex()
if self.animate is None :
return src
else :
return src + " " + "".join(self._tex())
def _tex (self) :
tail = r"\PY{{c+c1}}{{/* {value} */}}"
for value, start, stop in self._cell.hist :
if value is not None :
yield (r"\onlyshow{{{start}-{stop}}}{{{value}}}"
r"").format(start=start or 1,
stop=stop or "",
value=tail.format(value=value))
class BreakLoop (Exception) :
def __init__ (self) :
super().__init__()
class BREAK (_CODE) :
def __call__ (self) :
self._at.add(self.IP)
self.IP += 1
raise BreakLoop()
class FunctionReturn (Exception) :
def __init__ (self, RET) :
super().__init__()
self.RET = RET
class RETURN (_CODE) :
_fields = ["value"]
def __call__ (self) :
self.value()
self._at.add(self.IP)
self.IP += 1
raise FunctionReturn(self.last)
class IF (_CODE) :
_fields = ["cond", "then"]
_options = ["otherwise"]
def __call__ (self) :
self.cond()
if self.last :
self.then()
elif self.otherwise is not None :
self.otherwise()
class WHILE (_CODE) :
_fields = ["cond", "body"]
def __call__ (self) :
try :
while True :
self.cond()
if not self.last :
break
self.body()
except BreakLoop :
return
class DO (_CODE) :
_fields = ["body", "cond"]
def __call__ (self) :
try :
while True :
self.body()
self.cond()
if not self.last :
break
except BreakLoop :
pass
class FOR (_CODE) :
_fields = ["init", "cond", "step", "body"]
def __call__ (self) :
self.init()
try :
while True :
self.cond()
if not self.last :
break
self.body()
self.step()
except BreakLoop :
pass
class FUNC (_CODE) :
_fields = ["body"]
def __call__ (self) :
try :
self.body()
except FunctionReturn as exc :
self._env["LAST"] = exc.RET
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
from anim import *
##
## quicksort partitioning
##
array = Array([3, 13, 5, 0, 7, 11, 4, 9, 14, 2, 10, 1, 12, 8, 6],
index=["a", "b"])
tab = Struct(len=Value(15),
val=Pointer(array))
partition = FUNC(BLOCK(ENV("t", tab),
WS(" "),
DECL("pivot", EXPR("t.val[(t.len-1)//2]",
src="t.val[(t.len-1)/2]"),
animate=True,
src="int {name} = {init};"),
WS("\n "),
DECL("a", EXPR("-1"),
src="uint {name} = {init};"),
WS("\n "),
DECL("b", EXPR("t.len"),
src="uint {name} = {init};"),
WS("\n "),
WHILE(EXPR("1", src="1"),
BLOCK(WS(" "),
DO(STMT("a+=1", src="a++;"),
EXPR("t.val[a] < pivot"),
src="do {{ {body} }} while ({cond});"),
WS("\n "),
DO(STMT("b-=1", src="b--;"),
EXPR("t.val[b] > pivot"),
src="do {{ {body} }} while ({cond});"),
WS("\n "),
IF(EXPR("a >= b"),
RETURN(EXPR("b"),
src="return {value};"),
src="if ({cond}) {{ {then} }}"),
WS("\n "),
STMT("_old = t.val[a], t.val[b]",
"t.val[b], t.val[a] = _old",
src="swap(t, a, b);"),
WS("\n")),
src="while ({cond}) {{\n{body} }}"),
WS("\n")),
src="uint partition (Tab t) {{\n{body}}}\n")
# run code and save its animation
partition.IP += 1
partition()
with open("code.tex", "w") as out :
out.write(partition.tex())
# save data anaimation
data = Data(array, tab)
with open("code.tikz", "w") as out :
out.write(data.tex({"shift": "{(2.5,0)}"}, {}))
python quicksort.py
pdflatex test
pdflatex test
\documentclass{beamer}
\usepackage[francais]{babel}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{ae}
\usepackage{tikz}
\usepackage{adjustbox}
\usepackage{fancyvrb}
\usepackage{pygments}
\usepackage{relsize}
\usetikzlibrary{arrows}
\def\hl #1{{\setbox0=\hbox{#1}%
\adjustbox{set vsize={\ht0}{\dp0}}{\hbox to \wd0{\hss\colorbox{yellow}{#1}\hss}}}}
\def\hl #1{%
\tikz[overlay,baseline,inner sep=1pt]
\node[fill=yellow,anchor=text] {\color{yellow}#1};%
#1%
}%
\def\onlyhl #1{\only<#1>\hl}
\def\onlyshow #1{\only<#1>}
\begin{document}
\begin{frame}[fragile]{Tri rapide: algorithme de partitionnement}
\VerbatimInput[commandchars=\\\{\}]{code.tex}
\begin{tikzpicture}[scale=.55]
\input{code.tikz}
\end{tikzpicture}
\end{frame}
\end{document}
@cdlm
Copy link

cdlm commented Jan 25, 2020

apparemment le fichier pygments.sty doit être généré préalablement, en exécutant pygmentize -S default -f tex > pygments.sty

@fpom
Copy link
Author

fpom commented Jan 25, 2020

En effet, j'ai oublié de le fournir.
C'est juste une toute première release, je ferai sûrement un vrai dépôt quand ça va évoluer.

@fpom
Copy link
Author

fpom commented Jan 30, 2020

New version here : https://github.com/fpom/codanim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment