Fraser-Greenlee commited on
Commit
9f271d1
·
1 Parent(s): c6f8ae3

mv to fail

Browse files
make_variations_basic/__init__.py DELETED
File without changes
make_variations_basic/main.py DELETED
@@ -1,212 +0,0 @@
1
- # did 2563140/9000000
2
- import gzip
3
- import json
4
- from typing import List
5
- from tqdm import tqdm
6
- from random import randint, random, sample
7
- from astpretty import pprint
8
- from copy import deepcopy
9
- from string import ascii_letters
10
- import ast
11
-
12
-
13
- from utils import TimeoutError, timeout
14
-
15
-
16
- def write_rows(rows):
17
- rows = [json.dumps(r) for r in rows]
18
- with open('data.10_simple_variations.jsonl', 'a') as f:
19
- f.writelines('\n'.join(rows) + '\n')
20
-
21
-
22
- def write_rows_compressed(rows):
23
- rows = [json.dumps(r) for r in rows]
24
- with gzip.open('data.10_simple_variations.jsonl.gz', 'wb') as f:
25
- f.write('\n'.join(rows).encode() + b'\n')
26
-
27
-
28
- class AlternativeList(ast.NodeTransformer):
29
- def __init__(self):
30
- self.n_changes = 0
31
- super().__init__()
32
-
33
- def visit_List(self, node: List):
34
- code = ast.unparse(node)
35
- try:
36
- list_val = eval(code)
37
- except Exception:
38
- return node
39
-
40
- for _ in range(randint(0, 3)):
41
- list_val.append(randint(-999, 999))
42
-
43
- if not list_val:
44
- list_val.append(randint(-999, 999))
45
-
46
- list_val = sample(list_val, randint(1, len(list_val)))
47
-
48
- self.n_changes += 1
49
- return ast.parse(str(list_val)).body[0].value
50
-
51
-
52
- class AlternativeConstant(ast.NodeTransformer):
53
- def __init__(self):
54
- self.n_changes = 0
55
- super().__init__()
56
-
57
- def visit_Constant(self, node):
58
- '''
59
- Switch constant values to simple variations
60
- '''
61
- if type(node.value) is int:
62
- if randint(0, 1) == 1:
63
- node.value = randint(-9, 9)
64
- else:
65
- node.value = randint(-999, 999)
66
- elif type(node.value) is str:
67
- if randint(0, 1) == 1 and node.value:
68
- if node.value:
69
- node.value = ''.join(sample(node.value, randint(1, len(node.value))))
70
- else:
71
- self.n_changes -= 1
72
- else:
73
- node.value = ''.join(sample(ascii_letters, randint(1, 4)))
74
- elif type(node.value) is float:
75
- if randint(0, 1) == 1:
76
- node.value = random()
77
- else:
78
- node.value = random() * randint(-999, 999)
79
- elif type(node.value) is bool:
80
- node.value = bool(randint(0, 1))
81
- else:
82
- self.n_changes -= 1
83
- self.n_changes += 1
84
- return super().visit_Constant(node)
85
-
86
-
87
- class AlternativeNames(ast.NodeTransformer):
88
-
89
- def visit_Name(self, node):
90
- return ast.copy_location(ast.Subscript(
91
- value=ast.Name(id='data', ctx=ast.Load()),
92
- slice=ast.Index(value=ast.Str(s=node.id)),
93
- ctx=node.ctx
94
- ), node)
95
-
96
-
97
- def state_dict_to_str(state):
98
- vals = []
99
- for k, v in state.items():
100
- vals.append(
101
- f'{k} = {v}'
102
- )
103
- vals = sorted(vals)
104
- return ';'.join(vals)
105
-
106
-
107
- @timeout(seconds=3)
108
- def trace_code(start_state: str, code: str):
109
- state = {}
110
- try:
111
- exec(start_state, {}, state)
112
- except Exception:
113
- return
114
- start_state = dict(state)
115
- try:
116
- exec(code, {}, state)
117
- except Exception:
118
- return
119
- return state_dict_to_str(start_state), code, state_dict_to_str(state)
120
-
121
-
122
- def make_alternative_rows(start, code):
123
- variations = {}
124
- n_tries = 0
125
- state_root = ast.parse(start)
126
-
127
- while len(variations) < 10 and n_tries < 20:
128
-
129
- alt_state_root = None
130
-
131
- node_transformer = AlternativeList()
132
- try:
133
- alt_state_root = node_transformer.visit(deepcopy(state_root))
134
- except Exception:
135
- pass
136
-
137
- if node_transformer.n_changes < 1:
138
- node_transformer = AlternativeConstant()
139
- try:
140
- alt_state_root = node_transformer.visit(deepcopy(alt_state_root))
141
- except Exception:
142
- pass
143
- if node_transformer.n_changes < 1:
144
- n_tries += 10
145
-
146
- if alt_state_root:
147
- alt_start = ast.unparse(alt_state_root)
148
- try:
149
- alt_start_code_end = trace_code(alt_start, code)
150
- if alt_start_code_end:
151
- variations[alt_start] = alt_start_code_end
152
- except TimeoutError:
153
- pass
154
-
155
- n_tries += 1
156
-
157
- # TODO change the names (keep alphabetical order)
158
- '''
159
- get number of vals in start states (N)
160
- get N random lowercase letters in alphabetical order
161
- parse start state and shuffle the expr.body
162
- make name map old->new using new characters
163
- use visitor with name map to swap variable names using map
164
- do this for start, code, end seperately
165
- '''
166
- return [
167
- {'start': st, 'code': cd, 'end': en} for st, cd, en in variations.values()
168
- ]
169
-
170
-
171
- STATS = {
172
- 'alt_count': 0,
173
- 'num_rows': 0
174
- }
175
-
176
-
177
- with open('new_all_states.txt', 'r') as f:
178
- rows = []
179
- prev_lines = []
180
- for i, line in tqdm(enumerate(f), total=9_000_000):
181
- line = line.strip()
182
-
183
- if line[-1] != ';':
184
- prev_lines.append(line)
185
- continue
186
- elif prev_lines:
187
- line = '\n'.join(prev_lines) + '\n' + line
188
- prev_lines = []
189
-
190
- start, code_end = line.split('; code: ')
191
- start = start.removeprefix('state: ')
192
- code, end = code_end.split('; output: ')
193
- end = end.removesuffix(';')
194
-
195
- rows.append({
196
- 'start': start, 'code': code, 'end': end
197
- })
198
- alt_rows = make_alternative_rows(start, code)
199
- rows += alt_rows
200
-
201
- STATS['alt_count'] += len(alt_rows)
202
- STATS['num_rows'] += 1
203
-
204
- if len(rows) > 1_000:
205
- write_rows_compressed(rows)
206
- rows = []
207
-
208
- write_rows_compressed(rows)
209
-
210
-
211
- print(STATS)
212
- print(STATS['alt_count'] / STATS['num_rows'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
make_variations_basic/utils.py DELETED
@@ -1,26 +0,0 @@
1
- import errno
2
- import os
3
- import signal
4
- import functools
5
-
6
- class TimeoutError(Exception):
7
- pass
8
-
9
- def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
10
- def decorator(func):
11
- def _handle_timeout(signum, frame):
12
- raise TimeoutError(error_message)
13
-
14
- @functools.wraps(func)
15
- def wrapper(*args, **kwargs):
16
- signal.signal(signal.SIGALRM, _handle_timeout)
17
- signal.alarm(seconds)
18
- try:
19
- result = func(*args, **kwargs)
20
- finally:
21
- signal.alarm(0)
22
- return result
23
-
24
- return wrapper
25
-
26
- return decorator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
visualise/__init__.py DELETED
File without changes
visualise/flatten.py DELETED
@@ -1,37 +0,0 @@
1
- '''
2
- - parse the AST for every line of code
3
- - add this to a graph of all possibly trees with frequency counts
4
- - plot this tree
5
- '''
6
- import json
7
-
8
-
9
- with open('visualise/trie.json', 'r') as f:
10
- trie = json.load(f)
11
-
12
-
13
- def flatten_children(root):
14
- children = []
15
- for name, vals in root.items():
16
- if name[0] == ' ':
17
- continue
18
- rr = {'name': name, 'value': vals[' count']}
19
- rr['children'] = flatten_children(vals)
20
- if not rr['children']:
21
- del rr['children']
22
- children.append(rr)
23
-
24
- tot = sum(child['value'] for child in children)
25
- for child in children:
26
- child['value'] = child['value'] / tot
27
-
28
- return children
29
-
30
-
31
- trie = {
32
- "name": "Module",
33
- "children": flatten_children(trie)
34
- }
35
-
36
- with open('visualise/trie.flat.json', 'w') as f:
37
- f.write(json.dumps(trie))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
visualise/main.py DELETED
@@ -1,37 +0,0 @@
1
- '''
2
- - parse the AST for every line of code
3
- - add this to a graph of all possibly trees with frequency counts
4
- - plot this tree
5
- '''
6
- import ast
7
- import json
8
- from tqdm import tqdm
9
-
10
-
11
- trie = {}
12
-
13
-
14
- class Reader:
15
- def __init__(self, trie, code):
16
- self.trie = trie
17
- self.root = ast.parse(code)
18
-
19
- def run(self):
20
- return self.add_code(self.trie, self.root)
21
-
22
- def add_code(self, cursor, node):
23
- for child in ast.iter_child_nodes(node):
24
- name = type(child).__name__
25
- cursor[name] = cursor.get(name, {' count': 0})
26
- cursor[name][' count'] += 1
27
- cursor[name] = self.add_code(cursor[name], child)
28
- return cursor
29
-
30
-
31
- with open('data.jsonl', 'r', encoding="utf-8") as f:
32
- for id_, line in tqdm(enumerate(f), total=8968897):
33
- trie = Reader(trie, json.loads(line)['code']).run()
34
-
35
-
36
- with open('visualise/trie.json', 'w') as f:
37
- f.write(json.dumps(trie))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
visualise/trie.flat.json DELETED
The diff for this file is too large to render. See raw diff
 
visualise/trie.json DELETED
The diff for this file is too large to render. See raw diff