bench.py 7.41 KB
Newer Older
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python3

import argparse
import os
import subprocess
import json
import numpy as np
import scipy.stats as st

samples = 5


13
14
15
def coalg_file(states, monoid, symbols, zero_frequency, different_values, i):
    return "bench/wta_%s_%s_%s_%s_%s_%d" % (monoid, symbols, zero_frequency,
                                         different_values, states, i)
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
16
17
18
19
20
21
22
23


def generate(args):
    generator = args.generator
    states = args.states
    monoid = args.monoid
    symbols = args.symbols
    zero_frequency = args.zero_frequency
24
    different_values = args.different_values
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
25
26
27
28

    os.makedirs("bench", exist_ok=True)

    for i in range(0, samples):
29
        f = coalg_file(states, monoid, symbols, zero_frequency, different_values,
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
30
31
32
33
34
35
36
                       i) + ".coalgebra"

        if os.path.exists(f):
            continue

        cmd = [
            generator, "--states", states, "--monoid", monoid, "--symbols",
37
38
            symbols, "--zero-frequency", zero_frequency,
            "--different-values", different_values
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
39
40
41
42
43
44
45
46
47
48
        ]
        subprocess.run(cmd, stdout=open(f, "w+"))


def run_one(args, i):
    copar = args.copar
    states = args.states
    monoid = args.monoid
    symbols = args.symbols
    zero_frequency = args.zero_frequency
49
    different_values = args.different_values
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
50

51
    f = coalg_file(states, monoid, symbols, zero_frequency, different_values, i) + ".coalgebra"
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65

    copar_args = [copar, 'refine', '--stats-json', f]

    out = subprocess.run(
        copar_args,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.PIPE,
        check=True)

    stats = json.loads(out.stderr.decode('utf-8'))

    stats['monoid'] = monoid
    stats['symbols'] = symbols
    stats['zero-freq'] = zero_frequency
66
    stats['mon-values'] = different_values
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
67
68
69
70
71
72
73
74
75
76
77
    stats['i'] = i

    return stats


def run_one_simple(args, i):
    copar = args.copar
    states = args.states
    monoid = args.monoid
    symbols = args.symbols
    zero_frequency = args.zero_frequency
78
    different_values= args.different_values
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
79

80
    f = coalg_file(states, monoid, symbols, zero_frequency, different_values, i) + ".coalgebra"
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
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

    copar_args = [copar, 'refine', f]

    subprocess.run(
        copar_args,
        stdout=subprocess.DEVNULL,
        check=True)


def confidence(vals):
    """Compute the 95% confidence intervall (CI) for the mean with the student
distribution.

Returns a tuple of (mean, lower, upper), where lower and upper are the bounds
of the CI"""

    # For a larger sample size (> 30), we could also use the normal
    # distribution.
    #
    # This code is taken from
    # https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data/34474255#34474255

    mean = np.mean(vals)
    ci = st.t.interval(
        0.95, len(vals) - 1, loc=np.mean(vals), scale=st.sem(vals))

    return (mean, ci[0], ci[1])


def stddev(vals):
    """Compute the mean and standard deviation intervall on a sample.

This uses the corrected sample standard deviation."""

    # see also:
    # https://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation
    mean = np.mean(vals)
    std = np.std(vals, ddof=1)

    return (mean, std)


def print_row(d, header, stddev):
    keys = [
        'i', 'states', 'edges', 'initial-partition-size',
        'final-partition-size', 'explicit-final-partition-size',
        'size1-skipped'
    ]

    for k in [
            'overall-duration', 'parse-duration', 'algorithm-duration',
            'initialize-duration', 'refine-duration'
    ]:
        keys.append(k)
        if stddev:
            keys.append(k + '-stddev')

    values = [d[k] for k in keys]

    if header:
        print('\t'.join(keys))
    else:
        print('\t'.join(str(x) for x in values))


def run(args):
    results = [run_one(args, i) for i in range(0, samples)]

    def confidencekey(vals, k):
        return confidence(list(float(x[k]) for x in vals))

    def stddevkey(vals, k):
        return stddev(list(float(x[k]) for x in vals))

    combined = results[0].copy()
    combined['i'] = samples

    for k in [
            'overall-duration', 'parse-duration', 'initialize-duration',
            'refine-duration', 'algorithm-duration'
    ]:
        ci = stddevkey(results, k)
        combined[k] = str(ci[0])
        combined[k + '-stddev'] = str(ci[1])

    if args.indiv:
        if args.header:
            print_row(combined, True, stddev=False)
        for res in results:
            print_row(res, False, stddev=False)
    else:
        if args.header:
            print_row(combined, True, stddev=args.stddev)
        print_row(combined, False, stddev=args.stddev)


def test(args, states):
    print("Trying %d..." % states)

    args.states = str(states)
    generate(args)

    for i in range(0, samples):
        try:
            run_one_simple(args, i)
        except subprocess.CalledProcessError:
            return False

    return True


def find_bad(args, good):
    states = good*2

    if test(args, states):
        return find_bad(args, states)
    else:
        return (good, states)


def bisect_states(args):
    states = args.start_states

    good = args.good or 0
    bad = args.bad

    if bad is None:
        if good and states < good:
            states = good+1

        if test(args, states):
            (good, bad) = find_bad(args, states)
        else:
            bad = states

    while good+1 < bad:
        states = good + (bad-good)//2
        if test(args, states):
            good = states
        else:
            bad = states

    print("First bad state count: %d" % bad)


def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(required=True)

    gen_parser = subparsers.add_parser('generate')
    gen_parser.add_argument('generator')
    gen_parser.add_argument('--states', required=True)
    gen_parser.add_argument('--monoid', required=True)
    gen_parser.add_argument('--symbols', required=True)
    gen_parser.add_argument('--zero-frequency', required=True)
236
    gen_parser.add_argument('--different-values', required=True)
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
237
238
239
240
241
242
243
244
    gen_parser.set_defaults(func=generate)

    run_parser = subparsers.add_parser('run')
    run_parser.add_argument('copar')
    run_parser.add_argument('--states', required=True)
    run_parser.add_argument('--monoid', required=True)
    run_parser.add_argument('--symbols', required=True)
    run_parser.add_argument('--zero-frequency', required=True)
245
    run_parser.add_argument('--different-values', required=True)
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    run_parser.add_argument(
        '--stddev', action='store_true', help="report stddev for timings")
    run_parser.add_argument(
        '--indiv', action='store_true', help="report individual samples")
    run_parser.add_argument(
        '--header', action='store_true', help="Print header row for table")
    run_parser.set_defaults(func=run)

    bisect_parser = subparsers.add_parser('bisect')
    bisect_parser.add_argument('generator')
    bisect_parser.add_argument('copar')
    bisect_parser.add_argument('--monoid', required=True)
    bisect_parser.add_argument('--symbols', required=True)
    bisect_parser.add_argument('--zero-frequency', required=True)
260
    bisect_parser.add_argument('--different-values', required=True)
Hans-Peter Deifel's avatar
Hans-Peter Deifel committed
261
262
263
264
265
266
267
268
269
270
271
272
    bisect_parser.add_argument('--start-states', type=int, default=50)
    bisect_parser.add_argument('--good', type=int)
    bisect_parser.add_argument('--bad', type=int)

    bisect_parser.set_defaults(func=bisect_states)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()