Ejemplo n.º 1
0
def test_serial_to_base_game(players, facilities, required):
    """Test that reading a congestion game as a base game works"""
    cgame = congestion.gen_congestion_game(players, facilities, required)
    serial1 = cgame.gen_serializer()
    base1 = rsgame.BaseGame(cgame)
    base2, serial2 = gameio.read_base_game(cgame.to_json(serial1))
    assert base1 == base2
    assert serial1 == serial2
Ejemplo n.º 2
0
def main(args):
    data = json.load(args.input)
    if args.regret is not None:
        game, serial = gameio.read_base_game(json.load(args.regret[0]))
        mix = serial.from_prof_json(json.load(args.regret[1]))
        devs = load_devs(game, serial, data)
        expect = game.role_reduce(devs * mix)
        result = bootstrap.sample_regret(game, expect, devs, args.num_bootstraps, args.percentiles)
        if args.mean:
            mdevs = devs.mean(0)
            mexpect = game.role_reduce(mdevs * mix, keepdims=True)
            mean = np.max(mdevs - mexpect)

    elif args.dev_surplus is not None:
        game, serial = gameio.read_base_game(json.load(args.dev_surplus[0]))
        mix = serial.from_prof_json(json.load(args.dev_surplus[1]))
        devs = load_devs(game, serial, data)
        surpluses = np.sum(devs * mix * game.role_repeat(game.num_players), 1)
        result = bootstrap.mean(surpluses, args.num_bootstraps, args.percentiles)
        if args.mean:
            mean = surpluses.mean()

    else:
        data = np.asarray(data, float)
        result = bootstrap.mean(data, args.num_bootstraps, args.percentiles)
        if args.mean:
            mean = data.mean()

    if args.percentiles is None:
        args.percentiles = np.linspace(0, 100, args.num_bootstraps)
    jresult = {str(p).rstrip("0").rstrip("."): v.item() for p, v in zip(args.percentiles, result)}
    if args.mean:
        jresult["mean"] = mean

    json.dump(jresult, args.output)
    args.output.write("\n")
Ejemplo n.º 3
0
def test_base_game_from_json(json_):
    gameio.read_base_game(json_)
Ejemplo n.º 4
0
def test_empty_games_identical():
    game1, serial1 = gameio.read_base_game(EMPTY_GAME_JSON_1)
    game2, serial2 = gameio.read_base_game(EMPTY_GAME_JSON_2)
    assert game1 == game2
    assert serial1 == serial2
Ejemplo n.º 5
0
def main():
    """Main function, declared so it doesn't have global scope"""
    # Parse arguments
    args = _parser.parse_args()
    if args.auth_string is None:
        if path.isfile(args.auth_file):
            with open(args.auth_file) as auth_file:
                args.auth_string = auth_file.read().strip()
        else:
            sys.stderr.write(textwrap.fill((
                'This script needs an authorization token to access EGTA '
                'Online. By default, this script looks for file with your '
                'authorization token at "{}". See `egta --help` for other '
                'ways to specify your authorization '
                'token.').format(_def_auth)))
            sys.stderr.write('\n')
            sys.exit(1)

    # Create logger
    log = logging.getLogger(__name__)
    log.setLevel(max(40 - args.verbose * 10, 1))  # 0 is no logging
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(logging.Formatter(
        '%(asctime)s ({gid:d}) %(message)s'.format(gid=args.game)))
    log.addHandler(handler)

    # Email Logging
    if args.recipient:
        email_subject = 'EGTA Online Quiesce Status for Game {gid:d}'.format(
            gid=args.game)
        smtp_host = 'localhost'

        # We need to do this to match the from address to the local host name
        # otherwise, email logging will not work. This seems to vary somewhat
        # by machine
        server = smtplib.SMTP(smtp_host)
        smtp_fromaddr = 'EGTA Online <egta_online@{host}>'.format(
            host=server.local_hostname)
        server.quit()  # dummy server is now useless

        email_handler = handlers.SMTPHandler(smtp_host, smtp_fromaddr,
                                             args.recipient, email_subject)
        email_handler.setLevel(40 - args.email_verbosity * 10)
        log.addHandler(email_handler)

    # Fetch info from egta online
    egta_api = api.EgtaOnline(args.auth_string,
                              logLevel=(0 if args.verbose < 5 else 3))
    gamej = egta_api.game(id=args.game).get_info('summary')
    try:
        game, serial = gameio.read_base_game(gamej)
    except TypeError as e:
        log.error('Caught exception trying to read the initial game, this is '
                  'most likely caused by a game without roles specified: (%s) '
                  '%s\nWith traceback:\n%s\n',
                  e.__class__.__name__, e, traceback.format_exc())
        raise e
    sim = utils.only(s for s in egta_api.get_simulators()
                     if '{name}-{version}'.format(**s)
                     == gamej.simulator_fullname)

    if args.dpr is not None:
        args.dpr = serial.from_role_json(
            dict(zip(args.dpr[::2], map(int, args.dpr[1::2]))))

    try:
        quiesce(sim, game, serial, gamej.name, dict(gamej.configuration),
                args.dpr, log, profiles=gamej.profiles, all_devs=not
                args.role_devs, max_profiles=args.max_profiles,
                max_subgame_size=args.max_subgame_size,
                sleep_time=args.sleep_time,
                required_equilibria=args.num_equilibria,
                regret_thresh=args.regret_threshold, reschedule_limit=10,
                process_memory=args.memory,
                observation_time=args.observation_time,
                observation_increment=args.observation_increment,
                nodes=args.nodes)

    except Exception as e:
        # Other exception, notify, but don't deactivate
        log.error('Caught exception: (%s) %s\nWith traceback:\n%s\n',
                  e.__class__.__name__, e, traceback.format_exc())
        raise e

    finally:
        # Make sure to clean up
        egta_api.close()
Ejemplo n.º 6
0
def test_json_copy_base_game(players, strategies):
    game1 = rsgame.BaseGame(players, strategies)
    serial = gamegen.game_serializer(game1)
    game2, _ = gameio.read_base_game(game1.to_json(serial))
    assert game1 == game2