Skip to content
Open
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ Follow these steps:

If the data has been added via a pull request, you do not need to clone the repo. You can simply merge the PR; wait for the sanity checks to run; compute the metadata via the GitHub action; update the zip in the release via the GitHub action; and you're done. Then, move to [PrefLib-Jekyll](https://github.com/PrefLib/PrefLib-Jekyll) to update the website.

### Large data files

GitHub rejects files over 100 MB and warns above 50 MB. A data file larger
than 50 MB may be stored gzip-compressed, with `.gz` appended to its name
(for example `00080-00000005.soi.gz`). Everywhere else it keeps its plain name:

- `info.txt` lists `00080-00000005.soi`;
- `metadata.csv` gives the MD5 of the plain file;
- `scripts/zipall.py` writes the plain file into the release zip, so users see no difference.

`scripts/sanitychecks.py` and `scripts/compute_metadata.py` read compressed
files directly (see `scripts/datafiles.py`). Compress with `gzip -9 -n`.

### Update the zip archives

The zip files served from the website are actually hosted as assets of the v1.0 release of this repository.
Expand Down
22 changes: 11 additions & 11 deletions scripts/compute_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import argparse
import csv
import hashlib
import os
import pathlib
import sys
from collections.abc import Iterable, Callable, Collection
from datetime import datetime
from enum import IntEnum
Expand All @@ -14,14 +14,19 @@
import dateutil.parser
import pandas as pd

from preflibtools.instances import get_parsed_instance, PrefLibInstance
from preflibtools.instances import PrefLibInstance
from preflibtools.instances.dataset import read_info_file
from preflibtools.properties import num_alternatives, num_voters, num_different_preferences, \
is_approval, has_condorcet, is_strict, is_complete
from preflibtools.properties.subdomains.ordinal import is_single_peaked, is_single_peaked_pq_tree, \
is_single_crossing
from preflibtools.properties.subdomains.ordinal.singlepeaked import is_single_peaked_on_tree

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, SCRIPT_DIR)
# Data files may be stored compressed (x.soi.gz); they are always addressed by their plain path (x.soi).
from datafiles import md5 as data_file_md5, parse_instance, stored_path # noqa: E402


class SPEED(IntEnum):
SLOW = 1
Expand Down Expand Up @@ -105,7 +110,7 @@ def compute_file(self, file_path: str, speed: SPEED, pre_parsed_instance: PrefLi
if self.is_file_property:
return self.compute(file_path, os.path.splitext(file_path)[1][1:])
if pre_parsed_instance is None:
pre_parsed_instance = get_parsed_instance(file_path)
pre_parsed_instance = parse_instance(file_path)
return self.compute_instance(pre_parsed_instance, speed)

def __str__(self):
Expand Down Expand Up @@ -143,7 +148,7 @@ def compute_file_properties(file_path_and_property_list: Collection[str, Iterabl
file_name = os.path.basename(file_path)
print(f"\tComputing on {file_name} - {tuple(p.name for p in property_list)}")
results = {}
instance = get_parsed_instance(file_path)
instance = parse_instance(file_path)
for prop in property_list:
res = prop.compute_file(file_path, speed, pre_parsed_instance=instance)
if res is not None:
Expand Down Expand Up @@ -265,15 +270,11 @@ def get_file_number(file_path):


def get_last_modif_time(file_path):
return datetime.fromtimestamp(pathlib.Path(file_path).stat().st_mtime)
return datetime.fromtimestamp(pathlib.Path(stored_path(file_path)).stat().st_mtime)


def get_md5(file_path):
hash_md5 = hashlib.md5()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return str(hash_md5.hexdigest())
return str(data_file_md5(file_path))


def get_modification_type(file_path):
Expand Down Expand Up @@ -332,7 +333,6 @@ def none_func(x):
]
ALL_PROPERTIES_BY_NAME = {p.name: p for p in ALL_PROPERTIES_LIST}

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DATASET_FOLDER = os.path.join(SCRIPT_DIR, "..", "datasets")


Expand Down
69 changes: 69 additions & 0 deletions scripts/datafiles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Helpers for data files that are stored gzip-compressed in the repository.

A data file larger than GitHub comfortably handles (see README) may be stored
as ``<name>.gz``, for instance ``00080-00000005.soi.gz``. Everywhere else it is
known by its plain name: ``info.txt`` and ``metadata.csv`` list
``00080-00000005.soi``, the MD5 in ``metadata.csv`` is that of the plain file,
and ``zipall.py`` writes the plain file into the release zips. Users of the
zips and of the website never see the compressed form.
"""

import gzip
import hashlib
import os
import shutil
import tempfile

from preflibtools.instances import get_parsed_instance

COMPRESSED_SUFFIX = ".gz"


def logical_name(file_name):
"""The plain name of a data file: ``x.soi.gz`` -> ``x.soi``."""
if file_name.endswith(COMPRESSED_SUFFIX):
return file_name[: -len(COMPRESSED_SUFFIX)]
return file_name


def stored_path(file_path):
"""The path on disk of a data file given by its plain or stored path."""
if os.path.exists(file_path):
return file_path
compressed = file_path + COMPRESSED_SUFFIX
if os.path.exists(compressed):
return compressed
return file_path


def open_data_file(file_path):
"""Open a data file (plain or compressed) for binary reading."""
path = stored_path(file_path)
if path.endswith(COMPRESSED_SUFFIX):
return gzip.open(path, "rb")
return open(path, "rb")


def md5(file_path):
"""MD5 of the plain contents of a data file."""
hash_md5 = hashlib.md5()
with open_data_file(file_path) as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()


def parse_instance(file_path, **kwargs):
"""Parse a data file (plain or compressed) with preflibtools.

preflibtools infers the data type from the extension and records the file
name, so a compressed file is decompressed under its plain name first.
"""
path = stored_path(file_path)
if not path.endswith(COMPRESSED_SUFFIX):
return get_parsed_instance(path, **kwargs)
with tempfile.TemporaryDirectory() as tmp:
plain = os.path.join(tmp, logical_name(os.path.basename(path)))
with gzip.open(path, "rb") as src, open(plain, "wb") as dst:
shutil.copyfileobj(src, dst)
return get_parsed_instance(plain, **kwargs)
10 changes: 7 additions & 3 deletions scripts/sanitychecks.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import argparse
import warnings

from preflibtools.instances.preflibinstance import get_parsed_instance
from preflibtools.instances.dataset import read_info_file
import preflibtools.instances.sanity as sanity

import os
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, SCRIPT_DIR)
from datafiles import logical_name, parse_instance # noqa: E402

DATASET_FOLDER = os.path.join(SCRIPT_DIR, "..", "datasets")


def check_dataset(ds_dir, escalate_warnings):
"""Run sanity checks on a dataset directory and escalate warnings if specified."""
print(f"Checking {ds_dir}")
info_file_path = os.path.join(DATASET_FOLDER, ds_dir, "info.txt")
dataset_files = sorted(os.listdir(os.path.join(DATASET_FOLDER, ds_dir)))
# Compressed data files (x.soi.gz) are checked under their plain names (x.soi).
dataset_files = sorted(logical_name(f) for f in os.listdir(os.path.join(DATASET_FOLDER, ds_dir)))

# Check info.txt file if it exists
if "info.txt" in dataset_files:
Expand Down Expand Up @@ -69,7 +73,7 @@ def check_file(ds_dir, file, escalate_warnings):
extension = os.path.splitext(file)[1][1:]

if extension in ["soc", "toc", "soi", "toi", "cat"]:
instance = get_parsed_instance(file_path)
instance = parse_instance(file_path)

# Metadata check
metadata_errors = sanity.metadata(instance)
Expand Down
19 changes: 15 additions & 4 deletions scripts/zipall.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import csv
import shutil
import sys
import zipfile
import os

from preflibtools.instances import get_parsed_instance
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from datafiles import logical_name, open_data_file, stored_path # noqa: E402

IN_DIR = os.path.join("..", "datasets")
OUT_DIR = os.path.join("..", "zip")
Expand Down Expand Up @@ -30,9 +33,10 @@ def zip_all():

for datafile_name in sorted(os.listdir(os.path.join(IN_DIR, dataset_dir))):
print(f"\t.. {datafile_name}")
file_path = os.path.join(IN_DIR, dataset_dir, datafile_name)
# Compressed data files (x.soi.gz) are handled, and zipped, under their plain names (x.soi).
file_path = os.path.join(IN_DIR, dataset_dir, logical_name(datafile_name))
ds_files.append(file_path)
data_type = datafile_name[-3:]
data_type = file_path[-3:]
if data_type in relevant_data_types:
type_to_files[data_type].append(file_path)
metadata = file_to_metadatas[os.path.basename(file_path)]
Expand All @@ -50,7 +54,14 @@ def zip_all():
print(f"Zipping {dataset}")
with zipfile.ZipFile(os.path.join(OUT_DIR, dataset.replace(" - ", "_") + ".zip"), "w", zipfile.ZIP_DEFLATED) as zip_file:
for file_path in all_files:
zip_file.write(file_path, os.path.basename(file_path))
stored = stored_path(file_path)
if stored == file_path:
zip_file.write(file_path, os.path.basename(file_path))
else:
zip_info = zipfile.ZipInfo.from_file(stored, os.path.basename(file_path))
zip_info.compress_type = zipfile.ZIP_DEFLATED
with open_data_file(file_path) as src, zip_file.open(zip_info, "w") as dst:
shutil.copyfileobj(src, dst)
#
# for modif_type, all_files in modif_to_files.items():
# print(f"Zipping {modif_type}")
Expand Down
Loading