Scripting Golly

Installing Python
Example scripts
Golly's scripting commands
Cell lists and rectangle lists
Using the glife package
Potential problems
Universal Python on Mac OS X
Python copyright notice

 
Installing Python

Python scripts can be executed by Golly. This is a very powerful feature that allows you to automate Golly's user interface, extend its editing capabilities, construct complicated patterns, perform collision experiments, etc.

Before you can run a script, Python needs to be installed on your system. Mac OS X users don't need to do anything because Python is already installed (but see below for how to force Golly to use a newer version of Python). Windows and Linux users can download a Python installer from www.python.org/download.

On Windows and Linux, the Python library is loaded at runtime (the first time you try to run a script). Golly initially attempts to load a particular version of the Python library: python24.dll on Windows or libpython2.4.so on Linux. The numbers correspond to Python version 2.4. If that library can't be found then you'll be prompted to enter a different library name matching the version of Python installed on your system. A successfully loaded library is remembered (in your GollyPrefs file) so you won't get the prompt again unless you remove Python or install a new version. If Python isn't installed then you'll have to hit Cancel and you won't be able to run any scripts.

 
Example scripts

The Scripts folder supplied with Golly contains a number of example Python scripts:

density.py -- calculates the density of the current pattern
goto.py -- goes to a given generation
gun-demo.py -- constructs a few spaceship guns
invert.py -- inverts all cell states in the current selection
metafier.py -- converts the current selection into a meta pattern
oscar.py -- detects oscillating patterns, including spaceships
pd-glider.py -- creates a set of pentadecathlon+glider collisions
shift.py -- shifts the current selection by given x y amounts
slide-show.py -- displays all patterns in the Patterns folder
tile.py -- tiles the current selection with the pattern inside it
tile-with-clip.py -- tiles the current selection with the clipboard pattern

The easiest way to run one of these scripts is to tick the Show Scripts item in the File menu and then simply click on the script you wish to run. You can also select one of the Run items in the File menu.

To abort a running script, hit the escape key or click on the stop button in the tool bar or select the Stop item in the Control menu.

 
Golly's scripting commands

This section describes all the commands that can be used in a script after importing the golly module. Commands are grouped by function (filing, editing, control, viewing and miscellaneous) or you can search for individual commands alphabetically:

advance
appdir
autoupdate
clear
copy
cut
dokey
empty
error
evolve
fit
fitsel
flip
getbase
getcell
getcells
getclip
getcolor
getcursor
getgen
getkey
getmag
getoption
getpop
getpos
getrect
getrule
getselrect
getstep
load
new
open
parse
paste
putcells
randfill
reset
rotate
run
save
select
setbase
setcell
setcolor
setcursor
setmag
setoption
setpos
setrule
setstep
show
shrink
step
store
transform
update
visrect
warn

 
FILING COMMANDS

open(filename, remember=False)
Open the given pattern file. A non-absolute path is relative to the location of the script. The 2nd parameter is optional (default = False) and specifies if the file should be remembered in the Open Recent submenu.
Example: golly.open("my-patterns/foo.rle")

save(filename, format, remember=False)
Save the current pattern in a given file using the specified format ("rle" or "mc"). A non-absolute path is relative to the location of the script. The 3rd parameter is optional (default = False) and specifies if the file should be remembered in the Open Recent submenu. If the savexrle option is True then extended RLE format is used (see the Save Extended RLE item for details).
Example: golly.save("foo.rle", "rle", True)

load(filename)
Read the given pattern file and return a cell list.
Example: blinker = golly.load("blinker.rle")

store(cell-list, filename)
Write the given cell list to the specified file in RLE format. If the savexrle option is True then extended RLE format is used (see the Save Extended RLE item for details).
Example: golly.store(clist, "foo.rle")

appdir()
Return the location of the Golly application as a string.
Example: golly.open(appdir() + "Patterns/Breeders/breeder.lif")

 
EDITING COMMANDS

new(title)
Create a new, empty universe and set the window title. If the given title is empty then the current title won't change.
Example: golly.new("test-pattern")

cut()
Cut the current selection to the clipboard.

copy()
Copy the current selection to the clipboard.

clear(where)
Clear inside (where = 0) or outside (where = 1) the current selection.
Example: golly.clear(1)

paste(x, y, mode)
Paste the clipboard pattern at x,y using the given mode ("copy", "or" or "xor").
Example: golly.paste(0, 0, "or")

shrink()
Shrink the current selection to the smallest rectangle enclosing all of the selection's live cells.

randfill(percentage)
Randomly fill the current selection to a density specified by the given percentage (1 to 100).
Example: golly.randfill(50)

flip(direction)
Flip the current selection left-right (direction = 0) or up-down (direction = 1).

rotate(direction)
Rotate the current selection 90 degrees clockwise (direction = 0) or anticlockwise (direction = 1).

evolve(cell-list, numgens)
Advance the pattern in the given cell list by the specified number of generations and return the resulting cell list.
Example: newpatt = golly.evolve(currpatt, 100)

transform(cell-list, x0, y0, axx, axy, ayx, ayy)
Apply an affine transformation to the given cell list and return the resulting cell list. For each x,y cell in the input list the corresponding xn,yn cell in the output list is calculated as xn = x0 + x*axx + y*axy, yn = y0 + x*ayx + y*ayy.
Example: rot_blinker = golly.transform(blinker, 0, 0, 0, -1, 1, 0)

parse(string, x0, y0, axx, axy, ayx, ayy)
Parse an RLE or Life 1.05 string and return a (possibly transformed) cell list.
Example: blinker = golly.parse("3o!", 0, 0, 1, 0, 0, 1)

putcells(cell-list, x0, y0, axx, axy, ayx, ayy)
Paste the given cell list into the current universe using the given transformation.
Example: golly.putcells(blinker, 9, 9, 1, 0, 0, 1)

getcells(rect-list)
Return any live cells in the specified rectangle as a cell list. The given list can be empty (in which case the cell list is empty) or it must represent a valid rectangle of the form [x,y,width,height].
Example: clist = golly.getcells( getrect() )

getclip()
Parse the pattern data in the clipboard and return a cell list.
Example: clist = golly.getclip()

select(rect-list)
Create a selection if the given list represents a valid rectangle of the form [x,y,width,height] or remove the current selection if the given list is [].
Example: golly.select( [-10,-10,20,20] )

getrect()
Return the current pattern's bounding box as a list. If there is no pattern then the list is empty ([]), otherwise the list is of the form [x,y,width,height].
Example: if len(golly.getrect()) == 0: golly.show("No pattern.")

getselrect()
Return the current selection rectangle as a list. If there is no selection then the list is empty ([]), otherwise the list is of the form [x,y,width,height].
Example: if len(golly.getselrect()) == 0: golly.show("No selection.")

setcell(x, y, state)
Set the given cell to the specified state (0 for a dead cell, 1 for a live cell).

getcell(x, y)
Return the state of the given cell. The following example inverts the state of the cell at 0,0.
Example: golly.setcell(0, 0, 1 - golly.getcell(0, 0))

setcursor(index)
Set the cursor according to the given index and return the old cursor index. The valid index values are 0 for the pencil cursor, 1 for the cross cursor, 2 for the hand cursor, 3 for the zoom-in cursor and 4 for the zoom-out cursor.
Example: oldcurs = golly.setcursor(3)

getcursor()
Return the current cursor index.

 
CONTROL COMMANDS

run(numgens)
Run the current pattern for the specified number of generations. Intermediate generations are never displayed, and the final generation is only displayed if the current autoupdate setting is True.
Example: golly.run(100)

step()
Run the current pattern for the current step. Intermediate generations are never displayed, and the final generation is only displayed if the current autoupdate setting is True.

setstep(exp)
Set the step to base^exp (use the setbase command to change the base). A negative exponent sets the step to 1; it also sets a delay between each step, but that delay is ignored by the run and step commands.
Example: golly.setstep(0)

getstep()
Return the current step exponent.
Example: golly.setstep( golly.getstep() + 1 )

setbase(base)
Set the base step for the current universe type (hashing or non-hashing), so you might need to call setoption("hashing",True/False) first. The given base must be an integer from 2 to 100. The current step is also changed to base^exp where exp is the current step exponent returned by getstep().
Example: golly.setbase(2)

getbase()
Return the current base step for the current universe type (hashing or non-hashing).

advance(where, numgens)
Advance inside (where = 0) or outside (where = 1) the current selection by the specified number of generations. The generation count does not change.
Example: golly.advance(0, 3)

reset()
Restore the starting pattern and generation count. Also reset the rule, scale, location, step exponent and hashing option to the values they had at the starting generation. The starting generation is usually zero, but it can be larger after loading an RLE/macrocell file that stores a non-zero generation count.

getgen(sepchar='\0')
Return the current generation count as a string. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting string more readable. For example, golly.getgen(',') would return a string like "1,234,567" but golly.getgen() would return "1234567". Use the latter call if you want to do arithmetic on the generation count because then it's easy to use int to convert the string to an integer. Note that Python supports arbitrarily large integers.
Example: gen = int( golly.getgen() )

getpop(sepchar='\0')
Return the current population as a string. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting string more readable. For example, golly.getpop(',') would return a string like "1,234,567" but golly.getpop() would return "1234567". Use the latter call if you want to do arithmetic on the population count. The following example converts the population to a floating point number.
Example: pop = float( golly.getpop() )

empty()
Return True if the universe is empty or False if there is at least one live cell. This is much more efficient than testing getpop() == "0".
Example: if golly.empty(): golly.show("All cells are dead.")

setrule(string)
Set the current rule according to the given string. If the string is invalid then you'll get an error message and the script will be aborted (and the original rule will be restored).
Example: golly.setrule("b3/s23")

getrule()
Return the current rule as a string.

 
VIEWING COMMANDS

setpos(x, y)
Change the position of the viewport so the given cell is in the middle. The x,y coordinates are given as strings so the viewport can be moved to any location in the unbounded universe. Commas and other punctuation marks can be used to make large numbers more readable. Apart from a leading minus sign, most non-digits are simply ignored; only alphabetic characters will cause an error message. Note that positive y values increase downwards in Golly's coordinate system.
Example: golly.setpos("1,000,000,000,000", "-123456")

getpos(sepchar='\0')
Return the x,y position of the viewport's middle cell in the form of a Python tuple containing two strings. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting strings more readable. For example, golly.getpos(',') might return two strings like "1,234" and "-5,678" but golly.getpos() would return "1234" and "-5678". Use the latter call if you want to do arithmetic on the x,y values, or just use the getposint() function defined in the glife package.
Example: x, y = golly.getpos()

setmag(mag)
Set the magnification, where 0 corresponds to the scale 1:1, 1 = 1:2, -1 = 2:1, etc. The maximum allowed magnification is 4 (= 1:16).
Example: golly.setmag(0)

getmag()
Return the current magnification.
Example: golly.setmag( golly.getmag() - 1 )

fit()
Fit the entire pattern in the viewport.

fitsel()
Fit the current selection in the viewport.

visrect(rect-list)
Return True if the given rectangle is completely visible in the viewport. The rectangle must be a list of the form [x,y,width,height].
Example: if golly.visrect( [0,0,44,55] ): . . .

autoupdate(bool)
When Golly runs a script this setting is initially False. If the given parameter is True then Golly will automatically update the viewport and the status bar after each command that changes the universe or viewport in some way. Useful for debugging Python scripts.
Example: golly.autoupdate(True)

update()
Immediately update the viewport and the status bar, regardless of the current autoupdate setting. Note that Golly always does an update when a script finishes.

 
MISCELLANEOUS COMMANDS

setoption(name, value)
Set the given option to the given value. The old value is returned to make it easy to restore a setting. Here are all the valid option names and their possible values:

"autofit" 1 or 0 (True or False)
"boldspacing" 2 to 1000
"fullscreen" 1 or 0 (True or False)
"hashing" 1 or 0 (True or False)
"hyperspeed" 1 or 0 (True or False)
"maxdelay" 0 to 5000 (millisecs)
"mindelay" 0 to 5000 (millisecs)
"savexrle" 1 or 0 (True or False)
"showboldlines" 1 or 0 (True or False)
"showexact" 1 or 0 (True or False)
"showgrid" 1 or 0 (True or False)
"showpatterns" 1 or 0 (True or False)
"showscripts" 1 or 0 (True or False)
"showstatusbar" 1 or 0 (True or False)
"showtoolbar" 1 or 0 (True or False)
"swapcolors" 1 or 0 (True or False)

Example: oldhash = golly.setoption("hashing", True)

getoption(name)
Return the current value of the given option. See above for a list of all the valid option names.
Example: if not golly.getoption("hashing"): golly.setrule("b0")

setcolor(name, r, g, b)
Set the given color to the given RGB values (integers from 0 to 255). The old RGB values are returned as a 3-tuple to make it easy to restore the color. Here is a list of all the valid color names and how they are used:

"livecells" for displaying live cells
"deadcells" for displaying dead cells
"paste" for pasting patterns
"select" for selections (will be 50% transparent)
"hashing" for status bar background if hashing
"nothashing" for status bar background if not hashing

Example: oldrgb = golly.setcolor("livecells", 0, 0, 255)

getcolor(name)
Return the current RGB values for the given color as a 3-tuple. See above for a list of all the valid color names.
Example: r, g, b = golly.getcolor("deadcells")

getkey()
Return a key hit by the user as a single character, or an empty string if no key was hit. The characters returned by this command are a subset of ASCII:

' ' to '~' all displayable characters (space to tilde)
chr(8) backspace or delete
chr(9) tab
chr(13) return (or enter on Windows)
chr(28) to chr(31) left, right, up, down arrows

Example: ch = golly.getkey()

Note that the glife package defines a helper function called getstring which displays a prompt in the status bar and uses getkey to read user input. See also the goto.py script.

dokey(char)
This command allows limited keyboard interaction while a script is running. The given character is passed to Golly's keyboard event handler, but all keyboard shortcuts that can change the current pattern will be ignored.
Example: golly.dokey( golly.getkey() )

show(message)
Show the given string in the bottom line of the status bar. The status bar is automatically shown if necessary.
Example: golly.show("Hit any key to continue...")

error(message)
Beep and show the given string in the bottom line of the status bar. The status bar is automatically shown if necessary.
Example: golly.error("The pattern is empty.")

warn(message)
Show the given string in Golly's warning dialog. Useful for debugging Python scripts.
Example: golly.warn("xxx = " + str(xxx))

 
Cell lists and rectangle lists

Some of Golly's scripting commands manipulate patterns in the form of cell lists. A cell list is simply a Python list containing integer cell coordinates:

[ x1, y1, x2, y2 . . . xn, yn ]

A cell list should always contain an even number of integers. The ordering of cells within the list doesn't matter. Note that positive y values increase downwards in Golly's coordinate system.

Some commands manipulate rectangles in the form of lists. An empty rectangle is indicated by a list with no items; ie. []. A non-empty rectangle is indicated by a list containing four integers:

[ left, top, width, height ]

The first two items specify the cell at the top left corner of the rectangle. The last two items specify the rectangle's size (in cells). The width and height must be greater than zero.

 
Using the glife package

The glife folder included in the Scripts folder is a Python package that provides a high-level interface to some of Golly's scripting commands (it's based on Eugene Langvagen's life package included in PLife). When a script imports glife or any of its submodules, Python automatically executes the __init__.py module. This module defines the pattern and rect classes as well as a number of useful synonyms and helper functions. For example, consider this script:

from glife import *
blinker = pattern("3o!")
blinker.put(1, 2)
blinker.put(6, 7, rcw)   # rcw means rotate clockwise

Here is the equivalent script without using glife:

import golly as g
blinker = g.parse("3o!", 0, 0, 1, 0, 0, 1)
g.putcells(blinker, 1, 2, 1, 0, 0, 1)
g.putcells(blinker, 6, 7, 0, -1, 1, 0)

Here are some helper functions defined in glife:

getstring(prompt) -- prompt user and return entered string
validint(s) -- return True if given string is a valid integer
getposint() -- return viewport position as a tuple with 2 integers
setposint(x,y) -- use given integers to set viewport position
getminbox(patt) -- return minimal bounding box of given pattern

Most of the examples in the Scripts folder import glife, but it isn't compulsory. You might prefer to create your own high-level interface for the scripts you write.

 
Potential problems

1. The Python interpreter's memory allocator never releases memory back to the operating system. If you run a complicated or buggy script that uses lots of (Python) memory then that memory is no longer available for use by Golly, so you might need to quit Golly and restart. This problem is hopefully only temporary. The next major release of Python has a smarter memory allocator (available now if you're willing to build Python from the latest source code).

2. The first time you run a script that imports a particular module, the Python interpreter caches the results so it won't need to reload that module the next time it is imported. This is good for efficiency, but it's a problem if you've modified an imported module and you want to test your changes. One solution is to quit Golly and restart. A better solution is to force the module to be reloaded by inserting a line like

import mymodule ; reload(mymodule)

at the start of each script that imports the module. When the module is stable you can remove or comment out the above line.

3. The escape key check to abort a running script is not done by Python but by each Golly scripting command. This means that very long Python computations should call an occasional "no-op" command like run(0) to allow the script to be aborted in a timely manner.

 
Universal Python on Mac OS X

Even though Apple supply Python with OS X, it is usually not the latest version. If you have an Intel Mac then it's a good idea to download and install Universal Python 2.4 from pythonmac.org. This will install Python 2.4 in /Library/Frameworks. However, Golly is linked against the Python 2.3 framework stored in /System/Library/Frameworks and won't use the newer Python. Fortunately there is a simple solution that forces Golly to load the Python 2.4 framework. Quit Golly, open Terminal and enter this command (on one line):

install_name_tool -change \
/System/Library/Frameworks/Python.framework/Versions/2.3/Python \
/Library/Frameworks/Python.framework/Versions/2.4/Python \
/path/to/Golly/folder/Golly.app/Contents/MacOS/Golly

If you ever need to switch back to the system-supplied Python then just run the command again with the framework paths swapped. To verify which version of Python Golly is using, copy the following code, start up Golly and select Run Clipboard from the File menu:

import golly
import sys
golly.warn(sys.version)

On an Intel Mac your scripts will run significantly faster when using Universal Python.

 
Python copyright notice

Golly uses an embedded Python interpreter to execute scripts. Here is the official Python copyright notice:

Copyright (c) 2001-2005 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.

The Python license agreement is included in Golly's LICENSE file.