git @ Cat's Eye Technologies Samovar / scenario-goals bin / samovar
scenario-goals

Tree @scenario-goals (Download .tar.gz)

samovar @scenario-goalsraw · history · blame

#!/usr/bin/env python
# encoding: UTF-8

"""\
samovar {option} input.samovar

Driver script for Samovar assertion-retraction engine.
"""

from os.path import realpath, dirname, join
import sys

sys.path.insert(0, join(dirname(realpath(sys.argv[0])), '..', 'src'))

from argparse import ArgumentParser
import codecs
import json
import random

from samovar.parser import Parser
from samovar.generator import Generator


def main(args):
    argparser = ArgumentParser()

    argparser.add_argument('input_files', nargs='+', metavar='FILENAME', type=str,
        help='Source files containing the scenario descriptions'
    )
    argparser.add_argument("--debug", action="store_true",
        help="Show state before and after each move"
    )
    argparser.add_argument("--dump-ast",
                         action="store_true",
                         help="Just show the AST and stop")
    argparser.add_argument("--min-events",
                         type=int, default=1,
                         help="Generate at least this many events for each scenario")
    argparser.add_argument("--output-type",
                         choices=['naive-text', 'events-json', 'scenarios-json'],
                         default='naive-text',
                         help="Specify what to output and in what format")
    argparser.add_argument("--seed",
                         type=int, default=None,
                         help="Set random seed (to select moves deterministically)")
    argparser.add_argument("--profile",
                         action="store_true",
                         help="Run cProfile on standard 'heavy load' case and exit")

    options = argparser.parse_args(args)

    if options.profile:
        import cProfile
        def generate_fifty_thousand_words():
            with codecs.open('eg/chairs.samovar', 'r', encoding='UTF-8') as f:
                text = f.read()
            p = Parser(text)
            ast = p.world()
            random.seed(0)
            g = Generator(ast)
            g.generate_words(50000)
        cProfile.run('generate_fifty_thousand_words()')
        sys.exit(0)

    text = ''
    for arg in options.input_files:
        with codecs.open(arg, 'r', encoding='UTF-8') as f:
            text += f.read()

    p = Parser(text)
    ast = p.world()
    if options.dump_ast:
        print ast
        sys.exit(0)
    if options.seed is not None:
        random.seed(options.seed)

    event_buckets = []
    for scenario in ast.scenarios:
        if scenario.goal is None:
            continue
        g = Generator(ast, scenario, debug=options.debug)
        events = g.generate_events(options.min_events)
        event_buckets.append(events)

    if options.output_type == 'naive-text':
        for b in event_buckets:
            for e in b:
                sys.stdout.write("%s\n" % e)
            sys.stdout.write("\n")
    elif options.output_type == 'events-json':
        def jsonify_bucket(b):
            return [e.to_json() for e in b]
        jsonified_buckets = [jsonify_bucket(b) for b in event_buckets]
        sys.stdout.write(json.dumps(jsonified_buckets, indent=4, sort_keys=True))
    elif options.output_type == 'scenarios-json':
        raise NotImplementedError
    else:
        raise NotImplementedError


if __name__ == '__main__':
    main(sys.argv[1:])