Datasets:
Create metamath_graphs.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# metamath_graphs.py## Hugging Face Datasets loading script for Metamath proof graphs.# Assumes a raw `data.json` file whose top-level is either:# - a dict: { "0": {...}, "1": {...}, ... }# - or a list: [ {...}, {...}, ... ]## Each example is expected to look like:# {# "graph_features": [2, "mp2"],# "x": [# [0, {"num": 3, "label": "$e", "statement": "ps"}],# [1, {"num": 8, "label": "$e", "statement": "ph"}],# ...# ],# "edge_index": [[1, 2, 0, 3], [3, 3, 4, 4]],# "edge_attr": [[8, 10], [9, 10], [3, 11], [10, 11]]# }
import jsonimport osfrom typing import Dict, Any, Iterable, Tuple
import datasets
_CITATION = r"""@misc{yourname2025metamathgraphs, title = {Metamath Proof Graphs}, author = {Your Name}, year = {2025}, howpublished = {Hugging Face Datasets}, note = {Directed proof DAGs derived from the Metamath Proof Explorer}}"""
_DESCRIPTION = """Metamath Proof Graphs is a graph-structured dataset of formal proofs extractedfrom the Metamath Proof Explorer. Each example corresponds to a single theoremrepresented as a directed acyclic graph (DAG):
- Nodes represent hypotheses, axioms, and derived statements.- Directed edges represent logical dependencies between statements.- Node features include a local index, Metamath statement number, label, and full symbolic statement.- Edge attributes record the original Metamath statement numbers involved in each dependency.
The dataset is designed to be directly consumable by graph neural networks(PyTorch Geometric, DGL, etc.) and to preserve the original Metamath semantics."""
_HOMEPAGE = "https://huggingface.co/datasets/<your-username>/<dataset-name>"
_LICENSE = "mit"
class MetamathGraphsConfig(datasets.BuilderConfig): """BuilderConfig for MetamathGraphs."""
def __init__(self, **kwargs): super().__init__(**kwargs)
class MetamathGraphs(datasets.GeneratorBasedBuilder): """Metamath proof graphs as a Hugging Face dataset."""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [ MetamathGraphsConfig( name="default", version=VERSION, description="Metamath proof graphs with nodes and edges.", ), ]
DEFAULT_CONFIG_NAME = "default"
def _info(self) -> datasets.DatasetInfo: """Returns the dataset metadata and feature schema.""" features = datasets.Features( { # Global theorem metadata (from graph_features) "theorem_index": datasets.Value("int64"), # e.g., 2 "theorem_label": datasets.Value("string"), # e.g., "mp2"
# Nodes: one entry per node in the graph # Derived from `x`, which is [[local_index, {num, label, statement}], ...] "nodes": datasets.Sequence( { "local_index": datasets.Value("int64"), # 0, 1, 2, ... "num": datasets.Value("int64"), # Metamath statement number within proof context "label": datasets.Value("string"), # e.g. "$e", "ax-mp" "statement": datasets.Value("string"), # symbolic statement } ),
# Edge index in COO format (2 x num_edges) # edge_index[0][k] -> edge_index[1][k] "edge_index": datasets.Sequence( datasets.Sequence(datasets.Value("int64")) ),
# Edge attributes: one feature vector per edge # Here: [from_stmt_num, to_stmt_num] in Metamath numbering "edge_attr": datasets.Sequence( datasets.Sequence(datasets.Value("int64")) ), } )
return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, )
def _split_generators(self, dl_manager: datasets.DownloadManager): """ Define dataset splits.
This version assumes that `data.json` is available locally in a directory passed via `data_dir` when calling `load_dataset`, e.g.:
load_dataset("path/to/metamath_graphs.py", data_dir="path/to/folder")
and that `path/to/folder/data.json` exists.
On the Hub, you can adjust this to use a remote URL or just rely on `self.config.data_dir` being the repo data directory. """ data_dir = self.config.data_dir if data_dir is None: # Fallback: assume data.json is in the same directory as this script script_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = script_dir
filepath = os.path.join(data_dir, "data.json")
return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"filepath": filepath}, ), ]
def _generate_examples(self, filepath: str) -> Iterable[Tuple[int, Dict[str, Any]]]: """Yields examples as (key, example_dict).""" with open(filepath, "r", encoding="utf-8") as f: raw = json.load(f)
# Handle both dict and list top-level structures if isinstance(raw, dict): items = list(raw.items()) # (key, value) pairs else: # Assume list: convert to (index, example) items = [(str(i), ex) for i, ex in enumerate(raw)]
for raw_key, ex in items: # raw_key might be a string like "4" -> use int for deterministic id try: key = int(raw_key) except (TypeError, ValueError): # If keys are non-numeric, just enumerate key = None
graph_features = ex.get("graph_features", None) if graph_features is None or len(graph_features) != 2: raise ValueError(f"Example {raw_key} is missing valid 'graph_features'.")
theorem_index = int(graph_features[0]) theorem_label = str(graph_features[1])
# Convert `x` into a list of typed node dicts nodes_raw = ex.get("x", []) nodes = [] for node_entry in nodes_raw: # Expect [local_index, {num, label, statement}] if not isinstance(node_entry, list) or len(node_entry) != 2: raise ValueError(f"Bad node entry in example {raw_key}: {node_entry}")
local_index, node_info = node_entry nodes.append( { "local_index": int(local_index), "num": int(node_info["num"]), "label": str(node_info["label"]), "statement": str(node_info["statement"]), } )
edge_index = ex.get("edge_index", []) edge_attr = ex.get("edge_attr", [])
# Basic sanity checks (optional but helpful) if len(edge_index) != 2: raise ValueError( f"Example {raw_key} has edge_index with shape {len(edge_index)}, expected 2 rows." ) if len(edge_index[0]) != len(edge_index[1]): raise ValueError( f"Example {raw_key} has mismatched edge_index lengths: " f"{len(edge_index[0])} vs {len(edge_index[1])}" ) if len(edge_attr) != len(edge_index[0]): raise ValueError( f"Example {raw_key} has {len(edge_attr)} edge_attr rows but " f"{len(edge_index[0])} edges in edge_index." )
example = { "theorem_index": theorem_index, "theorem_label": theorem_label, "nodes": nodes, "edge_index": edge_index, "edge_attr": edge_attr, }
# Use theorem_index as key if possible, else fallback to enumeration yield key if key is not None else theorem_index, examplemetamath_graphs.pyAdded+224