示例#1
0
def bijoscar(maxsteps):
    initpop = int(g.getpop())
    initrect = g.getrect()
    if (len(initrect) == 0):
        return 0, None
    inithash = g.hash(initrect)

    for i in range(maxsteps):
        g.run(1)

        if (int(g.getpop()) == initpop):
            prect = g.getrect()
            phash = g.hash(prect)

            if (phash == inithash):
                period = i + 1

                if (prect == initrect):
                    return period, (0, 0)
                else:
                    dx = prect[0] - initrect[0]
                    dy = prect[1] - initrect[1]
                    return period, (dx, dy)

    return -1, None
示例#2
0
def bijoscar(maxsteps):

    initpop = int(g.getpop())
    initrect = g.getrect()
    if (len(initrect) == 0):
        return 0
    inithash = g.hash(initrect)

    for i in xrange(maxsteps):

        g.run(1)

        if (int(g.getpop()) == initpop): 

            prect = g.getrect()
            phash = g.hash(prect)

            if (phash == inithash):

                period = i + 1

                if (prect == initrect):
                    return period
                else:
                    return -period 
    return -1
示例#3
0
def randtopo(num, low, high):
    hashlist = []
    topolist = []
    arealist = []
    i = 0
    while i < num:
        size = random.choice(range(low, high + 1))
        area = size * size
        sel = [size, size, size, size]
        g.new('')
        randfill(sel, (1 + random.randrange(area)) * int(100 / area))
        if g.empty():
            continue
        h = g.hash(g.getrect())
        if h in hashlist:
            continue
        else:
            hashlist.append(h)
            pbox = g.getrect()
            actarea = pbox[2] * pbox[3]
            clist = g.getcells(g.getrect())
            g.store(clist, dir + 'topo_area%i_hash%i' % (actarea, h))

            clist.insert(0, pbox[2])  #prepare for tiling
            clist.insert(1, pbox[3])
            topolist.append(clist)
            arealist.append(actarea)
            i = i + 1
            continue
            return [topolist, hashlist, arealist]
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)))
示例#5
0
def is_static():
    global prev_world

    bbox = rect(g.getrect())
    if bbox.empty:
        return False

    cur_world = g.hash(g.getrect())
    if prev_world and prev_world == cur_world:
        return True
    else:
        prev_world = cur_world
示例#6
0
def analyse (gogen, glcnt, minpop, maxpop, mingl):
  if glcnt < mingl:
    return (False, 0)
  
  g.run (gogen)
  inrect = g.getrect ()
  clean (inrect)

  endpop = int (g.getpop ())
  if endpop < minpop or endpop > maxpop:
    return (False, 0)

  rect = g.getrect ()
  if rect == []:
    return (True, 0)
  else:
    addmarkers (inrect)
    return (True, g.hash (inrect))
示例#7
0
def oscillating():
    # return True if the pattern is empty, stable or oscillating

    # first get current pattern's bounding box
    csel = g.getselrect()
    g.shrink()
    prect = g.getselrect()
    g.select(csel)
    pbox = rect(prect)
    if pbox.empty:
        g.show("The pattern is empty.")
        return True

    # get current pattern and create hash of "normalized" version -- ie. shift
    # its top left corner to 0,0 -- so we can detect spaceships and knightships
    ## currpatt = pattern( g.getcells(prect) )
    ## h = hash( tuple( currpatt(-pbox.left, -pbox.top) ) )

    # use Golly's hash command (3 times faster than above code)
    h = g.hash(prect)

    # check if outer-totalistic rule has B0 but not S8
    rule = g.getrule().split(":")[0]
    hasB0notS8 = rule.startswith("B0") and (rule.find("/") >
                                            1) and not rule.endswith("8")

    # determine where to insert h into hashlist
    pos = 0
    listlen = len(hashlist)
    while pos < listlen:
        if h > hashlist[pos]:
            pos += 1
        elif h < hashlist[pos]:
            # shorten lists and append info below
            del hashlist[pos:listlen]
            del genlist[pos:listlen]
            del poplist[pos:listlen]
            del boxlist[pos:listlen]
            break
        else:
            # h == hashlist[pos] so pattern is probably oscillating, but just in
            # case this is a hash collision we also compare pop count and box size
            if (pbox.wd == boxlist[pos].wd) and \
               (pbox.ht == boxlist[pos].ht):
                # (int(g.getpop()) == poplist[pos])

                period = int(g.getgen()) - genlist[pos]

                if hasB0notS8 and (period % 2 > 0) and (pbox == boxlist[pos]):
                    # ignore this hash value because B0-and-not-S8 rules are
                    # emulated by using different rules for odd and even gens,
                    # so it's possible to have identical patterns at gen G and
                    # gen G+p if p is odd
                    return False

                if period == 1:
                    if pbox == boxlist[pos]:
                        g.show("The pattern is stable.")
                    else:
                        show_spaceship_speed(1, 0, 0)
                elif pbox == boxlist[pos]:
                    g.show("Oscillator detected (period = " + str(period) +
                           ")")
                else:
                    deltax = abs(boxlist[pos].x - pbox.x)
                    deltay = abs(boxlist[pos].y - pbox.y)
                    show_spaceship_speed(period, deltax, deltay)
                return True
            else:
                # look at next matching hash value or insert if no more
                pos += 1

    # store hash/gen/pop/box info at same position in various lists
    hashlist.insert(pos, h)
    genlist.insert(pos, int(g.getgen()))
    poplist.insert(pos, int(g.getpop()))
    boxlist.insert(pos, pbox)

    return False
示例#8
0
def oscillating():
   # return True if the pattern is empty, stable or oscillating
   
   # first get current pattern's bounding box
   prect = g.getrect()
   pbox = rect(prect)
   if pbox.empty:
      g.show("The pattern is empty.")
      return True
   
   # get current pattern and create hash of "normalized" version -- ie. shift
   # its top left corner to 0,0 -- so we can detect spaceships and knightships
   ## currpatt = pattern( g.getcells(prect) )
   ## h = hash( tuple( currpatt(-pbox.left, -pbox.top) ) )

   # use Golly's hash command (3 times faster than above code)
   h = g.hash(prect)

   # check if outer-totalistic rule has B0 but not S8
   rule = g.getrule().split(":")[0]
   hasB0notS8 = rule.startswith("B0") and (rule.find("/") > 1) and not rule.endswith("8")
   
   # determine where to insert h into hashlist
   pos = 0
   listlen = len(hashlist)
   while pos < listlen:
      if h > hashlist[pos]:
         pos += 1
      elif h < hashlist[pos]:
         # shorten lists and append info below
         del hashlist[pos : listlen]
         del genlist[pos : listlen]
         del poplist[pos : listlen]
         del boxlist[pos : listlen]
         break
      else:
         # h == hashlist[pos] so pattern is probably oscillating, but just in
         # case this is a hash collision we also compare pop count and box size
         if (int(g.getpop()) == poplist[pos]) and \
            (pbox.wd == boxlist[pos].wd) and \
            (pbox.ht == boxlist[pos].ht):
            period = int(g.getgen()) - genlist[pos]
            
            if hasB0notS8 and (period % 2 > 0) and (pbox == boxlist[pos]):
               # ignore this hash value because B0-and-not-S8 rules are
               # emulated by using different rules for odd and even gens,
               # so it's possible to have identical patterns at gen G and
               # gen G+p if p is odd
               return False
            
            if period == 1:
               if pbox == boxlist[pos]:
                  g.show("The pattern is stable.")
               else:
                  show_spaceship_speed(1, 0, 0)
            elif pbox == boxlist[pos]:
               g.show("Oscillator detected (period = " + str(period) + ")")
            else:
               deltax = abs(boxlist[pos].x - pbox.x)
               deltay = abs(boxlist[pos].y - pbox.y)
               show_spaceship_speed(period, deltax, deltay)
            return True
         else:
            # look at next matching hash value or insert if no more
            pos += 1
   
   # store hash/gen/pop/box info at same position in various lists
   hashlist.insert(pos, h)
   genlist.insert(pos, int(g.getgen()))
   poplist.insert(pos, int(g.getpop()))
   boxlist.insert(pos, pbox)

   return False
示例#9
0
    live_cells = dict_lc[g.getrule().split(':')[0]]
    if not sel:
        clist = g.getcells(g.getrect())
    else:
        clist = g.getcells(g.getselrect())
    return sum(clist[2::3].count(x) for x in live_cells)


dict_lc = {'BDRainbow': [2, 4], 'BGRainbowR2': [2, 4]}

input = (g.getstring('How many steps?/similarity distance?', '2000/1'))
numsteps = int(input.split('/')[0])
dmax = int(input.split('/')[1])

poplist = []
hashlist = [int(g.hash(g.getrect()))]
popold = int(g.getpop())
dead = 0

if g.getrule().split(':')[0] in dict_lc:
    popfunc = lambda: popcount()

else:
    popfunc = lambda: g.getpop()

for i in range(numsteps):
    g.run(1)
    if g.empty():
        break
    poplist.append(int(popfunc()))
    h = int(g.hash(g.getrect()))
示例#10
0
    remainder = g.getcells(g.getrect())

if len(ngp3) % 2 == 0: ngp3 += [0]  # mark as three-state pattern

LONG_ENOUGH = 1024 * (len(recipelist) + 1
                      )  # extra time for the unknown non-glider pattern

g.show("Running pattern...")
g.putcells(all)
g.run(LONG_ENOUGH)
output = g.getrect()
if len(output) == 0:
    g.exit(
        "This script wasn't designed to build a big pile of nothing.  Need a hashable output."
    )
hash = g.hash(output)
g.show("Restoring pattern...")
g.select(output)
g.clear(0)
g.putcells(all)

# g.note(str([len(recipelist),recipelist]))
g.addlayer()

# first find the shortest fixed-width separation between gliders
minsep, sep = 3, 256

while 1:
    midpoint = int(minsep + (sep - minsep) / 2)
    offset = max(nongliderpat[1::2]) + 4
    g.show("Regenerating pattern at midpoint = " + str(midpoint) +
示例#11
0
# minimal code for oscillators (only) --
# can be faster than an equivalent oscar.py/.lua run (I think)
# and can also be arranged to run in parallel, if some copies of the
# unknown pattern are advanced with HashLife, then checked for a hash match
# from that point.
import golly as g

h = g.hash([-608, -609, 1220, 1220])
newhash = 0
count = 0

while newhash != h:
    g.run(1)
    count += 1
    newhash = g.hash([-608, -609, 1220, 1220])
    if count % 100 == 0:
        g.show(str([count, h, newhash]))
示例#12
0
import golly as g
import random
from glife import *

g.setclipstr(str(g.hash(g.getselrect())))

示例#13
0
        g.step()
        iterations += 1
    end_time = time()

    status = o.status

    if iterations >= max_iter:
        status = "timeout"
        #f2.write("%d, %s\n" % (trial_number, str(test_list)))
        #g.store(test_list, rlepatterns_filename%(trial_number))

    elif initial_pop<=g.getpop() and status == '':
        if iterations==0:
            status = "no_change"
        elif g.empty() == False:
            current_clist = g.hash(g.getrect())
            g.step()
            next_clist = g.hash(g.getrect())
            if current_clist == next_clist:
                status = "stable"
            else:
                status = "glider"

    #if status is 'glider':
    #    g.store(test_list, rlepatterns_filename%(trial_number))

    d = calculate_density()
    f.write("%d,%d,%s,%s,%f,%f,%s,%f\n" % (trial_number, iterations, initial_pop, g.getpop(), initial_d, d, status, end_time-start_time))

    progress = float(100*(trial_number+1)) / float(number_of_tests)
    g.show("progress: %.1f%%, iterations: %d, pop: %s, density: %6f, status: %s" % (progress, iterations, g.getpop(), d, status))