Datasets:

DOI:
License:
GotPsi / scripts /patch_v1_1.py
ebrinz's picture
instnoeticsciences
claude opus 4.6
GotPsi v1.2
87ec79f
Raw History Blame Contribute Delete
5.11 kB
#!/usr/bin/env python3
"""Apply to the published v1.0 Parquet files the changes v1.1 makes to rows
that already existed in v1.0.
v1.1 also contains the trials of 34 log files that v1.0 had skipped. Those
rows are not produced here: they come only from rebuilding the tables from
data/source (scripts/process_*_full.py). For card and rv this script
therefore gives the v1.1 table without the rows of those logs; for location
it gives the v1.1 table.
The changes leave every user_id untouched, so no pepper is needed:
rv_cleaned.parquet the last 379 rows, which came from the judges'
rating files and are not trials, are dropped;
attr_00..attr_06 (shape checkboxes) become 0/1.
v1.0 stored a ticked box as NaN because the server
logged the checkbox word ("rounded", "angular", ...).
location_cleaned.parquet new boolean column `malformed`
(no timestamp, or |z_score| > 10).
card_cleaned.parquet is_hit recomputed as target2 == response. v1.0
compared the raw columns, where the response was
often text and the target a number, so most hits
before 2006-01-10 were stored as 0.
The fixed processors (scripts/process_rv_full.py,
scripts/process_location_full.py, scripts/process_card_full.py), run on the
published data/source archives, give the same values for these rows.
Usage:
python scripts/patch_v1_1.py --v1-0 path/to/v1.0/output/parquet --out path/to/out
"""
import argparse
import sys
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.processors.location_processor import flag_malformed
from src.processors.rv_processor import RVProcessor
def patch_rv(df: pd.DataFrame) -> pd.DataFrame:
# Rows from the judges' rating files are not trials: no time, no date.
judge_rows = df['start_time'].isna() & df['end_time'].isna() & df['file_date'].isna()
df = df[~judge_rows].reset_index(drop=True)
out = df.copy()
for col in RVProcessor.SHAPE_COLUMNS:
# NaN = a logged word = selected; any non-zero number is also "selected"
out[col] = (df[col].isna() | (df[col] != 0)).astype('int64')
# Ratings that were float only because the judge rows held NaN
for col in RVProcessor.ATTRIBUTE_COLUMNS[7:]:
if col in out.columns and not out[col].isna().any():
out[col] = out[col].astype('int64')
return out
def patch_location(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
out['malformed'] = flag_malformed(df)
return out
def patch_card(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
out['is_hit'] = (df['target2'] == df['response']).astype(df['is_hit'].dtype)
return out
def _patch_card_file(src: Path, dst: Path) -> None:
"""Patch the card table one row group at a time (89.5 million rows)."""
source = pq.ParquetFile(src)
schema = source.schema_arrow
rows = changed = 0
with pq.ParquetWriter(dst, schema, compression='snappy') as writer:
for i in range(source.num_row_groups):
old = source.read_row_group(i).to_pandas()
new = patch_card(old)
_check_untouched(old, new, ['is_hit'])
rows += len(new)
changed += int((old['is_hit'] != new['is_hit']).sum())
writer.write_table(pa.Table.from_pandas(new, schema=schema, preserve_index=False))
print(f'card_cleaned.parquet: {rows:,} rows, changed columns: is_hit ({changed:,} values)')
def _check_untouched(old: pd.DataFrame, new: pd.DataFrame, changed: list) -> None:
kept = old[old['user_id'].isin(new['user_id'])].reset_index(drop=True) if len(old) != len(new) else old
assert len(kept) == len(new), 'unexpected row count'
for col in old.columns:
if col not in changed:
assert (kept[col].eq(new[col]) | (kept[col].isna() & new[col].isna())).all(), f'{col} changed'
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])
parser.add_argument('--v1-0', required=True, type=Path, help='dir holding the v1.0 parquet files')
parser.add_argument('--out', required=True, type=Path, help='dir to write the v1.1 parquet files')
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
for name, patch, changed in [
('rv_cleaned.parquet', patch_rv, RVProcessor.SHAPE_COLUMNS),
('location_cleaned.parquet', patch_location, ['malformed']),
]:
old = pd.read_parquet(args.v1_0 / name)
new = patch(old)
_check_untouched(old, new, changed)
new.to_parquet(args.out / name, compression='snappy', engine='pyarrow', index=False)
print(f'{name}: {len(new):,} rows, changed columns: {", ".join(changed)}')
_patch_card_file(args.v1_0 / 'card_cleaned.parquet', args.out / 'card_cleaned.parquet')
return 0
if __name__ == '__main__':
sys.exit(main())