def slideshow():
    oldalgo = g.getalgo()
    oldrule = g.getrule()

    message = "Hit space to continue or escape to exit the slide show..."
    g.show(message)
    for root, dirs, files in os.walk(g.getdir("app") + "Patterns"):
        for name in files:
            if name.startswith("."):
                # ignore hidden files (like .DS_Store on Mac)
                pass
            else:
                g.new("")
                g.setalgo("QuickLife")  # nicer to start from this algo
                fullname = join(root, name)
                g.open(fullname,
                       False)  # don't add file to Open/Run Recent submenu
                g.update()
                if name.endswith(".lua") or name.endswith(".py"):
                    # reshow message in case it was changed by script
                    g.show(message)

                while True:
                    event = g.getevent()
                    if event == "key space none": break
                    g.doevent(event)  # allow keyboard/mouse interaction
                    sleep(0.01)  # avoid hogging cpu

    # if all patterns have been displayed then restore original algo and rule
    # (don't do this if user hits escape in case they want to explore pattern)
    g.new("untitled")
    g.setalgo(oldalgo)
    g.setrule(oldrule)
Пример #2
0
def main():

    g.setstep(0)
    g.setalgo('QuickLife')

    velocity = g.getstring('Please specify velocity', '(2,1)c/6')
    a, b, p = parse_velocity(velocity)
    params = partial_derivatives(a, b, p)

    dvdx = params['dvdx']
    dudx = params['dudx']
    dvdy = params['dvdy']
    dudy = params['dudy']
    dvdt = params['dvdt']
    dudt = params['dudt']

    cells = []

    for t in xrange(p):

        things = g.getcells(g.getrect())
        things = zip(things[::2], things[1::2])
        cells += [(dudx * x + dudy * y + dudt * t,
                   dvdx * x + dvdy * y + dvdt * t) for (x, y) in things]
        g.step()

    g.setlayer(g.addlayer())
    g.putcells([x for y in cells for x in y])
Пример #3
0
def slideshow ():
   oldalgo = g.getalgo()
   oldrule = g.getrule()
   
   message = "Hit space to continue or escape to exit the slide show..."
   g.show(message)
   for root, dirs, files in os.walk(g.getdir("app") + "Patterns"):
      for name in files:
         if name.startswith("."):
            # ignore hidden files (like .DS_Store on Mac)
            pass
         else:
            fullname = join(root, name)
            g.open(fullname, False)       # don't add file to Open/Run Recent submenu
            g.update()
            if name.endswith(".pl") or name.endswith(".py"):
               # reshow message in case it was changed by script
               g.show(message)
            
            while True:
               event = g.getevent()
               if event == "key space none": break
               g.doevent(event)           # allow keyboard/mouse interaction
               sleep(0.01)                # avoid hogging cpu
      
      if "CVS" in dirs:
         dirs.remove("CVS")  # don't visit CVS directories
   
   # if all patterns have been displayed then restore original algo and rule
   # (don't do this if user hits escape in case they want to explore pattern)
   g.new("untitled")
   g.setalgo(oldalgo)
   g.setrule(oldrule)
Пример #4
0
def main():
    #Vertical distance between pixels. Maybe get this from user. minimum = 16
    pdy = 16

    #Generate & display a dot matrix printer from current selection
    dmprinter(pdy, copies=1)

    golly.setcursor("Zoom In")
    golly.setalgo("HashLife")
    golly.setbase(2)
    golly.setstep(6)
Пример #5
0
 def writeRuleTree(self,name):
     # create a .tree file in user's rules directory
     f=open(golly.getdir("rules")+name+".tree", 'w')
     f.write("# Automatically generated by make-ruletree.py.\n")
     f.write("num_states=" + str(self.numStates)+"\n")
     f.write("num_neighbors=" + str(self.numNeighbors)+"\n")
     f.write("num_nodes=" + str(len(self.r))+"\n")
     for rule in self.r:
         f.write(rule+"\n")
     f.flush()                   # ensure file is complete (only on Windows?)
     f.close()
     golly.setalgo("RuleTree")   # in case name.table exists
     golly.setrule(name)
     golly.show("Created "+name+".tree in "+golly.getdir("rules"))
Пример #6
0
def render(length, x, y, generation):
    g.setgen("0")
    g.setalgo("Generations")
    g.setrule(generate_rule(x, y, generation))

    pop, extinction = get_pop(length, x, y)
    if extinction < 4410:
        g.show("Rule {} extinct at generation {}.".format(
            g.getrule(), extinction))
        with open("snd/short_lived_rules", "a") as short_lived:
            short_lived.write(g.getrule() + "\n")
        return
    with open("snd/long_lived_rules", "a") as long_lived:
        long_lived.write(g.getrule() + "\n")

    filename = create_name("snd")
    write_wave(filename, pop)

    g.show("Wave saved to " + filename)
Пример #7
0
def FinadOptimalRecipe(slv, idx):
	moveTable = slv.SLsMoveTable[idx]
	bests = [-1, -1]
	slCount = [1000, 1000]
	
	g.setrule("B3/S23")
	g.setalgo("HashLife")
	
	for i in xrange(0, len(moveTable)):
		g.new("")
		
		slv.ApplyRecipeSmart(i, idx)
		slv.PlaceRecipe()
		
		g.setstep(5)
		g.step()
		
		numSL = len(CountSL())
		laneID = (moveTable[i][1] + 10000) % 2
		
		if slCount[laneID] > numSL:
			slCount[laneID] = numSL
			bests[laneID] = i
		
		slv.Reset()
		
	g.setrule("LifeHistory")
	
	for i in xrange(0, len(bests)):
		slv.ApplyRecipeSmart(bests[i], idx)
		slv.PlaceRecipe(i * 100, 0, i == 0)
		slv.Reset()
	
	g.show(str(bests))
	#11 - [32, 249]
	#12 - [138, 123]
	#13 - [29, 27]
	#14 - [89, 15]
	return bests
Пример #8
0
def main():

    g.setstep(0)
    g.setalgo('QuickLife')

    velocity = g.getstring('Please specify velocity', '(2,1)c/6')
    a, b, p = parse_velocity(velocity)
    params = partial_derivatives(a, b, p)

    dvdy = params['dvdy']
    dudy = params['dudy']
    dvdt = params['dvdt']

    cells = g.getcells(g.getrect())
    cells = zip(cells[::2], cells[1::2])
    gcells = []

    for (u, v) in cells:
        for t in xrange(p):
            xp = dvdy * u - dudy * v - a * t
            yq = v - t * dvdt
            if (xp % p != 0):
                continue
            if (yq % dvdy != 0):
                continue
            x = xp // p
            y = yq // dvdy
            gcells.append((t, x, y))

    spacing = max([x for (_, x, _) in gcells]) - min([x for (_, x, _) in gcells])
    spacing += 10

    gcells = [(x + spacing * t, y) for (t, x, y) in gcells]

    g.setlayer(g.addlayer())
    g.putcells([x for y in gcells for x in y])
    g.fit()
Пример #9
0
                        # lower triangle
                        pixels[row][(encode(color,state,dir)-1)*15+column] = \
                            [palette[0],bg_color,fg_color][lower[dir][row][column]]
                        # upper triangle
                        pixels[row][(encode(color,state,dir)+total_states-2)*15+column] = \
                            [palette[0],bg_color,fg_color][lower[2-dir][13-row][column]]
                # draw the 7x7 icon
                for row in range(7):
                    for column in range(7):
                        # lower triangle
                        pixels[15+row][(encode(color,state,dir)-1)*15+column] = \
                            [palette[0],bg_color,fg_color][lower7x7[dir][row][column]]
                        # upper triangle
                        pixels[15+row][(encode(color,state,dir)+total_states-2)*15+column] = \
                            [palette[0],bg_color,fg_color][lower7x7[2-dir][6-row][column]]

    ConvertTreeToRule(rule_name, total_states, pixels)

else:

    golly.warn('Too many states!')
    golly.exit()

# -- select the rule --

golly.new(rule_name+'-demo.rle')
golly.setalgo('RuleLoader')
golly.setrule(rule_name)
golly.setcell(0,0,encode(0,0,0)) # start with a single turmite
golly.show('Created '+rule_name+'.rule and selected that rule.')
Пример #10
0
    return ( s[0] + s[1] + s[2] ) % 5
'''

import golly
from glife.RuleTree import *

# exec() only works if all lines end with LF, so we need to convert
# any Win line endings (CR+LF) or Mac line endings (CR) to LF
CR = chr(13)
LF = chr(10)
try:
   
   exec(golly.getclipstr().replace(CR+LF,LF).replace(CR,LF))
   MakeRuleTreeFromTransitionFunction( n_states, n_neighbors, transition_function, 
                                       golly.getdir("rules")+name+".tree" )
   golly.setalgo("RuleTree")   # in case name.table exists
   golly.setrule(name)
   golly.show("Created "+name+".tree in "+golly.getdir("rules"))
   
except:
   import sys
   import traceback
   exception, msg, tb = sys.exc_info()
   golly.warn(\
'''To use this script, copy a Python format rule definition into the clipboard, e.g.:

name = "ParityNWE"
n_states = 5
n_neighbors = 4
# order for 4 neighbors is N, W, E, S, C
def transition_function ( s ) : 
Пример #11
0
def score_pair(g, seed1, seed2, width_factor, height_factor, \
  time_factor, num_trials):
    """
  Put seed1 and seed2 into the Immigration Game g and see which 
  one wins and which one loses. Note that this function does
  not update the histories of the seeds. For updating histories,
  use update_history().
  """
    #
    # Make copies of the original two seeds, so that the following
    # manipulations do not change the originals.
    #
    s1 = copy.deepcopy(seed1)
    s2 = copy.deepcopy(seed2)
    #
    # Check the number of living cells in the seeds. If the number
    # is zero, it is probably a mistake. The number is initially
    # set to zero and it should be updated when the seed is filled
    # with living cells. We could use s1.count_ones() here, but
    # we're trying to be efficient by counting only once and
    # storing the count.
    #
    assert s1.num_living > 0
    assert s2.num_living > 0
    #
    # Initialize scores
    #
    score1 = 0.0
    score2 = 0.0
    #
    # Run several trials with different rotations and locations.
    #
    for trial in range(num_trials):
        #
        # Randomly rotate and flip s1 and s2
        #
        s1 = s1.random_rotate()
        s2 = s2.random_rotate()
        #
        # Switch cells in the second seed (s2) from state 1 (red) to state 2 (blue)
        #
        s2.red2blue()
        #
        # Rule file
        #
        rule_name = "Immigration"
        #
        # Set toroidal universe of height yspan and width xspan
        # Base the s1ze of the universe on the s1zes of the seeds
        #
        # g = the Golly universe
        #
        [g_width, g_height, g_time] = dimensions(s1, s2, \
          width_factor, height_factor, time_factor)
        #
        # set algorithm -- "HashLife" or "QuickLife"
        #
        g.setalgo("QuickLife")  # use "HashLife" or "QuickLife"
        g.autoupdate(False)  # do not update the view unless requested
        g.new(rule_name)  # initialize cells to state 0
        g.setrule(rule_name + ":T" + str(g_width) + "," +
                  str(g_height))  # make a toroid
        #
        # Find the min and max of the Golly toroid coordinates
        #
        [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g)
        #
        # Set magnification for Golly viewer
        #
        g.setmag(set_mag(g))
        #
        # Randomly place seed s1 somewhere in the left s1de of the toroid
        #
        s1.insert(g, g_xmin, -1, g_ymin, g_ymax)
        #
        # Randomly place seed s2 somewhere in the right s1de of the toroid
        #
        s2.insert(g, +1, g_xmax, g_ymin, g_ymax)
        #
        # Run for a fixed number of generations.
        # Base the number of generations on the sizes of the seeds.
        # Note that these are generations ins1de one Game of Life, not
        # generations in an evolutionary sense. Generations in the
        # Game of Life correspond to growth and decay of a phenotype,
        # whereas generations in evolution correspond to the reproduction
        # of a genotype.
        #
        g.run(g_time)  # run the Game of Life for g_time time steps
        g.update()  # need to update Golly to get counts
        #
        # Count the populations of the two colours. State 1 = red = seed1.
        # State 2 = blue = seed2.
        #
        [count1, count2] = count_pops(g)
        #
        # We need to make an adjustment to these counts. We don't want to
        # use the total count of living cells; instead we want to use
        # the increase in the number of living cells over the course of
        # the contest between the two organisms. The idea here is that
        # we want to reward seeds according to their growth during the
        # contest, not according to their initial states. This should
        # avoid an evolutionary bias towards larger seeds simply due
        # to size rather than due to functional properties. It should
        # also encourage efficient use of living cells, as opposed to
        # simply ignoring useless living cells.
        #
        # s1.num_living = initial number of living cells in s1
        # s2.num_living = initial number of living cells in s2
        #
        if (s1.num_living < count1):
            count1 = count1 - s1.num_living
        else:
            count1 = 0
        #
        if (s2.num_living < count2):
            count2 = count2 - s2.num_living
        else:
            count2 = 0
        #
        # Now we are ready to determine the winner.
        #
        if (count1 > count2):
            score1 = score1 + 1.0
        elif (count2 > count1):
            score2 = score2 + 1.0
        else:
            score1 = score1 + 0.5
            score2 = score2 + 0.5
        #
    #
    # Normalize the scores
    #
    score1 = score1 / num_trials
    score2 = score2 / num_trials
    #
    return [score1, score2]
Пример #12
0
  parity=1 if s[0]=="O" else 0
  input+=[[int(s[1:]),parity]]
for i,p in input:
  if elbowloc%2==0: # which recipe to use depends on current elbow chirality
    targetlane = i
  else:
    targetlane = -i
  if elbowloc<-48: # -32 doesn't work for the end of the recipe
    move,recipe,parity = posdict[targetlane]
  else:
    move,recipe,parity = negdict[targetlane]
  elbowloc+=move
  adjustedrecipe = recipe[2:] # skip the initial "0"
#  g.note(str([targetlane, move, recipe, parity]))
  if (total+parity+p)%2==1:
    # change the last number in the previous recipe, to flip the parity of the current recipe
    output[-1]+=1
    total+=1
  # now add the current recipe to the total
  for s in adjustedrecipe.split(","): total+=int(s)

  output+=eval("["+adjustedrecipe+"]")
 
# build the resulting recipe and display in a new layer
 
g.setclipstr(str(output).replace("["," ").replace("]","").replace(" ",""))
pat=makerecipe(output[:-1])
g.addlayer()
g.putcells(g.join(elbow,g.transform(pat,5,2)))
g.setalgo("HashLife")
Пример #13
0
## This script generate an ECA rule and emulate it on a torus of width 200. 
## Written by Feng ([email protected]) Feb 2017.
import golly
rnum=golly.getstring('TCA number','6152');




r=bin(int(rnum));
r=r[:1:-1];
r+='0'*(18-len(r));

rule=[i for x,i in zip(r,range(len(r))) if x=='1'];

alias='b';

ps=1;
for a in rule:
	if a>8 and ps:
		alias+='s';
		ps=0;
	alias+=str((a)%9)
if ps==1:
	alias+='s';


golly.setalgo("QuickLife")
# golly.note(alias)
golly.setrule(alias);
golly.setclipstr('\n'+rnum);
Пример #14
0
    golly.exit()  # user hit Cancel

# add new converters here as they become available:
Converters = {
    "vonNeumann": ConvertRuleTableTransitionsToRuleTree,
    "Moore": ConvertRuleTableTransitionsToRuleTree,
    "triangularVonNeumann": EmulateTriangular,
    "triangularMoore": EmulateTriangular,
    "Margolus": EmulateMargolus,
    "square4_figure8v": EmulateMargolus,
    "square4_figure8h": EmulateMargolus,
    "square4_cyclic": EmulateMargolus,
    "oneDimensional": EmulateOneDimensional,
    "hexagonal": EmulateHexagonal,
}

golly.show("Reading from rule table file...")
n_states, neighborhood, transitions = ReadRuleTable(filename)

if not neighborhood in Converters:
    golly.warn("Unsupported neighborhood: " + neighborhood)
    golly.show("")
    golly.exit()

golly.show("Building rule tree...")
rule_name = Converters[neighborhood](neighborhood, n_states, transitions, filename)

golly.setalgo("RuleTree")
golly.setrule(rule_name)
golly.show("Created " + rule_name + ".tree and selected that rule.")
Пример #15
0
                        rotate4[dir][0][1]*y + offset4[dir][0]*6
                    row = 15 + rotate4[dir][1][0] * x + rotate4[dir][1][
                        1] * y + offset4[dir][1] * 6
                    pixels[row][column] = [bg_col, fg_col, eyes,
                                           mid][ant7x7[y][x]]
for color in range(n_colors):
    bg_col = palette[color]
    for row in range(15):
        for column in range(15):
            pixels[row][(color - 1) * 15 + column] = bg_col
    for row in range(7):
        for column in range(7):
            pixels[15 + row][(color - 1) * 15 + column] = bg_col
WriteBMP(pixels, golly.getdir('rules') + rule_name + '.icons')

golly.setalgo('RuleTree')
golly.setrule(rule_name)

golly.new(rule_name + '-demo.rle')
golly.setcell(0, 0, encode(0, 0, 0))  # start with a single turmite
'''
# we make a turmite testbed so we don't miss interesting behaviour

# create an area of random initial configuration with a few turmites
for x in range(-300,-100):
    for y in range(-100,100):
        if x%50==0 and y%50==0:
            golly.setcell(x,y,n_colors) # start with a turmite facing N
        else:
            golly.setcell(x,y,random.randint(0,n_colors-1))
            
Пример #16
0
# exec() only works if all lines end with LF, so we need to convert
# any Win line endings (CR+LF) or Mac line endings (CR) to LF
CR = chr(13)
LF = chr(10)
try:

    exec(golly.getclipstr().replace(CR+LF,LF).replace(CR,LF))
    MakeRuleTreeFromTransitionFunction( n_states, n_neighbors, transition_function,
                                        golly.getdir("rules")+name+".tree" )
    
    # use name.tree to create name.rule (with no icons);
    # note that if name.rule already exists then we only replace the info in
    # the @TREE section to avoid clobbering any other info added by the user
    ConvertTreeToRule(name, n_states, [])
    
    golly.setalgo("RuleLoader")
    golly.setrule(name)
    golly.show("Created "+golly.getdir("rules")+name+".rule and switched to that rule.")

except:
    import sys
    import traceback
    exception, msg, tb = sys.exc_info()
    golly.warn(\
 '''To use this script, copy a Python format rule definition into the clipboard, e.g.:

 name = "ParityNWE"
 n_states = 5
 n_neighbors = 4
 # order for 4 neighbors is N, W, E, S, C
 def transition_function ( s ) :
Пример #17
0
    if os.access(ONcellFileName,
                 os.W_OK) or not os.access(ONcellFileName, os.F_OK):
        try:
            ONcell.save(ONcellFileName,
                        "Metapixel ON cell: Brice Due, Spring 2006")
        except:
            g.show("Failed to save file version of ON cell: " + ONcellFileName)
            os.remove(ONcellFileName)

OFFcell += RuleBits
ONcell += RuleBits

g.autoupdate(True)
g.new(layername)
g.setalgo("QuickLife")  # qlife's setcell is faster

for j in xrange(selheight):
    for i in xrange(selwidth):
        golly.show("Placing (" + str(i + 1) + "," + str(j + 1) + ") tile" +
                   " in a " + str(selwidth) + " by " + str(selheight) +
                   " rectangle.")
        if livecell[i][j]:
            ONcell.put(2048 * i - 5, 2048 * j - 5)
        else:
            OFFcell.put(2048 * i - 5, 2048 * j - 5)
        g.fit()

g.show("")
g.setalgo("HashLife")  # no point running a metapattern without hashing
g.setoption("hyperspeed", False)  # avoid going too fast
time_factor = mparam.time_factor
#
# At the bottom of this loop, the user will be prompted to quit
# the loop, if desired.
#
while True:
    # random rotation of seeds
    s1 = seed1.random_rotate()
    s2 = seed2.random_rotate()
    # switch red to blue in the second seed
    s2.red2blue()
    # set up Golly
    rule_name = mparam.rule_name
    [g_width, g_height, g_time] = mfunc.dimensions(s1, s2, \
        width_factor, height_factor, time_factor)
    g.setalgo("QuickLife")  # use the QuickLife algorithm
    g.new(rule_name)  # initialize cells to state 0
    g.setrule(rule_name + ":T" + str(g_width) + "," +
              str(g_height))  # make a toroid
    [g_xmin, g_xmax, g_ymin,
     g_ymax] = mfunc.get_minmax(g)  # find range of coordinates
    s1.insert(g, g_xmin, -1, g_ymin,
              g_ymax)  # insert the first seed into Golly
    s2.insert(g, +1, g_xmax, g_ymin,
              g_ymax)  # insert the second seed into Golly
    g.setmag(mfunc.set_mag(g))  # set magnification
    #
    g.update()  # show the intial state
    #
    g.note("These are the intial seeds.\n" + \
      "Red is on the left and blue is on the right.\n" + \
Пример #19
0
rulesFileName = "rule_sets" + str(currentGen) + ".txt"
genRules = open(rulesFileName, 'r')

# Update Current Generation
newGen = rootGA.find("CurrentGeneration")
newGen.text = str(int(currentGen) + 1)
tree.write('config.xml')

for j in range(int(numPopulation)):
    # Create New Window and Fill X% of YxY Square Grid with Random Noise
    g.new("test-pattern")
    g.select([0, 0, int(gridSize), int(gridSize)])
    g.randfill(int(fillPerc))

    # Declare Algorithm and Rule
    g.setalgo("QuickLife")

    # Read In Rule Set from File
    rule = genRules.readline().strip()
    g.setrule(rule)

    # Set Directory Back to Parent Folder
    fileLoc = g.getdir("rules") + generationDir
    # Creates Subfolder specific to Rule Set to hold Generation Patterns
    fileLoc += rule.replace("/", "_") + "/"
    if (os.path.isdir(fileLoc) is not True):
        os.mkdir(fileLoc)

    # Prepare File Names for each Genereration's Pattern File
    fileNamePrefix = fileLoc + rule.replace("/", "_") + "_"
Пример #20
0
    if os.access(ONcellFileName,
                 os.W_OK) or not os.access(ONcellFileName, os.F_OK):
        try:
            ONcell.save(ONcellFileName,
                        "Metapixel ON cell: Brice Due, Spring 2006")
        except:
            g.show("Failed to save file version of ON cell: " + ONcellFileName)
            os.remove(ONcellFileName)

if not varlife:
    OFFcell += RuleBits
    ONcell += RuleBits

g.new(layername)
g.setalgo("QuickLife")
file_num = 1

for j in xrange(selheight):
    for i in xrange(selwidth):
        golly.show("Placing (" + str(i + 1) + "," + str(j + 1) + ") tile" +
                   " in a " + str(selwidth) + " by " + str(selheight) +
                   " rectangle.")
        if not varlife:
            if livecell[i][j]:
                ONcell.put(2048 * i - 5, 2048 * j - 5)
            else:
                OFFcell.put(2048 * i - 5, 2048 * j - 5)
        else:
            cell = cells[i][j]
	def Main(self):
		
		g.show("left click on a pattern to change, 'h' for help")
		gollyMode = False
		
		while True:
		
			event = g.getevent()
			
			if ("key" in event and "return" in event) or (gollyMode and " a " in event):
				gollyMode = not gollyMode
				
				if gollyMode:
					g.show("In golly mode")
					g.update()

				else: 
					g.show("left click on a pattern, right click to finish")
					g.setrule("B3/S23")
					g.setalgo("HashLife")
					g.reset()
				
					g.update()
				
				continue 
				
			if gollyMode:
				
				if " delete " in event: 
					g.clear(0)
					
				if "click" in event and "ctrl" in event and g.getxy() != "":
					
					x, y = g.getxy().split()
					
					cell = g.getcell(int(x), int(y))
					
					if cell >= 0 and cell <= 1:
						g.setcell(int(x), int(y), 1 - cell)
					
					g.update()
				
				if " c " in event and "ctrl" in event and g.getselrect() != []:	
					g.copy()
				
				if " v " in event and "ctrl" in event and g.getxy() != "":
				
					x, y = g.getxy().split()
					
					g.paste(int(x), int(y), "or")
				
				if " space " in event:	
					if "ctrl" in event:
						g.run(10)
					else:
						g.run(1)
						
				g.doevent(event)
				continue 
				
			
			if "click" in event:
				
				if "left" in event:
					
					if self.ExistinCircuitHandler() == None:
						if self.SignalClickHandler(event) == None:
							g.show("left click on a pattern, h for help")
		
		
			elif "key" in event:
				if " space " in event:
					for i in xrange(0, 30):
						g.run(60)
						g.update()
						
					g.reset()
					g.update()		
					
				if " a " in event:
					
					if g.getrule() == "Perrier":
						g.setrule("B3/S23")
						g.setalgo("HashLife")
						g.update()
						
						
					else:
						g.setrule("Perrier")
						
						for key in self.smarCells:
							x, y = key.split(":")
							g.setcell(int(x), int(y),  self.smarCells[key] + 2)
						
						gollyMode = True
						g.show("In golly mode")
						g.update()
				
				if " s " in event:
					fname = os.path.join(g.getdir("data"), "MetadataManager.json")
					#self.Save(fname)
				
				if " h " in event:
					noteMessage = "Viewing and Selecting\n\n"
					noteMessage += "'left click' to chose gun or glider\n"
					noteMessage += "'a' to see in colors, a to go back \n"
					noteMessage += "'space' see ahead 1800 generations \n"
					noteMessage += "'enter' gollyMode, stays in the script \n"
					
					noteMessage += "\n Editing Gun \n\n"
					noteMessage += "'left click' to place\n"
					noteMessage += "'right click' to switch gun/orientation \n"
					noteMessage += "'delete' to delete the gun \n"
					noteMessage += "'left-right arrow' - one step adjustment\n"
					
					noteMessage += "\n In Golly Mode \n\n"
					noteMessage += "'delete' to clear selection\n"
					noteMessage += "'ctrl' + 'click' to draw \n"
					noteMessage += "'ctrl' + 'c' to copy selection \n"
					noteMessage += "'ctrl' + 'v' to paste in mouse location \n"
					noteMessage += "'space' + to run 1 generation \n"
					noteMessage += "'ctrl' +'space' to run 10 generations \n"
				
					g.note(noteMessage)
f.write('# convert any MCell Margolus specification into a rule table.\n')
f.write('#\n')
f.write('n_states:2\nneighborhood:Margolus\nsymmetries:none\n\n')

# the 16 cases of the (two-state) Margolus partition are:
dot = (0,0,0,0),(1,0,0,0),(0,1,0,0),(1,1,0,0),(0,0,1,0),(1,0,1,0),(0,1,1,0),(1,1,1,0),\
      (0,0,0,1),(1,0,0,1),(0,1,0,1),(1,1,0,1),(0,0,1,1),(1,0,1,1),(0,1,1,1),(1,1,1,1)
# cell order: 1  2
#             3  4
# (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html )

for i in range(16):
    if not i == becomes[i]:
        # (we can skip no-change transitions)
        f.write(','.join(map(str,dot[i]))+' : '+\
            ','.join(map(str,dot[becomes[i]]))+\
            '   # '+str(i)+' -> '+str(becomes[i])+'\n')
f.flush()
f.close()

# emulate the rule table with tree data in a .rule file
n_states, neighborhood, transitions = ReadRuleTable(tablepath)
golly.show("Building rule...")
rule_name = EmulateMargolus(neighborhood, n_states, transitions, tablepath)
os.remove(tablepath)

golly.new(rule_name + '-demo.rle')
golly.setalgo('RuleLoader')
golly.setrule(rule_name)
golly.show('Created ' + rule_name + '.rule and selected that rule.')
Пример #23
0


m,p,p,m,m,m,f,g,p,%s
m,p,1,m,m,m,f,g,p,%s
m,1,p,m,m,m,f,g,p,%s
m,1,1,m,m,m,f,g,p,%s
m,p,p,m,m,m,f,g,1,%s
m,p,1,m,m,m,f,g,1,%s
m,1,p,m,m,m,f,g,1,%s
m,1,1,m,m,m,f,g,1,%s
1,a,b,d,e,f,g,h,c,1
p,a,b,d,e,f,g,h,c,p

'''
rnum = golly.getstring('ECA number', '110')
name = 'W' + rnum
file = golly.getdir("rules") + name + ".rule"

r = bin(int(rnum))
r = r[:1:-1]
r += '0' * (8 - len(r))
rule = r
# rule=[0, 1, 1, 1, 1, 1, 0, 0];

dct = ['p', '1']
with open(file, 'w') as f:
    f.write(head % ((name, ) + tuple([dct[int(x)] for x in rule])))
golly.setalgo("RuleLoader")
golly.setrule(name + ':T1000,0')
Пример #24
0
def score_pair(g, seed1, seed2, width_factor, height_factor, \
  time_factor, num_trials):
    """
  Put seed1 and seed2 into the Immigration Game g and see which 
  one wins and which one loses. Note that this function does
  not update the histories of the seeds.
  """
    #
    # Make copies of the original two seeds, so that the following
    # manipulations do not change the originals.
    #
    s1 = copy.deepcopy(seed1)
    s2 = copy.deepcopy(seed2)
    #
    # Initialize scores
    #
    score1 = 0.0
    score2 = 0.0
    #
    # Run several trials with different rotations and locations.
    #
    for trial in range(num_trials):
        #
        # Randomly rotate and flip s1 and s2
        #
        s1 = s1.random_rotate()
        s2 = s2.random_rotate()
        #
        # Switch cells in the second seed (s2) from state 1 (red) to state 2 (blue)
        #
        s2.red2blue()
        #
        # Rule file is "Immigration.rule"
        # Set toroidal universe of height yspan and width xspan
        # Base the s1ze of the universe on the s1zes of the seeds
        #
        # g = the Golly universe
        #
        [g_width, g_height, g_time] = dimensions(s1, s2, \
          width_factor, height_factor, time_factor)
        #
        # set algorithm -- "HashLife" or "QuickLife"
        #
        g.setalgo("QuickLife")  # use "HashLife" or "QuickLife"
        g.autoupdate(False)  # do not update the view unless requested
        g.new("Immigration")  # initialize cells to state 0
        g.setrule("Immigration:T" + str(g_width) + "," +
                  str(g_height))  # make a toroid
        #
        # Find the min and max of the Golly toroid coordinates
        #
        [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g)
        #
        # Set magnification for Golly viewer
        #
        g.setmag(set_mag(g))
        #
        # Randomly place seed s1 somewhere in the left s1de of the toroid
        #
        s1.insert(g, g_xmin, -1, g_ymin, g_ymax)
        #
        # Randomly place seed s2 somewhere in the right s1de of the toroid
        #
        s2.insert(g, +1, g_xmax, g_ymin, g_ymax)
        #
        # Run for a fixed number of generations.
        # Base the number of generations on the sizes of the seeds.
        # Note that these are generations ins1de one Game of Life, not
        # generations in an evolutionary sense. Generations in the
        # Game of Life correspond to growth and decay of a phenotype,
        # whereas generations in evolution correspond to the reproduction
        # of a genotype.
        #
        g.run(g_time)  # run the Game of Life for g_time time steps
        g.update()  # need to update Golly to get counts
        #
        # Count the populations of the two colours. State 1 = red = seed1.
        # State 2 = blue = seed2.
        #
        [count1, count2] = count_pops(g)
        #
        if (count1 > count2):
            score1 = score1 + 1.0
        elif (count2 > count1):
            score2 = score2 + 1.0
        else:
            score1 = score1 + 0.5
            score2 = score2 + 0.5
        #
    #
    # Normalize the scores
    #
    score1 = score1 / num_trials
    score2 = score2 / num_trials
    #
    return [score1, score2]
for state in range(n_states):
    for color in range(n_colors):
        bg_col = palette[color]
        fg_col = palette[state+n_colors]
        mid = [(f+b)/2 for f,b in zip(fg_col,bg_col)]
        for row in range(15):
            for column in range(15):
                pixels[row][(encode(color,state)-1)*15+column] = [bg_col,fg_col,highlight,mid][icon15x15[row][column]]
        for row in range(7):
            for column in range(7):
                pixels[15+row][(encode(color,state)-1)*15+column] = [bg_col,fg_col,highlight,mid][icon7x7[row][column]]
for color in range(n_colors):
    bg_col = palette[color]
    for row in range(15):
        for column in range(15):
            pixels[row][(color-1)*15+column] = bg_col
    for row in range(7):
        for column in range(7):
            pixels[15+row][(color-1)*15+column] = bg_col
WriteBMP(pixels,golly.getdir('rules')+rule_name+'.icons')

# now we can switch to the new rule
golly.setalgo('RuleTree')
golly.setrule(rule_name)

golly.new(rule_name+'-demo.rle')
golly.setcell(0,0,encode(0,0)) # start with a single turmite
golly.fit()

golly.show('Created '+rule_name+'.tree and '+rule_name+'.icons, and selected this rule.')
Пример #26
0
     if x == "S" or x == "B":
         totalistic_context = "none"
     if x == "S":
         bs = "1,"
     if x == "B":
         bs = "0,"
  elif x == "-":
    positive_or_inverse = "inverse"
  elif x in ["c", "a", "e", "k", "i", "v", "j", "y", "q", "r", "w", "t", "z"] and totalistic_context != "none":
     if positive_or_inverse == "positive":
        notation_letter = x
        f.write(create_table_row(bs, totalistic_context, notation_letter, []))   
     else:
        notation_letter = x
        inverse_list.append(x)


f.write("# Death otherwise"+"\n")
f.write("1,a,b,c,d,e,f,g,h,0"+"\n\n")
f.flush()
f.close()
golly.setalgo("RuleTable")
golly.setrule(rule_name)
if pastepattern != "none":
  golly.setclipstr(pastepattern)
  golly.show("Paste the pattern when you are ready....")
else:
  golly.show("Created "+rule_name+".table in "+golly.getdir("rules"))


Пример #27
0
# Bill Gosper's pure-period p1100 double MWSS gun, circa 1984.

import golly as g
from glife import *

g.new("P1100 gun")
g.setalgo("HashLife")
g.setrule("B3/S23")

# update status bar now so we don't see different colors when
# g.show is called
g.update()

glider = pattern("bo$bbo$3o!")
block = pattern("oo$oo!")
eater = pattern("oo$bo$bobo$bboo!")
bhept = pattern("bbo$boo$oo$boo!")

twobits = eater + bhept(8,3)
half = twobits + twobits[1](51,0,flip_x)
centinal = half + half(0,16,flip_y)
passthrough = centinal[1](16,3,rcw) + centinal[19](52,0,rcw) \
   + centinal[81](55,51,rccw) + centinal[99](91,54,rccw)

# build the source signal -- the most compact set of gliders
# from which all other gliders and spaceships can be generated
MWSSrecipes = glider(5759,738,rccw) + glider(6325,667,flip_x) \
   + glider[3](5824,896,flip_x) + glider[2](5912,1264) \
   + glider[2](6135,1261,flip_x) + glider[1](5912,1490,flip_y) \
   + glider(6229,4717,flip_x) + glider[1](6229,5029,flip) \
   + glider[1](5920,5032,flip_y) + glider(6230,5188,flip) \
Пример #28
0
# find the CPU id for the current run
#
current_cpu_id = cparams.current_cpu_id
#
# read the rule list and extract rules that match the current
# run's CPU id
#
rule_list = cfuncs.tsv_BS_rule_cpu(rule_file_name, current_cpu_id)
#
# Golly screen magnification
#
screen_mag = cparams.screen_mag
#
# initialize Golly
#
g.setalgo("QuickLife")  # select the algorithm for Golly
g.autoupdate(False)  # do not update the view unless requested
g.new("Classification")  # create an empty universe
g.setmag(screen_mag)  # screen magnification
#
# show parameter settings in the log file
#
parameter_settings = cfuncs.show_parameters()
log_handle.write("\nParameter Settings\n\n")
for setting in parameter_settings:
    log_handle.write(setting + "\n")
log_handle.write("\n")
#
# write a header line for the list of results
#
columns = ["rule", \
Пример #29
0
    def Main(self):

        g.show("left click on a pattern to change, 'h' for help")
        gollyMode = False

        while True:

            event = g.getevent()

            if ("key" in event and "return" in event) or (gollyMode
                                                          and " a " in event):
                gollyMode = not gollyMode

                if gollyMode:
                    g.show("In golly mode")
                    g.update()

                else:
                    g.show("left click on a pattern, right click to finish")
                    g.setrule("B3/S23")
                    g.setalgo("HashLife")
                    g.reset()

                    g.update()

                continue

            if gollyMode:

                if " delete " in event:
                    g.clear(0)

                if "click" in event and "ctrl" in event and g.getxy() != "":

                    x, y = g.getxy().split()

                    cell = g.getcell(int(x), int(y))

                    if cell >= 0 and cell <= 1:
                        g.setcell(int(x), int(y), 1 - cell)

                    g.update()

                if " c " in event and "ctrl" in event and g.getselrect() != []:
                    g.copy()

                if " v " in event and "ctrl" in event and g.getxy() != "":

                    x, y = g.getxy().split()

                    g.paste(int(x), int(y), "or")

                if " space " in event:
                    if "ctrl" in event:
                        g.run(10)
                    else:
                        g.run(1)

                g.doevent(event)
                continue

            if "click" in event:

                if "left" in event:

                    if self.ExistinCircuitHandler() == None:
                        if self.SignalClickHandler(event) == None:
                            g.show("left click on a pattern, h for help")

            elif "key" in event:
                if " space " in event:
                    for i in xrange(0, 30):
                        g.run(60)
                        g.update()

                    g.reset()
                    g.update()

                if " a " in event:

                    if g.getrule() == "Perrier":
                        g.setrule("B3/S23")
                        g.setalgo("HashLife")
                        g.update()

                    else:
                        g.setrule("Perrier")

                        for key in self.smarCells:
                            x, y = key.split(":")
                            g.setcell(int(x), int(y), self.smarCells[key] + 2)

                        gollyMode = True
                        g.show("In golly mode")
                        g.update()

                if " s " in event:
                    fname = os.path.join(g.getdir("data"),
                                         "MetadataManager.json")
                    #self.Save(fname)

                if " h " in event:
                    noteMessage = "Viewing and Selecting\n\n"
                    noteMessage += "'left click' to chose gun or glider\n"
                    noteMessage += "'a' to see in colors, a to go back \n"
                    noteMessage += "'space' see ahead 1800 generations \n"
                    noteMessage += "'enter' gollyMode, stays in the script \n"

                    noteMessage += "\n Editing Gun \n\n"
                    noteMessage += "'left click' to place\n"
                    noteMessage += "'right click' to switch gun/orientation \n"
                    noteMessage += "'delete' to delete the gun \n"
                    noteMessage += "'left-right arrow' - one step adjustment\n"

                    noteMessage += "\n In Golly Mode \n\n"
                    noteMessage += "'delete' to clear selection\n"
                    noteMessage += "'ctrl' + 'click' to draw \n"
                    noteMessage += "'ctrl' + 'c' to copy selection \n"
                    noteMessage += "'ctrl' + 'v' to paste in mouse location \n"
                    noteMessage += "'space' + to run 1 generation \n"
                    noteMessage += "'ctrl' +'space' to run 10 generations \n"

                    g.note(noteMessage)
Пример #30
0
    # and p184 HWSS guns are in the same phase (3680 = 184 * 40)
    ONcell = all + CellCenter[3680]
    
    if os.access(ONcellFileName, os.W_OK) or not os.access(ONcellFileName, os.F_OK):
       try:
          ONcell.save (ONcellFileName, "Metapixel ON cell: Brice Due, Spring 2006")
       except:
          g.show("Failed to save file version of ON cell: " + ONcellFileName)
          os.remove(ONcellFileName)
          
OFFcell += RuleBits
ONcell += RuleBits

g.autoupdate(True)
g.new(layername)   
g.setalgo("QuickLife")              # qlife's setcell is faster

for j in xrange(selheight):
   for i in xrange(selwidth):
      golly.show("Placing (" + str(i+1) + "," + str(j+1) + ") tile" +
                 " in a " + str(selwidth) + " by " + str(selheight) + " rectangle.")
      if livecell[i][j]:
         ONcell.put(2048 * i - 5, 2048 * j - 5)
      else:
         OFFcell.put(2048 * i - 5, 2048 * j - 5)
      g.fit()
   
g.show("")
g.setalgo("HashLife")               # no point running a metapattern without hashing
g.setoption("hyperspeed", False)    # avoid going too fast
g.setbase(8)
Пример #31
0
            continue  # turmite halts
        new_state = action_table[state][color][2]
        for d in range(4):
            # what direction would the turmite have to be facing to end up here?
            facing = would_have_been_facing[turn][d]
            for central_color in range(n_colors):
                # output the required transition
                f.write(str(central_color))
                for element in range(4):
                    if element == d:
                        f.write("," + str(encode(color, state, facing)))
                    else:
                        f.write(",a" + str(element))
                f.write(
                    "," +
                    str(encode(central_color, new_state, opposite_dirs[d])) +
                    "\n")

f.flush()  # ensure file is complete (only on Windows?)
f.close()

# now we can switch to the new rule
golly.setalgo("RuleTable")  # in case name.tree exists
golly.setrule(prefix + '-' + spec_string)
golly.new(prefix + '-demo.rle')

golly.setcell(0, 0, n_colors)
golly.fit()
golly.show('Created ' + prefix + '-' + spec_string +
           '.table, and selected this rule.')