Example #1
0
def make(blocks):
    g.new("circuit")
    for block in blocks:
        fname = "blocks/{}.mc".format(block[0])
        paste(g, fname, *transfo(block[1], block[2]))
    g.fit()
    g.save("circuit.mc", "mc")
Example #2
0
def add_data(PATTERN_FN):

    g.select([-2753, 891, 1092, 1397])
    g.clear(0)
    g.select([])

    input_str = open(PATTERN_FN, "r").read()

    firstbreak = input_str.find("\n")
    if firstbreak == -1:
        g.show("Error, no newlines found, invalid format")
        g.exit()

    info_line = input_str[0:firstbreak]
    input_str = input_str[firstbreak:]

    #x = 1581, y = 1396, rule = Varlife
    dataptrn = re.compile(
        br'x = (?P<xval>[0-9]{1,4}), y = (?P<yval>[0-9]{1,4}), rule = .*')

    match = dataptrn.match(info_line)
    xval = 0
    yval = 0

    if (match):
        xval = int(match.group("xval"), 10)
        yval = int(match.group("yval"), 10)

    else:
        g.show("ERROR invalid format {}".format(info_line))
        g.exit()

    ipat = pattern(input_str)
    minbox = getminbox(ipat)

    if max(xval, minbox.x) > 1200:
        g.show("ERROR inserted cell area too wide, max width is 1090")
        g.exit()

    if max(yval, minbox.y) > 1397:
        g.show("ERROR inserted cell area too tall, max height is 1397")
        g.exit()

    startx = -1661 - xval
    starty = 891

    #blankptrn.put(startx, starty)

    g.show(
        "width={}, height={} startx={}, starty={}, xval={}, yval={}, bytes={}".
        format(minbox.wd, minbox.height, startx, starty, xval, yval,
               len(input_str)))
    ipat.put(startx, starty)
    g.save("/tmp/output.mc", "rle", False)

    return "Pattern load data: width={}, height={} startx={}, starty={}, xval={}, yval={}, bytes={}".format(
        minbox.wd, minbox.height, startx, starty, xval, yval, len(input_str))
def run_patt(known_cells):
    global patt_count, meth_count
    g.new("PlutoniumSearch")
    g.reset()
    g.update()
    patt_count += 1
    #patt = g.parse(known_cells + "!")
    patt = g.parse(known_cells[1:] + "!")
    #g.note(known_cells[1:] + "!")
    g.putcells(patt)
    g.update()
    hashlist = {}
    for gene in range(999):
        if g.empty():
            break
        if g.hash(g.getrect()) in hashlist:
            p = int(g.getgen()) - hashlist[g.hash(g.getrect())]
            if not p in boring_periods:
                g.reset()
                g.save("p" + str(p) + "_" + str(cnt[p]) + ".rle", "rle")
                cnt[p] += 1
            break
        else:
            hashlist[g.hash(g.getrect())] = int(g.getgen())
            g.run(1)
        """
		except:
			# Pattern dies
			if int(g.getgen()) > min_lifespan:
				meth_count += 1
				newlifespan = int(g.getgen())
				g.new("Saving methuselah")
				g.putcells(patt)
				try:
					g.save("diehard-" + str(newlifespan) + ".rle", "rle")
				except:
					pass
				g.update()
				#max_final_pop = newpop
			break"""
    #g.warn(str(hashlist))
    g.show(str(patt_count) + "/" + str(2**(bx * by)))
if ("outfilename" in os.environ):
    pattern_fp = os.environ["outfilename"]
    g.open(os.environ["outfilename"])

if pattern_fp:
    fpath = pattern_fp
else:
    fpath = g.getpath()

dirpath = os.path.dirname(fpath)
basename = os.path.basename(fpath)
timestr = time.strftime("%Y%m%d-%H%M%S")
backuppath = os.path.join(dirpath, "backups", basename[:-3] + "_" + timestr + ".mc")

g.show(backuppath)
g.save(backuppath,"mc")

bitOff = pattern('4.DBD$5.B$4.2B$5.D$D.B2.F2.3D$3BD2FD4B$D4.D2.3D$5.B$4.DBD$4.DBD$4.DBD!')
bitOn = pattern('4.DBD$5.B.B$4.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$4.DBD$4.DBD$4.DBD!')

bitOffRedLin = pattern('4.DBD$5.B$4.2B$5.D$D.B2.F2.3D$3BD2FD4B$D4.D2.3D$5.B$4.DBD$4.DBD$3F.DBD.3F!')
bitOnRedLine = pattern('4.DBD$5.B.B$4.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$4.DBD$4.DBD$3F.DBD.3F!')

bitOffHorzLine = pattern('4.DBD$.F3.B$.F2.2B$5.D$D.B2.F2.3D$3BD2FD4B$D4.D2.3D$5.B$.F2.DBD$.F2.DBD$4.DBD!')
bitOnHorzLine = pattern('4.DBD$.F3.B.B$.F2.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$.F2.DBD$.F2.DBD$4.DBD!')

"""
x = 11, y = 11, rule = Varlife
4.DBD$.F3.B.B$.F2.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$.F2.DBD$.F2.DBD$4.DBD!
"""
Example #5
0
d1 = delta * 15 + 9
d2 = 0
d3 = 9

g.open("reflecteur.mc")

# 2eme reflecteur
g.select(ref2)
g.cut()
g.run(29 + 4 * d1)
g.paste(-19 - d1, 16 + d1, "or")

# 3eme reflecteur
g.select(ref3)
g.cut()
g.run(4 * d1)
g.run(4 + 4 * d2)
g.paste(d2 + 1 - d1, 34 + d2 + d1, "or")

# 4eme reflecteur
g.select(ref4)
g.cut()
g.run(4 * (d1 + d2))
g.run(3 + 4 * d3)
g.paste(d2 + 17 - d1 + d3, 15 + d2 + d1 - d3, "or")

g.select([-80, -80, 10, 10])
g.clear(0)

g.save("deca_" + str(decalage) + ".mc", "mc")
Example #6
0
iters = (1 + int(iters / distForward)) * distForward

g.show("Iterating Tail to reach " + str(iters) + " iter")
g.fit()
g.update()
#The speed is negative 
Head = -speed * iters + 576
Tail = -speed * (iters - l * 2) + l + 576

GotoLimited(iters, 5)
rect = g.getrect()

g.select([rect[0], Head - 3 * distBack, rect[2], Tail - Head + 3 * distBack + 1500])
g.clear(1)

g.save(path.join(dir, str(step) + "_" + str(period) + "_Back.rle"), "rle", False)

#'''

#This code synchronize the backward recipes to fit with forward created at 0,0
g.show("synchronize the backward recipes to fit with forward")

g.new("")
MakeForwardSalvo(step, 0, 0, 0, True, True)
forwardRecipe = FindWssByDirection(True, distForward)
x0, y0, id  = forwardRecipe[0]
ConvertToRelative(forwardRecipe, distForward)

g.open(path.join(dir, str(step) + "_" + str(period) + "_Back.rle"), False)
rect = g.getrect()
Example #7
0
import os
import golly as g
#g.select(g.getrect())
oldrule=g.getrule()
i=0
g.autoupdate(0)
while i==0:
	g.run(1)
	g.save('temp','rle')
	g.setrule('S_input')
	g.run(1)
	cellindex=g.getlayer()
	execfile("histogram_2002_r75.py")
	histindex=g.getlayer()
	g.setlayer(cellindex)
	g.open('temp')
	g.setlayer(histindex)
	g.fit()
	g.update()
	g.setlayer(cellindex)
	i=+1
Example #8
0
    # 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("/", "_") + "_"

    # Loop and Save Patterns
    for i in range(int(timeElapsed) + 1):
        # Stop Loop if Universe is Empty
        if (g.empty()):
            break

        # Determine File Names
        fileNameRLE = fileNamePrefix + str(i) + ".rle"
        # Determine Previous File Names
        fileNamePrevRLE = fileNamePrefix + str(i - 1) + ".rle"

        g.save(fileNameRLE, "rle")
        # Compare Previous Generation to Determine Class I Systems
        if (i > 0 and compare_rle(fileNameRLE, fileNamePrevRLE)):
            break

        g.run(1)

# Close
g.doevent("key q cmd")
Example #9
0
'''
toimage2.py

Saves the current configuration to a mc, then loads the mc, and converts it to an image.
Assumes two virtual cells inside every physical (golly) cell.
'''
import parameters

reload(parameters)
from parameters import mcfn, bmpfn2, nstates
from gollytools.macrocell import Macrocell
from gollytools.bmp import display
from golly import save

save(mcfn, 'mc')
Macrocell().from_file(mcfn).setnstates2(nstates).bmp2().save(bmpfn2)
display(bmpfn2)
Example #10
0
            boxsel = [-int(tilewd / 2), -int(tilewd / 2), tilewd, tilewd]
            # output a buffer line and an index
            if rand:
                myfile.write('\n \n hash%i arealist%i \n' %
                             (topohash[pos], topoarea[pos]))
            else:
                myfile.write('\n \n index%i \n' % posi)

            # tile the universe 100*100

            tileit(i, tilewd)
            g.select(boxsel)

            tempfile = g.getdir('rules') + 'topoS_temptile'
            g.putcells(i, 0, 0)
            g.save(tempfile, 'rle')
            list_reset()

            # An I/O race
            # tile_clist=g.getcells(boxsel)
            # g.new('')
            # t1=time()
            # tile_clist=g.putcells(tile_clist,0,0)
            # t2=time()

            # tempfile=g.getdir('rules')+'topoS_temptile'
            # g.save(tempfile,'rle')
            # t3=time()
            # g.open(tempfile)
            # t4=time()
Example #11
0
        except ValueError:
            space_len = len(comments[i])-1
    if not began: #if still introduction
        comments2 += comments[i] + '\n'
    elif i != len(comments)-1 and '#O' in comments[i+1]: #puts pattern discoverer on name line with brackets
        comments2 += comments[i] + ' [' + comments[i+1][3:] + ']\n'
    elif '#C' in comments[i] and '----' not in comments[i]: #spaces comment lines to match pattern number
        comments2 += '#C' + ' '*space_len*began + comments[i][3:] + '\n'
    elif '#O' in comments[i]: #discoverers are put on the previous line; this is so that they're not duplicated
        pass
    else:
        comments2 += comments[i] + '\n'
comments2_intro = comments2[:comments2.index('1.0.0')]
comments2_patterns = comments2[comments2.index('1.0.0'):]
comments2_patterns = comments2_patterns.replace("#N ","#C ") #comments file only has one #N, and it's at the very beginning
comments2_patterns = comments2_patterns.replace(' #C', '\n#C')
comments2 = comments2_intro + comments2_patterns
    
# show_message('Comments size: %s KB' % ((len(comments2)+500)//1000),0.5)
show_message('Comments size: %s KB text, %s KB LifeViewer labels' % ((len(comments2)+500)//1000, (len(lvcomments)+500)//1000),0)
tempname = os.path.join(g.getdir("temp"),"oscillators.rle")
g.save(tempname, "rle")
with open(tempname,"r") as f:
    allrle = f.read()
with open(tempname,"w") as f:
    f.write(comments2 + "\n" + allrle)
g.open(tempname)  # this integrates the comments into the currently open pattern file
                  # there still seem to be some issues with keeping the comments after re-saving the file,
                  # but I'll deal with that separately.  Meanwhile:
g.note("Click OK to copy pattern to the clipboard, including comments at the beginning and LifeViewer commands at the end.")
g.setclipstr(comments2 + "\n" + allrle + lvcomments)
import golly as g
import os.path

# default base path as the Desktop, change it if needed
default_path = os.path.expanduser('~/Desktop')
# default name is the current pattern name without extension
pattern_name = g.getname().split('.')[0]
# getting an output path
export_path = g.savedialog('Choose the directory and name', 'All files (*)|*',
                           default_path, pattern_name)
if export_path == "":
    export_path = default_path

# number of generations
num_generations = 10

# has a selection been made?
selected = 1 if len(g.getselrect()) > 0 else 0

for i in range(num_generations):
    # advance by one generation (checking if something is selected)
    if selected == 1:
        g.advance(0, 1)
    else:
        g.run(1)
    # export to a new file
    file_path = '%s-%d.rle' % (export_path, i)
    g.show(file_path)
    g.save(file_path, 'rle')
import os.path

# default base path as the Desktop, change it if needed
default_path = os.path.expanduser('~/Desktop')
# default name is the current pattern name without extension
pattern_name = g.getname().split('.')[0]
# getting an output path
export_path = g.savedialog('Choose the directory and name',
                           'All files (*)|*',
                           default_path,
                           pattern_name)
if export_path == "":
    export_path = default_path

# number of generations
num_generations = 10

# has a selection been made?
selected = 1 if len(g.getselrect()) > 0 else 0

for i in range(num_generations):
    # advance by one generation (checking if something is selected)
    if selected == 1:
        g.advance(0, 1)
    else:
        g.run(1)
    # export to a new file
    file_path = '%s-%d.rle' % (export_path, i)
    g.show(file_path)
    g.save(file_path, 'rle')
Example #14
0
            return True

    return False


#g.show(str(calc_p_boring(0.83)))

found = 0
fail_reasons = [0, 0, 0, 0, 0, 0, 0]

for i in range(10000000):
    p_rule = 0.6

    rand_rule(p_rule)
    bor = rule_boring()

    if bor != -1:
        fail_reasons[bor] += 1
    else:
        if explode_dense():
            fail_reasons[2] += 1
            continue

        status = fail_cd()
        if status == -1:
            found += 1
            g.show(str([fail_reasons, found, i]))
            g.reset()
            g.save("../../rule_gen/CA{0}.rle".format(found), "rle", True)
        else:
            fail_reasons[3 + status] += 1
Example #15
0
g.show("Iterating Tail to reach " + str(iters) + " iter")
g.fit()
g.update()
#The speed is negative
Head = -speed * iters + 576
Tail = -speed * (iters - l * 2) + l + 576

GotoLimited(iters, 5)
rect = g.getrect()

g.select(
    [rect[0], Head - 3 * distBack, rect[2], Tail - Head + 3 * distBack + 1500])
g.clear(1)

g.save(path.join(dir,
                 str(step) + "_" + str(period) + "_Back.rle"), "rle", False)

#'''

#This code synchronize the backward recipes to fit with forward created at 0,0
g.show("synchronize the backward recipes to fit with forward")

g.new("")
MakeForwardSalvo(step, 0, 0, 0, True, True)
forwardRecipe = FindWssByDirection(True, distForward)
x0, y0, id = forwardRecipe[0]
ConvertToRelative(forwardRecipe, distForward)

g.open(path.join(dir, str(step) + "_" + str(period) + "_Back.rle"), False)
rect = g.getrect()
Example #16
0
'''
todensimage.py

Saves the current configuration to a mc, then loads the mc, and converts it to a density image.
'''
import parameters
reload(parameters)
from parameters import mcfn, densbmpfn, nstates, lbsl
from gollytools.macrocell import Macrocell
from gollytools.bmp import display
from golly import save
save(mcfn,'mc')
Macrocell().from_file(mcfn).setnstates2(nstates).precount_live_cells().bmpd(lbsl).save(densbmpfn)
display(densbmpfn)
Example #17
0
                Brle = Brle[:ind] + "o" + Brle[ind + 1:]
            for ch in Svalues:
                ind = 32 - int(ch) * 4
                Srle = Srle[:ind] + "o" + Srle[ind + 1:]
            RuleBits = pattern(Brle, 148, 1404) + pattern(Srle, 162, 1406)

            # apply the rule to the appropriate version of the metapixel
            metacell = (ONcell if alive else OFFcell) + RuleBits
            # place the metapixel on the board
            metacell.put(2048 * i - 5, 2048 * j - 5)
        g.fit()
        g.update()
    if varlife and j > 0 and j % 10 == 0:
        # every 10 lines, flush the board to a compressed RLE file
        # otherwise all your memory will be gone
        g.save(g.getdir("app") + "{}.rle.gz".format(file_num), "rle.gz")
        g.new(layername)
        file_num += 1

g.save(g.getdir("app") + "{}.rle.gz".format(file_num), "rle.gz")
g.show("")
g.setalgo("HashLife")  # no point running a metapattern without hashing
g.setoption("hyperspeed", False)  # avoid going too fast
g.setbase(8)
g.setstep(4)
g.step()  # save start and populate hash tables

# g.run(35328) # run one full cycle (can lock up Golly if construction has failed)
#
# Note that the first cycle is abnormal, since it does not advance the metapattern by
# one metageneration:  the first set of communication signals to adjacent cells is
Example #18
0
     if basegun == "fixed":
         fixedname = "p" + ("0000" + period)[-5:]
         folder = fixedfolder
     else:
         # g.note(basegun) #################
         fixedname = basegun + "_special_p" + ("0000" +
                                               period)[-5:] + ",0,0,0"
         folder = specialfolder
     g.open(os.path.join(folder, fixedname + ".rle"))
     bb = g.getrect()
     usebb = 1
     g.setrule("LifeHistoryToLife")
     g.run(1)
     g.setrule("Life")
     if basegun == "fixed":
         g.save(os.path.join(outfolder, fixedname) + "_fixed.rle", "rle")
         g.show("[fixed]")
         countfixed += 1
     else:
         g.save(
             os.path.join(outfolder, "p" +
                          ("0000" + period)[-5:] + "_custom") + ".rle",
             "rle")
         countspecial += 1
     r = g.getrect()
 else:
     datalist = basegun.split("_")
     if len(datalist) == 2:
         baseperiod, adjustment = datalist
     else:
         baseperiod, adjustment, finalperiod = datalist
Example #19
0
g.run(29+4*d1)
g.paste(-19-d1,16+d1, "or")


# 3eme reflecteur
g.select(ref3)
g.cut()
g.run(4*d1)
g.run(4+4*d2)
g.paste(d2+1-d1,34+d2+d1, "or")

# 4eme reflecteur
g.select(ref4)
g.cut()
g.run(4*(d1+d2))
g.run(3+4*d3)
g.paste(d2+17-d1+d3,15+d2+d1-d3, "or")

# envoyer les planeurs
g.select([-82,-80, 10, 10])
g.clear(0)
g.run(1000)

g.save("delay.mc", "mc")