-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapgsearch_repurposed.py
More file actions
3052 lines (2446 loc) · 104 KB
/
Copy pathapgsearch_repurposed.py
File metadata and controls
3052 lines (2446 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# **************************************************************
# * This is a modified version of Adam P Goucher's Ash Pattern *
# * Generator (apgsearch-2015-05-25.py), which was designed to *
# * generate random soups for cellular automata and run them *
# * to quiescence, to see what remains. *
# * *
# * Our modified version is designed to analyze runs of an *
# * evolutionary algorithm called Model-S, which models *
# * symbiosis in the Immigration Game, a variation of the *
# * Game of Life. The analysis method is essentially the same, *
# * but (1) the soups we study are all generated by evolution *
# * in Model-S and (2) we study one soup at a time, rather *
# * than merging many soups, because we are interested in *
# * comparing different populations of soups, generated from *
# * different settings of the evolutionary algorithm. *
# * *
# * Peter D. Turney, August 9, 2020. *
# **************************************************************
#
# *************************************
# * Ash Pattern Generator (apgsearch) *
# *************************************
# * Version: v1.1 (beta release) *
# *************************************
#
# -- Processes roughly 100 soups per (second . core . GHz), using caching
# and machine-learning to optimise itself during runtime.
#
# -- Can perfectly identify oscillators with period < 1000, well-separated
# spaceships of low period, and certain infinite-growth patterns (such
# guns and puffers, including both naturally-occurring types of switch
# engine).
#
# -- Separates most pseudo-objects into their constituent parts, including
# all pseudo-still-lifes of 18 or fewer live cells (which is the maximum
# theoretically possible, given there is a 19-cell pseudo-still-life
# with two distinct decompositions).
#
# -- Correctly separates non-interacting standard spaceships, irrespective
# of their proximity. In particular, a LWSS-on-LWSS is registered as two
# LWSSes, whereas an LWSS-on-HWSS is registered as a single spaceship
# (since they interact by suppressing sparks).
#
# -- At least 99.9999999999% reliable at identifying objects in asymmetrical
# soups in B3/S23 (based on the fact that out of over 10^12 objects that
# have appeared, there are no errors).
#
# -- Scores soups based on the total excitement of the ash objects.
#
# -- Support for other outer-totalistic rules, including detection and
# classification of various types of infinite growth.
#
# -- Support for symmetrical soups.
#
# -- Uploads results to the server at http://catagolue.appspot.com (which
# currently has collected over 2.7 * 10^12 objects).
#
# -- Peer-reviews others' contributions to ensure data integrity for the
# asymmetrical B3/S23 census.
#
# By Adam P. Goucher, with contributions from Andrew Trevorrow, Tom Rokicki,
# Nathaniel Johnston, Dave Greene and Richard Schank.
'''
Copyright 2015 Adam P. Goucher
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import golly as g
from glife import rect, pattern
import time
import math
import operator
import hashlib
import datetime
import os
import urllib2
def get_server_address():
# Should be 'http://catagolue.appspot.com' for the released version,
# and 'http://localhost:8080' for the development version:
return 'http://localhost:8080'
# Engages with Catagolue's authentication system ('payment over SHA-256',
# affectionately abbreviated to 'payosha256'):
#
# The payosha256_key can be obtained from logging into Catagolue in your
# web browser and visiting http://catagolue.appspot.com/payosha256
def authenticate(payosha256_key, operation_name):
g.show("Authenticating with Catagolue via the payosha256 protocol...")
payload = "payosha256:get_token:"+payosha256_key+":"+operation_name
req = urllib2.Request(get_server_address() + "/payosha256", payload, {"Content-type": "text/plain"})
f = urllib2.urlopen(req)
if (f.getcode() != 200):
return None
resp = f.read()
lines = resp.splitlines()
for line in lines:
parts = line.split(':')
if (len(parts) < 3):
continue
if (parts[1] != 'good'):
continue
target = parts[2]
token = parts[3]
g.show("Token " + token + " obtained from payosha256. Performing proof of work with target " + target + "...")
for nonce in xrange(100000000):
prehash = token + ":" + str(nonce)
posthash = hashlib.sha256(prehash).hexdigest()
if (posthash < target):
break
if (posthash > target):
continue
g.show("String "+prehash+" is sufficiently valuable ("+posthash+" < "+target+").")
payload = "payosha256:pay_token:"+prehash+"\n"
return payload
return None
# Sends the results to Catagolue:
def catagolue_results(results, payosha256_key, operation_name, endpoint="/apgsearch", return_point=None):
try:
payload = authenticate(payosha256_key, operation_name)
if payload is None:
return 1
payload += results
req = urllib2.Request(get_server_address() + endpoint, payload, {"Content-type": "text/plain"})
f = urllib2.urlopen(req)
if (f.getcode() != 200):
return 2
resp = f.read()
try:
f2 = open(g.getdir("data")+"catagolue-response.txt", 'w')
f2.write(resp)
f2.close()
if return_point is not None:
return_point[0] = resp
except:
g.warn("Unable to save catagolue response file.")
return 0
except:
return 1
# Takes approximately 350 microseconds to construct a 16-by-16 soup based
# on a SHA-256 cryptographic hash in the obvious way.
def hashsoup(instring, sym):
s = hashlib.sha256(instring).digest()
thesoup = []
if sym in ['D2_x', 'D8_1', 'D8_4']:
d = 1
elif sym in ['D4_x1', 'D4_x4']:
d = 2
else:
d = 0
for j in xrange(32):
t = ord(s[j])
for k in xrange(8):
if (sym == '8x32'):
x = k + 8*(j % 4)
y = int(j / 4)
else:
x = k + 8*(j % 2)
y = int(j / 2)
if (t & (1 << (7 - k))):
if ((d == 0) | (x >= y)):
thesoup.append(x)
thesoup.append(y)
elif (sym == 'D4_x1'):
thesoup.append(y)
thesoup.append(-x)
elif (sym == 'D4_x4'):
thesoup.append(y)
thesoup.append(-x-1)
if ((sym == 'D4_x1') & (x == y)):
thesoup.append(y)
thesoup.append(-x)
if ((sym == 'D4_x4') & (x == y)):
thesoup.append(y)
thesoup.append(-x-1)
# Checks for diagonal symmetries:
if (d >= 1):
for x in xrange(0, len(thesoup), 2):
thesoup.append(thesoup[x+1])
thesoup.append(thesoup[x])
if d == 2:
if (sym == 'D4_x1'):
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x+1])
thesoup.append(-thesoup[x])
else:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x+1] - 1)
thesoup.append(-thesoup[x] - 1)
return thesoup
# Checks for orthogonal x symmetry:
if sym in ['D2_+1', 'D4_+1', 'D4_+2']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(thesoup[x])
thesoup.append(-thesoup[x+1])
elif sym in ['D2_+2', 'D4_+4']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(thesoup[x])
thesoup.append(-thesoup[x+1] - 1)
# Checks for orthogonal y symmetry:
if sym in ['D4_+1']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x])
thesoup.append(thesoup[x+1])
elif sym in ['D4_+2', 'D4_+4']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x] - 1)
thesoup.append(thesoup[x+1])
# Checks for rotate2 symmetry:
if sym in ['C2_1', 'C4_1', 'D8_1']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x])
thesoup.append(-thesoup[x+1])
elif sym in ['C2_2']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x])
thesoup.append(-thesoup[x+1]-1)
elif sym in ['C2_4', 'C4_4', 'D8_4']:
for x in xrange(0, len(thesoup), 2):
thesoup.append(-thesoup[x]-1)
thesoup.append(-thesoup[x+1]-1)
# Checks for rotate4 symmetry:
if (sym in ['C4_1', 'D8_1']):
for x in xrange(0, len(thesoup), 2):
thesoup.append(thesoup[x+1])
thesoup.append(-thesoup[x])
elif (sym in ['C4_4', 'D8_4']):
for x in xrange(0, len(thesoup), 2):
thesoup.append(thesoup[x+1])
thesoup.append(-thesoup[x]-1)
return thesoup
# Obtains a canonical representation of any oscillator/spaceship that (in
# some phase) fits within a 40-by-40 bounding box. This representation is
# alphanumeric and lowercase, and so much more compact than RLE. Compare:
#
# Common name: pentadecathlon
# Canonical representation: 4r4z4r4
# Equivalent RLE: 2bo4bo$2ob4ob2o$2bo4bo!
#
# It is a generalisation of a notation created by Allan Weschler in 1992.
def canonise(duration):
representation = "#"
# We need to compare each phase to find the one with the smallest
# description:
for t in xrange(duration):
rect = g.getrect()
if (len(rect) == 0):
return "0"
if ((rect[2] <= 40) & (rect[3] <= 40)):
# Fits within a 40-by-40 bounding box, so eligible to be canonised.
# Choose the orientation which results in the smallest description:
representation = compare_representations(representation, canonise_orientation(rect[2], rect[3], rect[0], rect[1], 1, 0, 0, 1))
representation = compare_representations(representation, canonise_orientation(rect[2], rect[3], rect[0]+rect[2]-1, rect[1], -1, 0, 0, 1))
representation = compare_representations(representation, canonise_orientation(rect[2], rect[3], rect[0], rect[1]+rect[3]-1, 1, 0, 0, -1))
representation = compare_representations(representation, canonise_orientation(rect[2], rect[3], rect[0]+rect[2]-1, rect[1]+rect[3]-1, -1, 0, 0, -1))
representation = compare_representations(representation, canonise_orientation(rect[3], rect[2], rect[0], rect[1], 0, 1, 1, 0))
representation = compare_representations(representation, canonise_orientation(rect[3], rect[2], rect[0]+rect[2]-1, rect[1], 0, -1, 1, 0))
representation = compare_representations(representation, canonise_orientation(rect[3], rect[2], rect[0], rect[1]+rect[3]-1, 0, 1, -1, 0))
representation = compare_representations(representation, canonise_orientation(rect[3], rect[2], rect[0]+rect[2]-1, rect[1]+rect[3]-1, 0, -1, -1, 0))
g.run(1)
return representation
# A subroutine used by canonise:
def canonise_orientation(length, breadth, ox, oy, a, b, c, d):
representation = ""
chars = "0123456789abcdefghijklmnopqrstuvwxyz"
for v in xrange(int((breadth-1)/5)+1):
zeroes = 0
if (v != 0):
representation += "z"
for u in xrange(length):
baudot = 0
for w in xrange(5):
x = ox + a*u + b*(5*v + w)
y = oy + c*u + d*(5*v + w)
baudot = (baudot >> 1) + 16*g.getcell(x, y)
if (baudot == 0):
zeroes += 1
else:
if (zeroes > 0):
if (zeroes == 1):
representation += "0"
elif (zeroes == 2):
representation += "w"
elif (zeroes == 3):
representation += "x"
else:
representation += "y"
representation += chars[zeroes - 4]
zeroes = 0
representation += chars[baudot]
return representation
# Compares strings first by length, then by lexicographical ordering.
# A hash character is worse than anything else.
def compare_representations(a, b):
if (a == "#"):
return b
elif (b == "#"):
return a
elif (len(a) < len(b)):
return a
elif (len(b) < len(a)):
return b
elif (a < b):
return a
else:
return b
# Finds the gradient of the least-squares regression line corresponding
# to a list of ordered pairs:
def regress(pairlist):
cumx = 0.0
cumy = 0.0
cumvar = 0.0
cumcov = 0.0
for x,y in pairlist:
cumx += x
cumy += y
cumx = cumx / len(pairlist)
cumy = cumy / len(pairlist)
for x,y in pairlist:
cumvar += (x - cumx)*(x - cumx)
cumcov += (x - cumx)*(y - cumy)
return (cumcov / cumvar)
# Analyses a pattern whose average population follows a power-law:
def powerlyse(stepsize, numsteps):
g.setalgo("HashLife")
g.setbase(2)
g.setstep(stepsize)
poplist = [0]*numsteps
poplist[0] = int(g.getpop())
pointlist = []
for i in xrange(1, numsteps, 1):
g.step()
poplist[i] = int(g.getpop()) + poplist[i-1]
if (i % 50 == 0):
g.fit()
g.update()
if (i > numsteps/2):
pointlist.append((math.log(i),math.log(poplist[i]+1.0)))
power = regress(pointlist)
if (power < 1.10):
return "unidentified"
elif (power < 1.65):
return "zz_REPLICATOR"
elif (power < 2.05):
return "zz_LINEAR"
elif (power < 2.8):
return "zz_EXPLOSIVE"
else:
return "zz_QUADRATIC"
# Gets the period of an interleaving of degree-d polynomials:
def deepperiod(sequence, maxperiod, degree):
for p in xrange(1, maxperiod, 1):
good = True
for i in xrange(maxperiod):
diffs = [0] * (degree + 2)
for j in xrange(degree + 2):
diffs[j] = sequence[i + j*p]
# Produce successive differences:
for j in xrange(degree + 1):
for k in xrange(degree + 1):
diffs[k] = diffs[k] - diffs[k + 1]
if (diffs[0] != 0):
good = False
break
if (good):
return p
return -1
# Analyses a linear-growth pattern, returning a hash:
def linearlyse(maxperiod):
poplist = [0]*(3*maxperiod)
for i in xrange(3*maxperiod):
g.run(1)
poplist[i] = int(g.getpop())
p = deepperiod(poplist, maxperiod, 1)
if (p == -1):
return "unidentified"
difflist = [0]*(2*maxperiod)
for i in xrange(2*maxperiod):
difflist[i] = poplist[i + p] - poplist[i]
q = deepperiod(difflist, maxperiod, 0)
moments = [0, 0, 0]
for i in xrange(p):
moments[0] += (poplist[i + q] - poplist[i])
moments[1] += (poplist[i + q] - poplist[i]) ** 2
moments[2] += (poplist[i + q] - poplist[i]) ** 3
prehash = str(moments[1]) + "#" + str(moments[2])
# Linear-growth patterns with growth rate zero are clearly errors!
if (moments[0] == 0):
return "unidentified"
return "yl" + str(p) + "_" + str(q) + "_" + str(moments[0]) + "_" + hashlib.md5(prehash).hexdigest()
# This explodes pseudo-still-lifes and pseudo-oscillators into their
# constituent parts.
#
# -- Requires the period (if oscillatory) and graph-theoretic diameter
# to not exceed 4096.
# -- Never mistakenly separates a true object.
# -- Correctly separates most pseudo-still-lifes, including the famous:
# http://www.conwaylife.com/wiki/Quad_pseudo_still_life
# -- Works perfectly for all still-lifes of up to 17 bits.
# -- Doesn't separate 'locks', of which the smallest example has 18
# bits and is unique:
#
# ** **
# ** **
#
# * *** *
# ** * **
#
# To use this function (standalone), merely copy it into a script of
# the following form:
#
# import golly as g
#
# def pseudo_bangbang():
#
# [...]
#
# pseudo_bangbang()
#
# and execute it in Golly with a B3/S23 universe containing any still-
# lifes or oscillators you want to separate. Pure objects correspond to
# connected components in the final state of the universe.
#
# This has dependencies on the rules ContagiousLife, PercolateInfection
# and EradicateInfection.
#
# Not to be confused with the Unix shell instruction for repeating the
# previous instruction as a superuser (sudo !!), or indeed with any
# parodies of this song: https://www.youtube.com/watch?v=YswhUHH6Ufc
#
# Adam P. Goucher, 2014-08-25
def pseudo_bangbang(alpharule):
g.setrule("APG_ContagiousLife_" + alpharule)
g.setbase(2)
g.setstep(12)
g.step()
celllist = g.getcells(g.getrect())
for i in xrange(0, len(celllist)-1, 3):
# Only infect cells that haven't yet been infected:
if (g.getcell(celllist[i], celllist[i+1]) <= 2):
# Seed an initial 'infected' (red) cell:
g.setcell(celllist[i], celllist[i+1], g.getcell(celllist[i], celllist[i+1]) + 2)
prevpop = 0
currpop = int(g.getpop())
# Continue infecting until the entire component has been engulfed:
while (prevpop != currpop):
# Percolate the infection to every cell in the island:
g.setrule("APG_PercolateInfection")
g.setbase(2)
g.setstep(12)
g.step()
# Transmit the infection across any bridges.
g.setrule("APG_ContagiousLife_" + alpharule)
g.setbase(2)
g.setstep(12)
g.step()
prevpop = currpop
currpop = int(g.getpop())
g.fit()
g.update()
# Red becomes green:
g.setrule("APG_EradicateInfection")
g.step()
# Counts the number of live cells of each degree:
def degreecount():
celllist = g.getcells(g.getrect())
counts = [0,0,0,0,0,0,0,0,0]
for i in xrange(0, len(celllist), 2):
x = celllist[i]
y = celllist[i+1]
degree = -1
for ux in xrange(x - 1, x + 2):
for uy in xrange(y - 1, y + 2):
degree += g.getcell(ux, uy)
counts[degree] += 1
return counts
# Counts the number of live cells of each degree in generations 1 and 2:
def degreecount2():
g.run(1)
a = degreecount()
g.run(1)
b = degreecount()
return (a + b)
# If the universe consists only of disjoint *WSSes, this will return
# a triple (l, w, h) giving the quantities of each *WSS. Otherwise,
# this function will return (-1, -1, -1).
#
# This should only be used to separate period-4 moving objects which
# may contain multiple *WSSes.
def countxwsses():
degcount = degreecount2()
if (degreecount2() != degcount):
# Degree counts are not period-2:
return (-1, -1, -1)
# Degree counts of each standard spaceship:
hwssa = [1,4,6,2,0,0,0,0,0,0,0,0,4,4,6,1,2,1]
mwssa = [2,2,5,2,0,0,0,0,0,0,0,0,4,4,4,1,2,0]
lwssa = [1,2,4,2,0,0,0,0,0,0,0,0,4,4,2,2,0,0]
hwssb = [0,0,0,4,4,6,1,2,1,1,4,6,2,0,0,0,0,0]
mwssb = [0,0,0,4,4,4,1,2,0,2,2,5,2,0,0,0,0,0]
lwssb = [0,0,0,4,4,2,2,0,0,1,2,4,2,0,0,0,0,0]
# Calculate the number of standard spaceships in each phase:
hacount = degcount[17]
macount = degcount[16]/2 - hacount
lacount = (degcount[15] - hacount - macount)/2
hbcount = degcount[8]
mbcount = degcount[7]/2 - hbcount
lbcount = (degcount[6] - hbcount - mbcount)/2
# Determine the expected degcount given the calculated quantities:
pcounts = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: hacount*x, hwssa))
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: macount*x, mwssa))
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: lacount*x, lwssa))
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: hbcount*x, hwssb))
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: mbcount*x, mwssb))
pcounts = map(lambda x, y: x + y, pcounts, map(lambda x: lbcount*x, lwssb))
# Compare the observed and expected degcounts (to eliminate nonstandard spaceships):
if (pcounts != degcount):
# Expected and observed values do not match:
return (-1, -1, -1)
# Return the combined numbers of *WSSes:
return(lacount + lbcount, macount + mbcount, hacount + hbcount)
# Generates the helper rules for apgsearch, given a base outer-totalistic rule.
class RuleGenerator:
def __init__(self):
# Unless otherwise specified, assume standard B3/S23 rule:
self.bee = [False, False, False, True, False, False, False, False, False]
self.ess = [False, False, True, True, False, False, False, False, False]
self.alphanumeric = "B3S23"
self.slashed = "B3/S23"
# Save all helper rules:
def saveAllRules(self):
self.saveClassifyObjects()
self.saveCoalesceObjects()
self.saveExpungeObjects()
self.saveExpungeGliders()
self.saveIdentifyGliders()
self.saveHandlePlumes()
self.savePercolateInfection()
self.saveEradicateInfection()
self.saveContagiousLife()
# Set outer-totalistic rule:
def setrule(self, rulestring):
mode = 0
s = [False]*9
b = [False]*9
for c in rulestring:
if ((c == 's') | (c == 'S')):
mode = 0
if ((c == 'b') | (c == 'B')):
mode = 1
if (c == '/'):
mode = 1 - mode
if ((ord(c) >= 48) & (ord(c) <= 56)):
d = ord(c) - 48
if (mode == 0):
s[d] = True
else:
b[d] = True
prefix = "B"
suffix = "S"
for i in xrange(9):
if (b[i]):
prefix += str(i)
if (s[i]):
suffix += str(i)
self.alphanumeric = prefix + suffix
self.slashed = prefix + "/" + suffix
self.bee = b
self.ess = s
# Save a rule file:
def saverule(self, name, comments, table, colours):
ruledir = g.getdir("rules")
filename = ruledir + name + ".rule"
results = "@RULE " + name + "\n\n"
results += "*** File autogenerated by saverule. ***\n\n"
results += comments
results += "\n\n@TABLE\n\n"
results += table
results += "\n\n@COLORS\n\n"
results += colours
# Only create a rule file if it doesn't already exist; this avoids
# concurrency issues when booting an instance of apgsearch whilst
# one is already running.
if not os.path.exists(filename):
try:
f = open(filename, 'w')
f.write(results)
f.close()
except:
g.warn("Unable to create rule table:\n" + filename)
# Defines a variable:
def newvar(self, name, vallist):
line = "var "+name+"={"
for i in xrange(len(vallist)):
if (i > 0):
line += ','
line += str(vallist[i])
line += "}\n"
return line
# Defines a block of equivalent variables:
def newvars(self, namelist, vallist):
block = ""
for name in namelist:
block += self.newvar(name, vallist)
block += "\n"
return block
def scoline(self, chara, charb, left, right, amount):
line = str(left) + ","
for i in xrange(8):
if (i < amount):
line += chara
else:
line += charb
line += chr(97 + i)
line += ","
line += str(right) + "\n"
return line
def saveHandlePlumes(self):
comments = """
This post-processes the output of ClassifyObjects to remove any
unwanted clustering of low-period objects appearing in puffer
exhaust.
state 0: vacuum
state 7: ON, still-life
state 8: OFF, still-life
state 9: ON, p2 oscillator
state 10: OFF, p2 oscillator
state 11: ON, higher-period object
state 12: OFF, higher-period object
"""
table = """
n_states:17
neighborhood:Moore
symmetries:permute
var da={0,2,4,6,8,10,12,14,16}
var db={0,2,4,6,8,10,12,14,16}
var dc={0,2,4,6,8,10,12,14,16}
var dd={0,2,4,6,8,10,12,14,16}
var de={0,2,4,6,8,10,12,14,16}
var df={0,2,4,6,8,10,12,14,16}
var dg={0,2,4,6,8,10,12,14,16}
var dh={0,2,4,6,8,10,12,14,16}
var a={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var b={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var c={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var d={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var e={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var f={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var g={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var h={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
8,da,db,dc,dd,de,df,dg,dh,0
10,da,db,dc,dd,de,df,dg,dh,0
9,a,b,c,d,e,f,g,h,1
10,a,b,c,d,e,f,g,h,2
"""
colours = """
1 255 255 255
2 127 127 127
7 0 0 255
8 0 0 127
9 255 0 0
10 127 0 0
11 0 255 0
12 0 127 0
"""
self.saverule("APG_HandlePlumesCorrected", comments, table, colours)
def saveExpungeGliders(self):
comments = """
This removes unwanted gliders.
It is mandatory that one first runs the rules CoalesceObjects,
IdentifyGliders and ClassifyObjects.
Run this for two generations, and observe the population
counts after 1 and 2 generations. This will give the
following data:
number of gliders = (p(1) - p(2))/5
"""
table = """
n_states:17
neighborhood:Moore
symmetries:rotate4reflect
var a={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var b={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var c={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var d={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var e={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var f={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var g={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var h={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
13,a,b,c,d,e,f,g,h,14
14,a,b,c,d,e,f,g,h,0
"""
colours = """
0 0 0 0
1 255 255 255
2 127 127 127
7 0 0 255
8 0 0 127
9 255 0 0
10 127 0 0
11 0 255 0
12 0 127 0
13 255 255 0
14 127 127 0
"""
self.saverule("APG_ExpungeGliders", comments, table, colours)
def saveIdentifyGliders(self):
comments = """
Run this after CoalesceObjects to find any gliders.
state 0: vacuum
state 1: ON
state 2: OFF
"""
table = """
n_states:17
neighborhood:Moore
symmetries:rotate4reflect
var a={0,2}
var b={0,2}
var c={0,2}
var d={0,2}
var e={0,2}
var f={0,2}
var g={0,2}
var h={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var i={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var j={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var k={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var l={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var m={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var n={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var o={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var p={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
var q={3,4}
var r={9,10}
var s={11,12}
1,1,a,1,1,b,1,c,d,3
d,1,1,1,1,a,b,1,c,4
3,i,j,k,l,m,n,o,p,5
4,i,j,k,l,m,n,o,p,6
1,q,i,j,a,b,c,k,l,7
d,q,i,j,a,b,c,k,l,8
1,i,a,b,c,d,e,j,q,7
f,i,a,b,c,d,e,j,q,8
5,7,8,7,7,8,7,8,8,9
6,7,7,7,7,8,8,7,8,10
5,i,j,k,l,m,n,o,p,15
6,i,j,k,l,m,n,o,p,16
15,i,j,k,l,m,n,o,p,1
16,i,j,k,l,m,n,o,p,2
7,i,j,k,l,m,n,o,p,11
8,i,j,k,l,m,n,o,p,12
9,i,j,k,l,m,n,o,p,13
10,i,j,k,l,m,n,o,p,14
11,r,j,k,l,m,n,o,p,13
11,i,r,k,l,m,n,o,p,13
12,r,j,k,l,m,n,o,p,14
12,i,r,k,l,m,n,o,p,14
11,i,j,k,l,m,n,o,p,1
12,i,j,k,l,m,n,o,p,2
"""
colours = """
0 0 0 0
1 255 255 255
2 127 127 127