Skip to content

Instantly share code, notes, and snippets.

@harshildarji
Created May 24, 2021 09:17
Show Gist options
  • Save harshildarji/956963430ea49a305af94ddc751a4496 to your computer and use it in GitHub Desktop.
Save harshildarji/956963430ea49a305af94ddc751a4496 to your computer and use it in GitHub Desktop.
Generate true Reber grammar sequences.
# This Python script can be used to generate true Reber grammar sequences.
# To generate false Reber grammar sequences, just change tuple values in 'traversal' at line 8.
import numpy as np
chars = 'BTSXPVE'
traversal = [[('T', 'P'), (1, 4)], [('S', 'X'), (1, 2)], [('S', 'X'), (3, 4)], [('E'), (-1,)], [('V', 'T'), (5, 4)], [('V', 'P'), (3, 2)]]
def generate_seq(min_length):
while True:
seq = ['B']
node = 0
while node is not -1:
trans = traversal[node]
index = np.random.randint(0, len(trans[0]))
seq.append(trans[0][index])
node = trans[1][index]
if len(seq) > min_length:
return ''.join(seq)
def check_seq(seq):
seq = list(seq.upper())
if seq[0] is not 'B':
return False
node = 0
for s in seq[1:]:
trans = traversal[node]
try:
index = trans[0].index(s)
node = trans[1][index]
except ValueError:
return False
return True
def to_one_hot(seq):
seq = list(seq)
in_seq = []
for c in seq:
encoded = np.zeros(7)
encoded[chars.find(c)] = 1.
in_seq.append(encoded)
out_seq = in_seq[1:]
in_seq = in_seq[0:-1]
return in_seq, out_seq
def to_string(seq):
reber_string = ''
for s in seq:
index = np.where(s==1.)[0][0]
reber_string += chars[index]
return reber_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment