Skip to the Main Content

Note:These pages make extensive use of the latest XHTML and CSS Standards. They ought to look great in any standards-compliant modern browser. Unfortunately, they will probably look horrible in older browsers, like Netscape 4.x and IE 4.x. Moreover, many posts use MathML, which is, currently only supported in Mozilla. My best suggestion (and you will thank me when surfing an ever-increasing number of sites on the web which have been crafted to use the new standards) is to upgrade to the latest version of your browser. If that's not possible, consider moving to the Standards-compliant and open-source Mozilla browser.

January 23, 2018

FreeTikZ

Posted by Tom Leinster

I don’t have to tell you, dear nn-Category Café reader, that string diagrams are extremely useful. They speed up computations massively, reveal what makes a proof tick without an impenetrable forest of details, and suggest properties that you might not even have thought about in algebraic notation. They also make your paper friendlier to read.

However, string diagrams are also a pain to typeset. First, there is the entrance fee of learning a modern LaTeX drawing package, like TikZ. Then, there is the learning period of setting up macros tailored to string diagrams and internalizing them in your muscle memory. But even after all that investment, it still takes a lot of time. And unlike that glorious moment when you realise that you have cycled about twice the circumference of the Earth in your life, this time is mostly wasted. I estimate I’ve wasted over 2000 string diagrams’ worth of time by now.

Wouldn’t it be great if you could simply draw your diagram by hand, and have it magically converted into TikZ? Now you can!

Meet FreeTikZ. It uses the magic of SVG, HTML, and Javascript, to turn

Some things to notice. To help LaTeX make sense of things like \node[dot] and \node[morphism], you will need a small latex package. This defines the shapes of the nodes. You see that FreeTikZ is geared towards morphisms that can be rotated four ways, and dots for Frobenius algebras. If you prefer different shapes, such as rectangles with a marked corner instead of morphisms, or ribbons instead of wires, or cobordism-style pictures instead of dots, this is the place to change that.

You can only draw or erase in FreeTikZ, as if you were working on paper. There is no way to move dots around once they are drawn, or to change the colour of things, or to write labels anywhere. The idea is that you use a touchscreen, or stylus, or mouse, to draw your diagram. After that, you can tweak the LaTeX code by hand, moving morphisms around, changing angles, adding labels, or whatever you like. So you still need to know a bit of TikZ, but this is much faster than typesetting your diagram from scratch.
(If you really wanted, you could load the LaTeX code into TikZiT, and change the diagram with your mouse before going to your actual LaTex file and using your keyboard.)

Finally, you can download the whole source, so you can also use FreeTikZ locally. Handy for when you don’t have an internet connection, en route to your conference, desparately making slides.

How does it work?

To let this post not completely be a blatant commercial, let’s briefly explain how FreeTikZ works. Up to some webpage bookkeeping and generating LaTeX code, the heart of the algorithm solves the following problem. You’re given a list of strokes, each stroke being a list of vectors in ℝ2\mathbb{R}^2. For each stroke, you’re asked whether it is a dot, a morphism (and if so in which orientation), or something else (that is, a wire, and if so what it connects).

How does it do that? First we compute some numerical properties of the stroke. Thinking of the stroke as spanning a polygon, we can calculate some basic properties:

Compactness: This has nothing to do with topological compactness. Instead it measures “how close together” the points of the stroke are. For example, a circle will be very compact, but a straight line will not.

Eccentricity is another fundamental characteristic of polygons. It measures the shortest distance between a point and all others, and takes the maximum of that over all points.

The two most useful properties for us are the following.

Rectangularity is the ratio between the area of the polygon itself and the area of the smallest rectangle that contains it. So a perfect rectangle will have rectangularity 1, whereas a straight line will have rectangularity 0.

Circularity is the ratio between the area of the polygon itself and the area of the smallest circle that contains it. So a perfect circle will have circularity 1, whereas a straight line will have circularity 0.

We then make a simple decision. If circularity is high enough and rectangularity low enough, then our stroke is probably a dot. If rectangularity is high enough and circularity is low enough, it is probably a morphism. (In that case, we can find out its orientation by checking whether the centroid is left/right/above/below the point furthest from the centroid.) Otherwise, we leave the stroke as a wire.

Can it be improved?

This simple decision procedure is a terrible hack, but it seems to work well enough. It would be better to train a support vector machine to make the decision for us based on all these numerical characteristics. Indeed, this is what Ruiting Cao did for her MSc thesis project, on which FreeTikZ is based. Similarly, there are other areas for improvement, but the current heuristics seem to work well enough.

Right now dots and morphisms need to be drawn in a single stroke. If you take your stylus/finger/mouse off the screen when drawing a wire, it will end up as two wires. Segmenting and joining strokes cleverly could improve the recognition.

If you would like a graphical language with more shapes than just dots and morphisms, you could tweak the characteristic properties, or ideally train and use a state vector machine.

Wires are simplified in a somewhat buggy way. You’re given a stroke with many many points. But we would like the LaTeX code not to have hundreds of points in it. At the moment wires are simplified as follows. Annotate each point with its incoming and outgoing angles. Then throw away all points that keep the same angle, up to a certain threshold. So if your stroke has angles 90, 90, 90, 90, 89, 87, 80, 60, 45, 40, 0, you would delete all points except the ones with angles 90, 60, 45, 0 (if the threshold is 30 degrees). But, for example, especially at the start of a stroke when the user just put the pen to the screen, the angle could be off, but that is the one that will be used. There are probably better heuristics.

Luckily, all you need to know is a little JavaScript to make FreeTikZ fit all your needs! What would you like to implement?

Posted at January 23, 2018 2:01 PM UTC

TrackBack URL for this Entry: https://golem.ph.utexas.edu/cgi-bin/MT-3.0/dxy-tb.fcgi/3009

31 Comments & 0 Trackbacks

Re: FreeTikZ

In your example, the hand-drawn input shows a very nearly straight line at the bottom-right, but in the output it’s been converted into a gentle S shape. I think the output looks good, but I’m curious as to why this happened.

It makes me even more curious that the straightish line at the top-right of the input diagram seems (to my eye) to be slightly less straight than the one at the bottom right, and yet that one remains straight in the output diagram.

My guess: it’s something to do with the attachments to the four-sided box.

Re: FreeTikZ

There may be two explanations. First: this may simply be to do with rounding off. The window you draw in has coordinates roughly between 0 and 500, depending on your browser window and resolution. This is converted to a TikZ picture of about 10cm by 10cm. To make things “more straight”, all coordinates (of dots, morphisms, and end-points of wires) are rounded to the nearest multiple of 5mm. Apparently in the example I drew the bottom-right line just across a 5mm boundary, whereas the top-right line stays within the same vertical grid boundaries.

Second explanation: in addition, the top end of the bottom-right wire is connected to the “south east” end of the morphism box. TikZ has predefined coordinates for this, which might not be exactly the end point of the wire I drew by hand, which is therefore moved a bit left, probably across a rounding boundary.

Finally, the “gentle S-shape” comes about because TikZ is just told the two end-points of that line, and the angles at both ends. It will then fit a nice gentle curve.

Re: FreeTikZ

I tried your online FreeTikz page, and yes it does convert mouse movements to Tikz code. I was a bit disappointed that it didn’t display what that Tikz code would look like. Instead you need to paste that code into a different program.

If these JSOs were exposed (as SVG or as JSON like text) they could be online edited, allowing such things as repositioning, deletion, and label addition that would then affect the generated Tikz code. The JSON or SVG could even be useful for people who don’t want to use Tikz.

Re: FreeTikZ

I had experimented with having a third part, next to the input drawing area and the latex output, namely what the compiled pdf looks like. But in the end I decided against it. There are two options to get the compiled-pdf-look, both of which are not ideal. The first option is to actually run latex. As it’s browser based you need something like texlive.js. But this is extremely slow. What’s worse, it isn’t “real latex” but just an approximation, and doesn’t seem to support packages like TikZ.

The second option is what you mention, to emulate latex/tikz yourself in svg. Drawing the svg itself is relatively easy to do. But in the end it’s again only approximating the real latex. So you still can’t be sure it looks exactly right and becomes another step in the process, and in the end you still have to run latex. As I wrote this mainly as a tool for myself to quickly generate latex code, and I’m happy to then work with the latex code and tweak it, I didn’t think this was worth it.

Nevertheless, you make a good point that this SVG or JSON might be useful for people that don’t care about latex or tikz. Moreover, if there was JSON export, then it could also be fed to other programs such as Quantomatic. I’ll look into it!

Re: FreeTikZ

Chris wrote:

Moreover, if there was JSON export, then it could also be fed to other programs such as Quantomatic. I’ll look into it!

I was thinking about something like that. The great thing about string diagrams is that they aren’t just pretty pictures, they represent morphisms in symmetric monoidal categories. So, one can imagine first presenting a symmetric monoidal category by hand drawing some generators and relations (or more precisely, rewrite rules), and then drawing further string diagrams and having them automatically simplified using the rewrite rules. Or various other things like that. This would be fun.

I don’t have any serious ambitions in this direction, but I can’t resist an advertisement: in Props for network theory, Brandon Coya and I lay down the category-theoretic infrastructure needed to rigorously work with props using generators and relations, and apply this idea to a variety of examples, mainly different sorts of electrical circuits. The ‘behavior’ of networks of a given sort can be described using a morphism of props: for example, there’s a morphism of props sending any electrical circuit to the relation it imposes between potentials and currents at its input and output terminals.

All this generalizes to colored props.

A lot of what we’re doing is carefully spelling out what people do already in a less formal way.

Re: FreeTikZ

Actually, it occurs to me now that Globular is also pretty good at drawing pictures. So if FreeTikZ had an output mode that included only the semantic information, i.e. what is connected to what, then it could be fed into Globular and its pictures could then be exported, even if one didn’t care about using it as a proof assistant. I don’t think Globular has a TikZ output mode, but it could probably be enhanced with one.

Re: FreeTikZ

Ah yes, adding the label m0 is on purpose, so that if you wanted to change it to, say, ff, you can find the right thing to change in the latex code very quickly, rather than having to hunt for the \node[morphism] based on its coordinates. The intended workflow is that you draw a diagram, freetikz-convert it to latex, edit the latex, and then compile it. In editing the latex you can just remove the labels you don’t need, and change the ones you want to change.

Re: FreeTikZ

You’re doing it wrong, only in so far that of course the program is modeled on behaviour I used while testing and writing it! So really the program is wrong, and I’ve just gotten used to how to use it. We’ve co-evolved. Joking aside, I can explain why it does this.

First, the end points of the wires are apparently not close enough to the box to connect to it. They will connect when the end-points are actually inside the polygon spanned by the box, or if they are closer than a given threshold to the centroid of this polygon. So especially if you tend to draw big, it’s better to draw wires to ‘inside’ the dot or box you want to connect them to.

Incidentally, when you draw a wire, you can see the line in the tikz code pop up, and you can see immediately if it connects like you intended. If it doesn’t, you can quickly undo (keyboard shortcut Z) and redraw the wire.

Second, the heuristic that simplifies wires can indeed be improved. For example, in the third wire in your example latex code, there is ‘a mid point too many’. Similarly, the angles on the top-left line are funny, because of the way wires are simplified. The top-left line really consists of about 100 points (depending on how quick you moved the mouse), and most of these are deleted, because you don’t want endless tikz code. But the angle of the line between the first and second point is retained, even if the 2nd to 99th point are deleted. This is probably just where you clicked the mouse button, so the mouse wobbled about a bit. I don’t really know how to make this better. Maybe take some sort of averages first? Does anybody have a good idea?

Re: FreeTikZ

Thanks for the explanation! I’ve tried a number of times more, and although thanks to your hint I can now get the wires to connect to the boxes, the wires always come out squiggly all over the page no matter how carefully I draw them, with my mouse or with my stylus.

You could try doing some averaging of the angles; that might help smooth things out. I feel like the errors are also getting exaggerated a lot; perhaps you could try setting the tikz looseness parameter (or placing the bezier control points manually) depending on how close together the points end up.

Would it be possible, rather than simply deleting a bunch of the points, to try to guess what “sort of curve” the user is intending to draw and then draw that curve using only a handful of points? Most of the time when I draw a string diagram, I want my wires to have only a single bezier segment, or at most two.

Re: FreeTikZ

I presume that your half-right-angled trapezoids for “morphisms” align with the conventions of some particular community, but it’s a convention I’ve never encountered, and I must admit they look very weird to me. Where do they come from?

Re: FreeTikZ

The trapezoids come from the Oxford school of Categorical quantum mechanics that I was indoctrinated in. There, compact dagger categories are used often, and the idea is that the little wedge on the rectangle breaks the symmetry, so you can differentiate between the various transpositions/dagger of the box.
In particular, this is the form used in a forthcoming book I’m finishing with Jamie Vicary.

Re: FreeTikZ

Here’s a little problem I had: my Latex installation doesn’t recognize the document class “standalone”, which meant that when I tried FreeTikZ, the Latex didn’t compile.

Of course, I could (and did) make it work by just changing “standalone” to “article”. And I gather that “standalone” provides cropped pdf output, which was presumably why you chose it. But given that it’s not part of everyone’s Latex installation, maybe it would be useful to provide a link to standalone’s CTAN page, or say a word or two. I don’t know; it’s just a thought.

I also got slightly surprising results from my trial, though not as weird as Mike’s m0 thing. Input:

Re: FreeTikZ

I didn’t realise the standalone package isn’t part of the standard latex distribution, and thought it came with tikz. To be honest, I copied this format of making a \begin{tikzpicture} … \end{tikzpicture} into something compilable from texample.net. I’ll add a link to the CTAN page.

Re: FreeTikZ

Re: FreeTikZ

First let me say, great tool!

Is Ruiting Cao’s thesis available somewhere? I’m curious what were the primary challenges in implementing an SVM for this problem.

I’ve always had this cute idea of training some machine learning model for this kind of thing, but structuring the model to output TikZ code seemed tricky. It’d be fun to train a few layers of a model on a big set of string diagrams taken from existing papers (asking authors or a grad student to perform the much easier task of drawing already typeset diagrams by hand). These layers should be just trying to learn a diagram structure roughly at the level of detail FreeTikZ does.

Then you train another set of layers on all of the diagrams of a certain ‘class’ of diagrams one typically draws, i.e. however I like to draw a bimonoid. This would just assign ‘types’ to each string and node in the output of the other. Implementing this second stage is probably a bit silly compared to doing it by hand.

Re: FreeTikZ

Re: FreeTikZ

Thanks for the links!

There is growing interest in developing category theoretic software tools catering to more applied audiences. Easing the pain of drawing string diagrams is probably an important part of any such tool chain.

Re: FreeTikZ

Since a while I was hoping for someone to develop a program/tool that would draw nice-looking braided diagrams in a pdf format out of diagrams written by hand, for the same reasons Chris lists in his introduction post. So, this is a great news and thanks for the initiative!

It resulted though that a simple diagram that I drew by hand ended up in a pretty different one in the pdf output (unfortunately, I didn’t find the way to paste here my screen shot or upload the file with the drawings, so to illustrate what I mean). It was the anti-algebra morphism rule, I drew circles instead of boxes for morphisms, but two out of three circles ended up in dots, and the third one ended up in a “trapeeze”. The reason for the latter could be, I guess, that where I obtained dots the starting and ending point of my circle don’t meet, while there where I got a trapeeze they do meet. The output drawing should not depend on so sensitive detail in my mouse move. Also the equality sign ended up in a line similar to the Greek letter capital Gamma.

I hope that this project evolves and saves us from so much diagram-typing! :)