Skip to content

Commit

Permalink
Add pre-commit hooks and blacken everything.
Browse files Browse the repository at this point in the history
  • Loading branch information
alecpm committed Jul 31, 2023
1 parent bfdf457 commit 68bc57b
Show file tree
Hide file tree
Showing 22 changed files with 285 additions and 236 deletions.
18 changes: 18 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
repos:

- repo: https://github.com/psf/black
rev: 23.7.0 # update with `pre-commit autoupdate`
hooks:
- id: black
language_version: python3 # Should be a command that runs python3.6+
files: ^(tests|dallinger|dallinger_scripts|demos)/|setup.py

- repo: https://github.com/PyCQA/flake8
rev: '6.0.0'
hooks:
- id: flake8
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black", "--filter-files"]
51 changes: 25 additions & 26 deletions demos/active_learning_demo.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from dallinger.experiments import Griduniverse
from bams.learners import ActiveLearner
from bams.query_strategies import (
# BALD,
HyperCubePool,
RandomStrategy,
)
from bams.query_strategies import HyperCubePool, RandomStrategy # BALD,
from dallinger.experiments import Griduniverse

NDIM = 1
POOL_SIZE = 500
Expand All @@ -18,41 +14,45 @@ def scale_up(threshold, dim):
out = int(dim * threshold)
return out


def scale_down(threshold, dim):
"""Rescale 0 =< output =< 1"""
out = float(dim/threshold) if threshold else 0.0
out = float(dim / threshold) if threshold else 0.0
return out


def oracle(x):
"""Run a GU game by scaling up the features so they can be input into the game.
Then scale them done so the active learner can understand them.
"""
grid_config = {"participants": 1,
"time_per_round": 20.0,
"num_food": 100,
"average_score": 200.0,
}
grid_config = {
"participants": 1,
"time_per_round": 20.0,
"num_food": 100,
"average_score": 200.0,
}
experiment = Griduniverse()
# Scale up
print x[0]
num_food = scale_up(grid_config['num_food'], float(x[0]))
print num_food
print(x[0])
num_food = scale_up(grid_config["num_food"], float(x[0]))
print(num_food)
data = experiment.run(
mode=u'debug',
recruiter=u'bots',
bot_policy=u"AdvantageSeekingBot",
time_per_round = grid_config['time_per_round'],
num_food = num_food,
max_participants=grid_config['participants'],
num_dynos_worker=grid_config['participants'],
webdriver_type=u'chrome',
mode="debug",
recruiter="bots",
bot_policy="AdvantageSeekingBot",
time_per_round=grid_config["time_per_round"],
num_food=num_food,
max_participants=grid_config["participants"],
num_dynos_worker=grid_config["participants"],
webdriver_type="chrome",
)
score = experiment.average_score(data)
print score
print(score)
# Scale back down
results = scale_down(grid_config['average_score'], score)
results = scale_down(grid_config["average_score"], score)
return results


learner = ActiveLearner(
query_strategy=RandomStrategy(pool=HyperCubePool(NDIM, POOL_SIZE)),
budget=BUDGET,
Expand All @@ -67,4 +67,3 @@ def oracle(x):
learner.update(x, y)
print(learner.posteriors)
print(learner.map_model)

48 changes: 26 additions & 22 deletions demos/active_learning_group_size.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from dallinger.experiments import Griduniverse
from bams.learners import ActiveLearner
from bams.query_strategies import (
BALD,
HyperCubePool,
RandomStrategy,
)
from bams.query_strategies import BALD
from dallinger.experiments import Griduniverse

NDIM = 1
POOL_SIZE = 500
Expand All @@ -14,40 +10,45 @@

collected_data = {}


def num_colors(x):
"""x is the fraction of the total players who are on a single team"""
return int(round(1.0 / x))


def closest_valid_x(x):
x = x[0]
x = max(1.0/6.0, x) # 1/6 is the lowest valid value as we have at most 6 teams
x = max(1.0 / 6.0, x) # 1/6 is the lowest valid value as we have at most 6 teams
num_teams = num_colors(x)
return (1.0 / num_teams, )
return (1.0 / num_teams,)


def scale_up(threshold, dim):
"""Rescale up to actual values"""
out = int(dim * threshold)
return out


def scale_down(threshold, dim):
"""Rescale 0 =< output =< 1"""
out = float(dim/threshold) if threshold else 0.0
out = float(dim / threshold) if threshold else 0.0
return out


def oracle(x):
"""Run a GU game by scaling up the features so they can be input into the game.
Then scale them done so the active learner can understand them.
"""
grid_config = {
"mode": u'live',
"recruiter": u'mturk',
"bot_policy": u"AdvantageSeekingBot",
u'contact_email_on_error': u"[email protected]",
"contact_email_on_error": u"[email protected]",
u'organization_name': u'UC Berkeley',
u'description': u'Play an interactive game',
"dyno_type": u"performance-l",
"redis_size": u"premium-5",
"mode": "live",
"recruiter": "mturk",
"bot_policy": "AdvantageSeekingBot",
"contact_email_on_error": "[email protected]",
"contact_email_on_error": "[email protected]",
"organization_name": "UC Berkeley",
"description": "Play an interactive game",
"dyno_type": "performance-l",
"redis_size": "premium-5",
"num_dynos_worker": 4,
"num_dynos_web": 1,
"max_participants": 12,
Expand All @@ -67,6 +68,7 @@ def oracle(x):
collected_data[data.source] = grid_config
return results


def main():
learner = ActiveLearner(
query_strategy=BALD(dim=NDIM),
Expand All @@ -80,13 +82,15 @@ def main():
x = learner.next_query()
x = closest_valid_x(x)
y = learner.query(oracle, x)
print x, y
print((x, y))
learner.update(x, y)
print(learner.posteriors)
print(learner.map_model)
import pdb; pdb.set_trace()
print collected_data
import pdb

pdb.set_trace()
print(collected_data)


if __name__ == '__main__':
if __name__ == "__main__":
main()
6 changes: 3 additions & 3 deletions demos/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
participants = 3

data = experiment.run(
mode=u'debug',
recruiter=u'bots',
bot_policy=u"AdvantageSeekingBot",
mode="debug",
recruiter="bots",
bot_policy="AdvantageSeekingBot",
max_participants=participants,
num_dynos_worker=participants,
)
Expand Down
39 changes: 25 additions & 14 deletions demos/graph_groups.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,44 @@
from __future__ import unicode_literals

import csv
import json

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from dallinger.experiments import Griduniverse

from dlgr.griduniverse.experiment import Gridworld

matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.use("Agg")

ROWS = 40
COLS = 40
# We need to increase the CSV field size to successfully load GU experiment
# data with a large grid
ORIG_CSV_LIMIT = csv.field_size_limit(ROWS*COLS*1024)
ORIG_CSV_LIMIT = csv.field_size_limit(ROWS * COLS * 1024)

BASE_ID = "b0d3daa{}-f7ed-43fa-ad6b-9928aa51f8e1"
PARTICIPANTS = 6

# Repeat for each group counts into which we can divide participants
GROUP_COUNTS = [n for n in range(1, len(Gridworld.player_colors) + 1)
if PARTICIPANTS % n == 0 and n != PARTICIPANTS]
GROUP_COUNTS = [
n
for n in range(1, len(Gridworld.player_colors) + 1)
if PARTICIPANTS % n == 0 and n != PARTICIPANTS
]

PLOT_VARS = ["average_score", "average_payoff"]
print "Running with {} participants and group counts {}".format(
PARTICIPANTS, GROUP_COUNTS
print(
"Running with {} participants and group counts {}".format(
PARTICIPANTS, GROUP_COUNTS
)
)

EXP_CONFIG = {
"mode": "live",
"max_participants": PARTICIPANTS,
"num_recruits": PARTICIPANTS*3,
"num_recruits": PARTICIPANTS * 3,
"num_colors": 1,
"time_per_round": 60.0,
"num_rounds": 2,
Expand Down Expand Up @@ -63,17 +71,20 @@
config["num_colors"] = count
data.append(exp.collect(exp_id, exp_config=config))

graph_data = [(count, json.loads(exp.analyze(data[i])))
for i, count in enumerate(GROUP_COUNTS)]
graph_data = [
(count, json.loads(exp.analyze(data[i]))) for i, count in enumerate(GROUP_COUNTS)
]

df = pd.DataFrame([[d[1][v] for v in PLOT_VARS] for d in graph_data],
index=[d[0] for d in graph_data],
columns=PLOT_VARS)
df = pd.DataFrame(
[[d[1][v] for v in PLOT_VARS] for d in graph_data],
index=[d[0] for d in graph_data],
columns=PLOT_VARS,
)

axes = df.plot(kind="bar", title="Griduniverse Score/Payoff by Number of Groups")
axes.set_xlabel("Number of Groups")
fig = axes.get_figure()

fig.savefig("groups_graph.png")
plt.close(fig)
print "Graph saved to groups_graph.png"
print("Graph saved to groups_graph.png")
Loading

0 comments on commit 68bc57b

Please sign in to comment.