Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions scripts/backfill_reward_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
be the rounded or truncated form of the value in the file, and the block's
first_trial must agree. Anything that fails is reported and left alone.

WARNING: the stored value is the scale of the block's FIRST trial only, as in
MATLAB's TowersBlock.m. ViRMEn can change the scale mid-block, and the database
has no per-trial column, so reward_scale does not describe every trial of such a
block, before or after this backfill. The script counts and lists them. For the
scale of each trial, read block(b).trial(t).rewardScale from the log.

Runs read-only unless --commit is passed.

python scripts/backfill_reward_scale.py --user efonseca
Expand Down Expand Up @@ -283,6 +289,7 @@ def main(argv=None):
problems = []
missing = []
relocated = []
mid_block = []

for i, key in enumerate(session_keys, start=1):
session_rows = sessions[key]
Expand Down Expand Up @@ -325,6 +332,13 @@ def main(argv=None):
)
counts[verdict] += 1

scales = rsb.read_trial_scales(log, row["block"])
changes = rsb.scale_changes(scales)
if changes:
mid_block.append(
(label, row["block"], len(scales), file_scale, changes, verdict)
)

if verdict == rsb.MISMATCH:
problems.append(
(
Expand Down Expand Up @@ -384,6 +398,24 @@ def main(argv=None):
if len(relocated) > 50:
print(f" ... and {len(relocated) - 50} more")

if mid_block:
to_update = sum(verdict == rsb.OK for *_, verdict in mid_block)
print(
f"\n--- WARNING: reward scale changes mid-block in {len(mid_block)} block(s), "
f"{to_update} of them with verdict {rsb.OK} ---\n"
" reward_scale stores only the first trial's value, so it does not "
"describe the later trials of these blocks."
)
for label, block, n_trials, first_scale, changes, _ in mid_block[:50]:
first = "missing" if first_scale is None else f"{first_scale:.4g}"
steps = ", ".join(f"{scale:.4g} at trial {t}" for t, scale in changes)
print(
f" {label} block {block} ({n_trials} trials): "
f"first trial {first}, then {steps}"
)
if len(mid_block) > 50:
print(f" ... and {len(mid_block) - 50} more")

if problems:
print(f"\n--- {len(problems)} blocks/sessions needing attention ---")
for label, block, kind, detail in problems[:50]:
Expand Down
65 changes: 65 additions & 0 deletions tests/utils/test_reward_scale_backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,71 @@ def test_no_blocks(self):
assert rsb.read_block_values({}, 1) == (None, None)


class TestReadTrialScales:
@staticmethod
def block_of(*scales):
trials = [{"rewardScale": scale} for scale in scales]
return {"firstTrial": 1, "trial": np.array(trials, dtype=object)}

def test_one_value_per_trial(self):
log = make_log(np.array([make_block(), self.block_of(1.2, 1.2, 3.0)]))
assert rsb.read_trial_scales(log, 2) == pytest.approx([1.2, 1.2, 3.0])

def test_single_block_and_single_trial_squeezed_to_dicts(self):
block = {"firstTrial": 7, "trial": {"rewardScale": 0.6}}
assert rsb.read_trial_scales(make_log(block), 1) == pytest.approx([0.6])

def test_trials_without_a_usable_value_are_none(self):
block = self.block_of(1.2, np.nan, np.array([]))
block["trial"] = np.append(block["trial"], [{"choice": 1}, None])
assert rsb.read_trial_scales(make_log(block), 1) == [
1.2,
None,
None,
None,
None,
]

@pytest.mark.parametrize("block_num", [0, 2, -1])
def test_block_index_out_of_range(self, block_num):
assert rsb.read_trial_scales(make_log(make_block()), block_num) == []

@pytest.mark.parametrize("trials", [None, np.array([]), []])
def test_no_trials(self, trials):
log = make_log({"firstTrial": 1, "trial": trials})
assert rsb.read_trial_scales(log, 1) == []

def test_no_blocks(self):
assert rsb.read_trial_scales({}, 1) == []


class TestScaleChanges:
def test_constant_block_has_none(self):
assert rsb.scale_changes([1.2, 1.2, 1.2]) == []

def test_reports_trial_number_and_new_value(self):
assert rsb.scale_changes([1.5, 1.5, 1.7, 3.0, 3.0]) == [(3, 1.7), (4, 3.0)]

def test_change_on_the_last_trial_counts(self):
assert rsb.scale_changes([1.2, 3.0]) == [(2, 3.0)]

def test_change_back_to_the_first_value_counts(self):
assert rsb.scale_changes([1.0, 1.2, 1.0]) == [(2, 1.2), (3, 1.0)]

def test_float_noise_is_not_a_change(self):
assert rsb.scale_changes([1.2, float(np.float32(1.2))]) == []

def test_missing_values_are_skipped_but_keep_their_trial_number(self):
assert rsb.scale_changes([1.2, None, 1.2, None, 1.4]) == [(5, 1.4)]

def test_missing_first_value_is_not_a_change(self):
assert rsb.scale_changes([None, 1.2, 1.2]) == []

@pytest.mark.parametrize("scales", [[], [1.2], [None], [None, None]])
def test_nothing_to_compare(self, scales):
assert rsb.scale_changes(scales) == []


class TestClassify:
@pytest.mark.parametrize(
"db, file", [(1, 1.2), (2, 1.8), (1, 1.8), (2, 1.5), (0, 0.4)]
Expand Down
37 changes: 37 additions & 0 deletions u19_pipeline/utils/reward_scale_backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,43 @@ def read_block_values(log, block_num):
return reward_scale, first_trial


def read_trial_scales(log, block_num):
"""Return the reward scale of every trial in 1-indexed block_num.

A trial without a usable value is None, so positions stay trial numbers.
"""
blocks = as_list(log.get("block"))
if block_num < 1 or block_num > len(blocks):
return []
block = blocks[block_num - 1]
if not isinstance(block, dict):
return []
return [
scalar(trial.get("rewardScale")) if isinstance(trial, dict) else None
for trial in as_list(block.get("trial"))
]


def scale_changes(scales):
"""Return (trial, new value) wherever the scale differs from the trial before.

Trials are numbered from 1 within the block. TowersBlock.reward_scale holds
only the first trial's value, so a non-empty result means the stored value
does not describe the whole block.
"""
changes = []
previous = None
for trial, scale in enumerate(scales, start=1):
if scale is None:
continue
if previous is not None and not math.isclose(
scale, previous, rel_tol=0, abs_tol=1e-6
):
changes.append((trial, scale))
previous = scale
return changes


def classify(db_scale, db_first_trial, file_scale, file_first_trial):
"""Decide whether this block is safe to update."""
if file_scale is None:
Expand Down