summaryrefslogtreecommitdiff
path: root/monkey/edits.py
blob: 58843f648696967838d8717faa30af92d1f2da18 (plain)
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
#!/usr/bin/python3

import collections

from .action import expand, parse
from .graph import Node
from .prolog.util import rename_vars, stringify, tokenize
from .util import get_line

# A line edit is a contiguous sequences of actions within a single line. This
# function takes a sequence of actions and builds a directed acyclic graph
# where each edit represents one line edit and each node represents a version
# of some line. The function returns a list of nodes (first element is the
# root), and sets of submissions (program versions tested by the user) and
# queries in this attempt.
def edit_graph(actions, debug=False):
    # Return values.
    nodes = [Node([0, 0, ()])]  # Node data: rank (Y), line no. (X), and tokens.
    submissions = set()         # Program versions at 'test' actions.
    queries = set()             # Queries run by the student.

    # State variables.
    leaves = {0: nodes[0]}  # Current leaf node for each line.
    rank = 1                # Rank (order / y-position) for the next node.
    code_next = ''          # Program code after applying the current action.

    # Ensure there is a separate action for each inserted/removed character.
    expand(actions)
    for action_id, action in enumerate(actions):
        code = code_next
        code_next = action.apply(code)

        if action.type == 'test':
            submissions.add(code)

        elif action.type == 'solve' or action.type == 'solve_all':
            queries.add(action.query)

        elif action.type == 'insert' or action.type == 'remove':
            # Number of the changed line.
            line = code[:action.offset].count('\n')
            # Current leaf node for this line.
            parent = leaves[line]
            # Tokens in this line after applying [action].
            tokens_next = tuple(tokenize(get_line(code_next, line)))

            # If a new node is inserted, clone each leaf into the next rank.
            # This makes it easier to print the graph for graphviz; when
            # analyzing the graph, duplicate nodes without siblings should be
            # ignored.
            new_leaves = {}

            if action.text == '\n':
                if action.type == 'insert':
                    tokens_next_right = tuple(tokenize(get_line(code_next, line+1)))

                    child_left = Node([rank, line, tokens_next])
                    parent.add_out(child_left)

                    child_right = Node([rank, line+1, tokens_next_right])
                    parent.add_out(child_right)

                    # Create new leaf nodes.
                    for i, leaf in leaves.items():
                        if i < line:
                            new_leaves[i] = Node([rank, i, leaf.data[2]])
                            leaf.add_out(new_leaves[i])
                        elif i > line:
                            new_leaves[i+1] = Node([rank, i+1, leaf.data[2]])
                            leaf.add_out(new_leaves[i+1])
                    new_leaves[line] = child_left
                    new_leaves[line+1] = child_right

                elif action.type == 'remove':
                    parent_right = leaves[line+1]

                    child = Node([rank, line, tokens_next])
                    parent_right.add_out(child)
                    parent.add_out(child)

                    # Create new leaf nodes.
                    for i, leaf in leaves.items():
                        if i < line:
                            new_leaves[i] = Node([rank, i, leaf.data[2]])
                            leaf.add_out(new_leaves[i])
                        elif i > line+1:
                            new_leaves[i-1] = Node([rank, i-1, leaf.data[2]])
                            leaf.add_out(new_leaves[i-1])
                    new_leaves[line] = child
            else:
                # Skip the node if the next action is insert/remove (except \n)
                # on the same line.
                if action_id < len(actions)-1:
                    action_next = actions[action_id+1]
                    if action_next.type in ('insert', 'remove'):
                        line_next = code_next[:action_next.offset].count('\n')
                        if action_next.text != '\n' and line == line_next:
                            continue

                # Skip the node if it is the same as the parent.
                if tokens_next == parent.data[2]:
                    continue

                child = Node([rank, line, tokens_next])
                parent.add_out(child)

                # Create new leaf nodes.
                for i, leaf in leaves.items():
                    if i != line:
                        new_leaves[i] = Node([rank, i, leaf.data[2]])
                        leaf.add_out(new_leaves[i])
                new_leaves[line] = child

            leaves = new_leaves
            nodes += leaves.values()
            rank += 1

    return nodes, submissions, queries

# Return all interesting edit paths in the edit graph rooted at [root].
def get_paths(root, path=tuple(), done=None):
    if done is None:
        done = set()

    cur_path = list(path)
    if len(path) == 0 or path[-1] != root.data[2]:
        cur_path.append(root.data[2])

    # leaf node
    if len(root.eout) == 0:
        yield tuple(cur_path)
    # empty node
    elif len(path) > 1 and len(root.data[2]) == 0:
        yield tuple(cur_path)

    if len(root.data[2]) > 0:
        new_path = cur_path
    else:
        new_path = [root.data[2]]
        done.add(root)

    for node in root.eout:
        if node not in done:
            yield from get_paths(node, tuple(new_path), done)

# Build an edit graph for each trace and find "meaningful" (to be defined)
# edits. Return a dictionary of edits and their frequencies, and also
# submissions and queries in [traces].
def get_edits_from_traces(traces):
    # Helper function to remove trailing punctuation from lines. This is a
    # rather ugly performance-boosting hack.
    def remove_punct(line):
        if line and line[-1].type in ('COMMA', 'PERIOD', 'SEMI', 'FROM'):
            return line[:-1]
        return line

    # Return values: counts for observed edits, lines, submissions and queries.
    edits = collections.Counter()
    lines = collections.Counter()
    submissions = collections.Counter()
    queries = collections.Counter()

    for trace in traces:
        try:
            actions = parse(trace)
        except:
            continue
        nodes, trace_submissions, trace_queries = edit_graph(actions)

        # Update the submissions/queries counters; rename variables first to
        # remove trivial differences.
        for submission in trace_submissions:
            tokens = tokenize(submission)
            rename_vars(tokens)
            code = stringify(tokens)
            submissions[code] += 1

        for query in trace_queries:
            tokens = tokenize(query)
            rename_vars(tokens)
            code = stringify(tokens)
            queries[code] += 1

        # Get edits.
        for path in get_paths(nodes[0]):
            for i in range(len(path)):
                start = list(remove_punct(path[i]))
                var_names = rename_vars(start)
                start_t = tuple(start)

                for j in range(len(path[i+1:])):
                    end = list(remove_punct(path[i+1+j]))
                    rename_vars(end, var_names)
                    end_t = tuple(end)

                    if start_t != end_t:
                        edit = (start_t, end_t)
                        edits[edit] += 1
                        lines[start_t] += 1

    # Discard rarely occurring edits. XXX only for testing
    singletons = [edit for edit in edits if edits[edit] < 2]
    for edit in singletons:
        lines[edit[0]] -= edits[edit]
        del edits[edit]

    # Get the probability of each edit given its 'before' line.
    for before, after in edits:
        edits[(before, after)] /= lines[before]

    # Normalize line frequencies.
    if len(lines) > 0:
        lines_max = max(lines.values())
        lines = {line: count/lines_max for line, count in lines.items()}

    return edits, lines, submissions, queries

def classify_edits(edits):
    inserts = {}
    removes = {}
    changes = {}
    for (before, after), cost in edits.items():
        if after and not before:
            inserts[after] = cost
        elif before and not after:
            removes[before] = cost
        else:
            changes[(before, after)] = cost
    return inserts, removes, changes

# Simplify an edit graph with given nodes: remove empty leaf nodes and other
# fluff. The function is called recursively until no more changes are done.
def clean_graph(nodes):
    changed = False

    # A
    # | --> A (when B is an empty leaf)
    # B
    for node in nodes:
        if len(node.eout) == 0 and len(node.ein) == 1 and len(node.data[2]) == 0:
            parent = node.ein[0]
            parent.eout.remove(node)
            nodes.remove(node)
            changed = True
            break

    # A
    # | --> A
    # A
    for node in nodes:
        if len(node.ein) == 1:
            parent = node.ein[0]
            if len(parent.eout) == 1 and node.data[2] == parent.data[2]:
                parent.eout = node.eout
                for child in parent.eout:
                    child.ein = [parent if node == node else node for node in child.ein]
                nodes.remove(node)
                changed = True
                break

    # A       A
    # |\      |
    # | C --> |   (when C is empty)
    # |/      |
    # B       B
    for node in nodes:
        if len(node.data[2]) == 0 and len(node.ein) == 1 and len(node.eout) == 1:
            parent = node.ein[0]
            child = node.eout[0]
            if len(parent.eout) == 2 and len(child.ein) == 2:
                parent.eout = [n for n in parent.eout if n != node]
                child.ein = [n for n in child.ein if n != node]
                nodes.remove(node)
                changed = True
                break

    # A
    # |
    # C --> A
    # |
    # A
    for node in nodes:
        if len(node.data[2]) == 0 and len(node.ein) == 1 and len(node.eout) == 1:
            parent = node.ein[0]
            child = node.eout[0]
            if len(parent.eout) == 1 and len(child.ein) == 1 and parent.data[2] == child.data[2]:
                parent.eout = [child]
                child.ein = [parent]
                nodes.remove(node)
                changed = True
                break

    if changed:
        # go again until nothing changes
        clean_graph(nodes)
    else:
        # compact node ranks
        ranks = set([node.data[0] for node in nodes])
        missing = set(range(1,max(ranks)+1)) - ranks

        for node in nodes:
            diff = 0
            for rank in sorted(missing):
                if rank >= node.data[0]:
                    break
                diff += 1
            node.data[0] -= diff

if __name__ == '__main__':
    import os
    import pickle
    import django

    # Load django models.
    os.environ['DJANGO_SETTINGS_MODULE'] = 'webmonkey.settings'
    django.setup()
    from django.contrib.auth.models import User
    from tutor.models import Attempt, Problem

    edits = {}
    lines = {}
    submissions = {}
    queries = {}
    for problem in Problem.objects.all():
        pid = problem.pk
        traces = [a.trace for a in Attempt.objects.filter(problem=problem, done=True)]
        edits[pid], lines[pid], submissions[pid], queries[pid] = get_edits_from_traces(traces)

    pickle.dump((edits, lines, submissions, queries), open('edits.pickle', 'wb'))