File size: 5,761 Bytes
c6f8ae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# did 2563140/9000000
import gzip
import json
from typing import List
from tqdm import tqdm
from random import randint, random, sample
from astpretty import pprint
from copy import deepcopy
from string import ascii_letters
import ast


from utils import TimeoutError, timeout


def write_rows(rows):
    rows = [json.dumps(r) for r in rows]
    with open('data.10_simple_variations.jsonl', 'a') as f:
        f.writelines('\n'.join(rows) + '\n')


def write_rows_compressed(rows):
    rows = [json.dumps(r) for r in rows]
    with gzip.open('data.10_simple_variations.jsonl.gz', 'wb') as f:
        f.write('\n'.join(rows).encode() + b'\n')


class AlternativeList(ast.NodeTransformer):
    def __init__(self):
        self.n_changes = 0
        super().__init__()

    def visit_List(self, node: List):
        code = ast.unparse(node)
        try:
            list_val = eval(code)
        except Exception:
            return node

        for _ in range(randint(0, 3)):
            list_val.append(randint(-999, 999))

        if not list_val:
            list_val.append(randint(-999, 999))

        list_val = sample(list_val, randint(1, len(list_val)))

        self.n_changes += 1
        return ast.parse(str(list_val)).body[0].value


class AlternativeConstant(ast.NodeTransformer):
    def __init__(self):
        self.n_changes = 0
        super().__init__()

    def visit_Constant(self, node):
        '''
            Switch constant values to simple variations
        '''
        if type(node.value) is int:
            if randint(0, 1) == 1:
                node.value = randint(-9, 9)
            else:
                node.value = randint(-999, 999)
        elif type(node.value) is str:
            if randint(0, 1) == 1 and node.value:
                if node.value:
                    node.value = ''.join(sample(node.value, randint(1, len(node.value))))
                else:
                    self.n_changes -= 1
            else:
                node.value = ''.join(sample(ascii_letters, randint(1, 4)))
        elif type(node.value) is float:
            if randint(0, 1) == 1:
                node.value = random()
            else:
                node.value = random() * randint(-999, 999)
        elif type(node.value) is bool:
            node.value = bool(randint(0, 1))
        else:
            self.n_changes -= 1
        self.n_changes += 1
        return super().visit_Constant(node)


class AlternativeNames(ast.NodeTransformer):

    def visit_Name(self, node):
        return ast.copy_location(ast.Subscript(
            value=ast.Name(id='data', ctx=ast.Load()),
            slice=ast.Index(value=ast.Str(s=node.id)),
            ctx=node.ctx
        ), node)


def state_dict_to_str(state):
    vals = []
    for k, v in state.items():
        vals.append(
            f'{k} = {v}'
        )
    vals = sorted(vals)
    return ';'.join(vals)


@timeout(seconds=3)
def trace_code(start_state: str, code: str):
    state = {}
    try:
        exec(start_state, {}, state)
    except Exception:
        return
    start_state = dict(state)
    try:
        exec(code, {}, state)
    except Exception:
        return
    return state_dict_to_str(start_state), code, state_dict_to_str(state)


def make_alternative_rows(start, code):
    variations = {}
    n_tries = 0
    state_root = ast.parse(start)

    while len(variations) < 10 and n_tries < 20:

        alt_state_root = None

        node_transformer = AlternativeList()
        try:
            alt_state_root = node_transformer.visit(deepcopy(state_root))
        except Exception:
            pass

        if node_transformer.n_changes < 1:
            node_transformer = AlternativeConstant()
            try:
                alt_state_root = node_transformer.visit(deepcopy(alt_state_root))
            except Exception:
                pass
            if node_transformer.n_changes < 1:
                n_tries += 10

        if alt_state_root:
            alt_start = ast.unparse(alt_state_root)
            try:
                alt_start_code_end = trace_code(alt_start, code)
                if alt_start_code_end:
                    variations[alt_start] = alt_start_code_end
            except TimeoutError:
                pass

        n_tries += 1

    # TODO change the names (keep alphabetical order)
    '''
    get number of vals in start states (N)
    get N random lowercase letters in alphabetical order
    parse start state and shuffle the expr.body
    make name map old->new using new characters
    use visitor with name map to swap variable names using map
        do this for start, code, end seperately
    '''
    return [
        {'start': st, 'code': cd, 'end': en} for st, cd, en in variations.values()
    ]


STATS = {
    'alt_count': 0,
    'num_rows': 0
}


with open('new_all_states.txt', 'r') as f:
    rows = []
    prev_lines = []
    for i, line in tqdm(enumerate(f), total=9_000_000):
        line = line.strip()

        if line[-1] != ';':
            prev_lines.append(line)
            continue
        elif prev_lines:
            line = '\n'.join(prev_lines) + '\n' + line
            prev_lines = []

        start, code_end = line.split('; code: ')
        start = start.removeprefix('state: ')
        code, end = code_end.split('; output: ')
        end = end.removesuffix(';')

        rows.append({
            'start': start, 'code': code, 'end': end
        })
        alt_rows = make_alternative_rows(start, code)
        rows += alt_rows

        STATS['alt_count'] += len(alt_rows)
        STATS['num_rows'] += 1

        if len(rows) > 1_000:
            write_rows_compressed(rows)
            rows = []

write_rows_compressed(rows)


print(STATS)
print(STATS['alt_count'] / STATS['num_rows'])