summaryrefslogtreecommitdiff
path: root/graphics/jflap2tikz/jflap2tikz.groovy
blob: c049e5f0f48d23cf8e32b62bed084275247baef9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * This groovy script converts a JFLAP jff file representing a finite automaton
 * to LaTeX file depicting the automaton graphically using TikZ.
 *
 * Copyright (c) 2009, 2014, 2015 Andrew Mertz and William Slough
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

// Define a few constants
scale = 1.0                 // 1 pixel in JFLAP = scale points in LaTeX
gridsize = 20.0             // gridsize is measured in pixels
turingBlank = '$\\Box$'     // the symbol to be used for a blank in a TM
blank = '$\\lambda$'        // the symbol to be used for blank otherwise
arrowWidth = 6              // width of an arrow in points
arrowLength = 9             // length of an arrow in points
arrowType = 'Stealth'       // arrow type from arrows.meta TikZ library
acceptingDistance = 2       // distance, in pt, between circles in accepting
                            // state
version = '1.2'
infilename = null
outputStream = null

// Define a function that cleans up text that could be "bad" for LaTeX to
// ingest
String fixText(String text)
{
  if(text)
  {
    text = text.replace('\\', '$\\backslash$')
    text = text.replace('~', '$\\sim$')
    text = text.replaceAll('[$%^&_#{}]', {'\\'+ it[0]})
  }
  return text
}

// Setup the command line options
// TODO: maybe add a switch for arrow type
// TODO: maybe allow different scales and grid sizes for each axis
// TODO: maybe allow user to set preview boarder
cmdLine = new CliBuilder(usage: 'jflap2tikz [options]',
                         header: "Version ${version}",
                         width: 80)

cmdLine.d(longOpt:'accepting-distance',
          args: 1,
          argName: 'distance',
          required: false,
          "Distance, in pt, between the circles of an accepting state (default is ${acceptingDistance})")
cmdLine.i(longOpt: 'input-file',
          args: 1,
          argName: 'filename',
          'Name of a JFLAP jff file representing a finite automaton, pushdown automaton, or Turing machine. If a ' +
          'file is not given standard input will be used.')
cmdLine.g(longOpt:'grid',
          args:1,
          optionalArg: true,
          argName: 'size',
          required: false,
          "Round positions so that they are on a grid. If a size is given it sets the spacing of the grid (default " +
          "is ${gridsize})")
cmdLine.h(longOpt:'help',
          required: false,
          'Show usage information and quit')
cmdLine.l(longOpt:'arrow-length',
          args:1,
          argName: 'length',
          required: false,
          "Length of arrows in points (default is ${arrowLength})")
cmdLine.o(longOpt: 'output-file',
          args: 1,
          argName: 'filename',
          'Name of a file for writing output. If this file already exists it will be overwritten.')
cmdLine.r(longOpt:'rotate',
          required: false,
          'Rotate labels along edges')
cmdLine.s(longOpt:'scale',
          args:1,
          argName:'x',
          required: false,
          "1 pixel in JFLAP = x points in LaTeX (default is ${scale})")
cmdLine.w(longOpt:'arrow-width',
          args:1,
          argName:'width',
          required: false,
          "Width of arrows in points (default is ${arrowWidth})")
cmdLine.k(longOpt:'keep-names',
          required: false,
          "Use the state names from the JFLAP file. The default is to replace the state names with names of the " +
          "form '\$q_{id}\$', where id is the unique state number. Note state names will not be sanitized and thus " +
          "may contain invalid TeX.")

// Parse the command line options
options = cmdLine.parse(args)

// If there is a parse error, quit. Note usage information will already have
// been displayed.
if(!options)
{
  System.exit(1)
}

// If the user has asked for help print the usage information and quit
if(options.h)
{
  cmdLine.usage()
  System.exit(0)
}

keapNames = options.k

grid = false
if(options.g)
{
  grid = true

  // Verify that gridsize is valid (a positive double)
  if(!(options.g instanceof Boolean))
  {
    try
    {
      gridsize = Double.valueOf(options.g)
      if (gridsize <= 0) throw new NumberFormatException()
    }
    catch(NumberFormatException ex)
    {
      System.err.println "error: gridsize must be a positive number"
      cmdLine.usage()
      System.exit(2)
    }
  }
}

// Verify that the scale is valid (a positive double)
try
{
  if(options.s)
  {
    scale = Double.valueOf(options.s)
    if (scale <= 0)
    {
      throw new NumberFormatException()
    }
  }
}
catch(NumberFormatException ex)
{
  System.err.println "error: scale must be a positive number"
  cmdLine.usage()
  System.exit(3)
}

// Verify that the accepting distance is valid (a positive double)
try
{
  if(options.d)
  {
    acceptingDistance = Double.valueOf(options.d)
    if (acceptingDistance <= 0)
    {
      throw new NumberFormatException()
    }
  }
}
catch(NumberFormatException ex)
{
  System.err.println "error: accepting distance must be a positive number"
  cmdLine.usage()
  System.exit(4)
}

if(options.i)
{
  infilename = options.i
}

if(options.o)
{
  try
  {
    outputStream = new FileWriter(options.o)
  }
  catch(Exception e)
  {
    System.err.println "error: unable to write to output file ${options.o}"
    System.exit(5)
  }
}
else
{
  outputStream = System.out
}

// Try to get the text from the file
if(infilename)
{
  try
  {
    body = new File(infilename).text
  }
  catch(IOException ex)
  {
    System.err.println "error: unable to read ${infilename}"
    System.exit(4)
  }
}
else
{
  body = System.in.text
}

// Parse the XML
try
{
  structure = new XmlParser().parseText(body)
}
catch(Exception ex)
{
  System.err.println "error: parsing XML"
  System.exit(5)
}

// Check the type to be sure it is a machine that can be converted
type = structure.type.text()
if(type != "fa" && type != "pda" && type != "turing")
{
  System.err.println "error: unsupported machine type --- only FAs, PDAs and Turing machines can be converted"
  System.exit(6);
}

// If the automaton is a Turing machine, get the number of tapes
try
{
  tapes = Integer.valueOf(structure.tapes.text())
}
catch (Exception ex)
{
  tapes = 1
}

// Find the automaton in the XML tree
automaton = structure.automaton
if(!automaton)
{
  automaton = structure
}

// Print the LaTeX header
outputStream.println """\\documentclass{article}
\\usepackage{tikz}
\\usetikzlibrary{automata,positioning,arrows.meta}${type == "turing" ? "\n\\usepackage{amssymb}\n" : ""}
\\usepackage[graphics,tightpage,active,pdftex]{preview}
\\setlength{\\PreviewBorder}{5pt}
\\PreviewEnvironment{tikzpicture}
\\begin{document}
\\begin{tikzpicture}[>={Stealth[width=${arrowWidth}pt,length=${arrowLength}pt]}, accepting/.style={double distance = ${acceptingDistance}pt, outer sep = ${acceptingDistance/2.0}pt + \\pgflinewidth}, shorten >=1pt${options.r ? "" : ", auto"}]"""

// For each state in the XML define a TikZ node and record their position
statePosition = [:]
automaton.state.each
{
  // Get the x and y value of the position, correcting for the change in
  // coordinate systems
  x = Double.valueOf(it.x.text()) * scale
  y = -Double.valueOf(it.y.text()) * scale
  if(grid)
  {
    x = Math.round(x / gridsize) * gridsize
    y = Math.round(y / gridsize) * gridsize
  }

  // record position
  statePosition[it.@id] = [x,y]

  // get state name
  def stateName
  if(keapNames)
  {
    stateName = it.@name
  }
  else
  {
    stateName = "\$q_{${fixText(it.@id)}}\$"
  }

  // Output the TikZ version of this state
  outputStream.println "  \\draw (${x}pt, ${y}pt)" +
    "node[state${it.initial ? ", initial, initial text =" : ""}" +
    "${it.get("final") ? ", accepting" : ""}]" +
    "(${fixText(it.@id)}){$stateName};"
}

// Define a function that makes a key based on the end points of a transition
// without taking into account the order of the keys. In other words, edge
// (a,b) results in the same key as the edge (b,a).
String makeKey(String a, String b)
{
  return a < b ? "${a},${b}" : "${b},${a}"
}

// Scan transitions and create their labels. Also, check to see if there are
// edges going in both directions.
doubleEdges = [:]
edgeLabels = [:]
automaton.transition.each
{
  orderedKey = [it.from.text(), it.to.text()]

  // Have we seen the reverse of this edge before?
  if(edgeLabels.get([it.to.text(), it.from.text()]) &&
    it.to.text() != it.from.text())
  {
    doubleEdges.put(makeKey(it.from.text(), it.to.text()), true)
  }

  // Get the read symbol. If it is blank use lambda for the symbol.
  if(!(readSymbol = fixText(it.read.text())))
  {
    readSymbol = blank
  }

  // Get the pop and push symbols if the machine is a PDA
  if(type == "pda")
  {
    if(!(popSymbol = fixText(it.pop.text())))
    {
      popSymbol = blank
    }
    if(!(pushSymbol = fixText(it.push.text())))
    {
      pushSymbol = blank
    }
  }

  // If the machine is a Turing machine, get all of the read, write, and move
  // information
  if(type == "turing")
  {
    readSymbols = []
    it.read.each{r->
      readSymbols << (r.text() ? fixText(r.text()) : turingBlank)
    }

    writeSymbols = []
    it.write.each{w->
      writeSymbols << (w.text() ? fixText(w.text()) : turingBlank)
    }

    moves = []
    it.move.each{m->
      moves << fixText(m.text())
    }
  }

  // Make the label for this transition
  if(type == "fa")
  {
    label = readSymbol;
  }
  else if(type == "pda")
  {
    label = "${readSymbol}, ${popSymbol}; ${pushSymbol}"
  }
  else if(type == "turing")
  {
    // Merge the read, write and move lists into one label
    label = []
    readSymbols.eachWithIndex{read, i->
      label << "${read} : ${writeSymbols[i]}, ${moves[i]}"
    }
    label = label.join('$|$')
  }

  // Add this edge's label to the edge label list
  if((oldLabel = edgeLabels.get(orderedKey)))
  {
    oldLabel << label
  }
  else
  {
    edgeLabels.put(orderedKey, [label])
  }
}

// For each transition draw an edge
edgeLabels.each
{
  // Turn the label into a string
  if(type == "fa")
  {
    label = it.value.join(", ")
  }
  else
  {
    label = it.value.join("\\\\ ")
  }

  // Construct the options for the node that will hold the label
  nodeOptions = []
  if(type != "fa" && it.value.size() > 1) // Are line breaks needed?
  {
    nodeOptions << "align=center"
  }
  if(options.r && it.key[0] != it.key[1]) // Does the text need to be rotated?
  {
    nodeOptions << "sloped"

    // In the case of rotations auto positioning is not used. Thus, an anchor
    // point for the node must be given.
    if(statePosition[it.key[0]][0] < statePosition[it.key[1]][0])
    {
      nodeOptions << "anchor=south"
    }
    else
    {
      nodeOptions << "anchor=north"
    }
  }

  // Turn the node options into a string. If there are no options then use the
  // empty string. Otherwise join the option with commas and surround them with
  // square brackets.
  if(nodeOptions.size() > 0)
  {
    nodeOptions = "[${nodeOptions.join(",")}]"
  }
  else
  {
    nodeOptions = ""
  }

  outputStream.println "  \\path[->] (${it.key[0]}) edge" +
  (it.key[0] == it.key[1] ? "[loop above]" : "") +   // Do we have a self loop?
  (doubleEdges.get(makeKey(it.key[0], it.key[1])) ? "[bend left]" : "") + // Do we have more than one edge? If so add a bend.
    " node${nodeOptions}" +
    "{${label}}(${it.key[1]});"
}

// Print the LaTeX footer
outputStream.println """\\end{tikzpicture}
\\end{document}"""
outputStream.close()