Metadata-Version: 2.4
Name: pydfig
Version: 0.2.0
Summary: Self-describing scientific figures (Figure-as-Data): embed exact data, SMILES and structure files in SVG/PNG, decode losslessly to JSON (for AI) and HTML (for humans).
Author: Fenglong Li, Siyang Li
License: MIT
Project-URL: Homepage, https://pydfig.ai4c/schema
Project-URL: Schema, https://dfig.ai4c/schema/dfig-2.0.schema.json
Keywords: scientific figures,FAIR data,machine-readable,AI4Science,SVG,metadata,Figure-as-Data
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Chemistry
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# pydfig — dFIG: Self-Describing Scientific Figures (Figure-as-Data)

[![PyPI](https://img.shields.io/pypi/v/pydfig.svg)](https://pypi.org/project/pydfig/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org/)

**dFIG** is an open figure format that embeds the *exact* underlying data of a
scientific plot inside the figure file itself. The visual layer shows only the
plot; the file carries structured, machine-readable JSON that parsers and LLM
agents can read **losslessly** — no OCR, no pixel digitization, no error.

`pydfig` is the reference implementation: the dFIG 2.0 schema, a payload
builder, three embedding carriers (SVG / PNG / `.dfigz`), a set of dFIG-native
figure generators, and a CLI. **Pure Python standard library, zero
dependencies.**

## Why

Today, scientific figures are data *endpoints*: data is plotted, rasterized,
and the numbers are lost. Recovering them requires chart OCR / vision models,
which our ablation benchmark shows recover only a small fraction of points on
common chemistry/materials figure types (XRD, band structures, RDF, Nyquist,
BET, XPS, DSC, Arrhenius ...), with non-trivial coordinate error — even for
frontier vision-language models. dFIG inverts the flow: **the figure is the
starting point of the data stream**.

| Path | recall | norm. MAE |
|---|---|---|
| **dFIG parse (exact)** | **1.000** | **0** |
| Vision-language models (best of 24+) | 0.03 – 0.18 | 0.010 – 0.020 |

(100-figure stratified ablation + 78-figure structure-reconstruction
benchmark — see the AI4C paper.) Full numbers ship with the paper's
supplementary material.

## How the data is hidden

dFIG 2.0 uses three complementary channels:

1. **SVG `<metadata>` JSON payload (primary).** `<metadata>` is the standard
   W3C element for machine-readable metadata. Every compliant renderer ignores
   it, so the figure looks identical in any viewer, while the JSON payload —
   exact data points, curves, axes, caption, provenance — is one `regex` away.
2. **Per-element `data-*` attributes (redundancy).** Each graphical element
   carries its own values (`<circle ... data-x="-1.95" data-y="0.42"
   data-material="NiO"/>`), enabling spot checks and graceful degradation if
   the metadata block is stripped.
3. **Hidden chemistry.** Molecular figures embed the **SMILES** string;
   molecule/crystal figures embed the full **PDB / CIF / VASP POSCAR** source
   in `payload.structure`. One figure file = lossless 3D structure recovery.
   (PNG payloads use a legal private ancillary chunk `dDat`; the `.dfigz` ZIP
   container survives re-encoding pipelines.)

## Install

```bash
pip install pydfig
```

## Payload at a glance (v2.0)

```json
{
  "format": "dFIG",
  "version": "2.0",
  "figure_type": "molecule",
  "caption": "benzene ball-and-stick (SMILES: c1ccccc1)",
  "smiles": "c1ccccc1",
  "structure": {"format": "pdb", "content": "REMARK ... END"},
  "axes": {"x": {...}, "y": {...}},
  "points": [{"element": "C", "x": 1.39, "y": 0.0, "z": 0.0}],
  "curves": [],
  "provenance": {"domain": "molecular chemistry", "method": "DFT/PBE"}
}
```

Formal JSON Schema: `pydfig/schema/dfig-2.0.schema.json` (installed with the
package, also published at <https://dfig.ai4c/schema/dfig-2.0.schema.json>).

## Usage — read a dFIG

```bash
# decode the embedded payload (SVG / PNG(dDat) / .dfigz auto-detected)
python -m pydfig decode figure.svg
dfig decode figure.svg          # same, via the console entry point

# one-line summary (type, points, smiles, hidden structure composition)
dfig info figure.svg

# validate against the dFIG 2.0 schema
dfig validate figure.svg

# extract the hidden PDB/POSCAR structure to disk
dfig extract-structure slab.svg -o nio_slab.poscar
```

```python
from pydfig import decode_any, validate

payload = decode_any("figure.svg")     # SVG / PNG(dDat) / .dfigz auto-detect
errors  = validate(payload)            # [] == valid
```

## Usage — write a dFIG

### Embed into an existing SVG

```python
from pydfig import build_payload, embed_in_svg

svg = open("my_plot.svg").read()
svg = embed_in_svg(svg, build_payload("scatter", points=[{"x": 1.0, "y": 2.0}]))
```

### Generate a dFIG-native figure (new in 0.2.0)

```python
from pydfig import scatter_svg, line_svg, bar_svg, molecule_svg, slab_svg, save_svg

# scatter / volcano — every <circle> carries data-x / data-y / data-material
svg = scatter_svg(
    points=[{"x": -1.95, "y": 0.42, "material": "NiO"},
            {"x": -1.10, "y": 0.18, "material": "Pt"}],
    x_label="ΔG_H* (eV)", y_label="overpotential (V)",
    caption="Volcano plot of HER activity",
    provenance={"domain": "electrocatalysis", "method": "DFT/PBE"},
)
save_svg(svg, "volcano.dfig.svg")

# grouped bars / histograms — every <rect> carries data-x / data-series / data-y
svg = bar_svg(
    categories=["Pt", "Pd", "Ni"],
    series={"CO": [8.5, 6.2, 3.1], "CH4": [1.2, 2.4, 5.6]},
    axes={"y_label": "selectivity (%)"},
)
save_svg(svg, "selectivity.dfig.svg")

# molecules & slabs — SMILES and PDB/POSCAR embedded verbatim
svg = molecule_svg(atoms, bonds, smiles="c1ccccc1", structure=pdb_text, caption="benzene")
```

### matplotlib one-liner

```python
import matplotlib.pyplot as plt
from pydfig.matplotlib_converter import convert

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel("2Theta (degree)")
ax.set_ylabel("Intensity")

convert(fig, "output.svg", caption="XRD pattern")   # data embedded, float-exact
convert(fig, "output.png", caption="XRD pattern")   # same, in a PNG dDat chunk
```

The converter auto-detects figure type from axis labels (XRD, FTIR, UV-Vis,
XPS, Nyquist, BET, DSC, TGA, Arrhenius, volcano, RDF, DOS, band structure, ...),
extracts scatter points + line curves with full float precision, and embeds the
dFIG 2.0 payload.

### PNG carrier — `dDat` private chunk

dFIG 2.0 can also embed the payload in a **legal PNG private ancillary chunk
`dDat`**, so an ordinary PNG image carries the exact data too. The PNG remains
a valid image (open it in any viewer / browser), and `decode_any` reads the
chunk losslessly.

```bash
dfig encode-png chart.png --payload payload.json -o chart_dfig.png
dfig decode chart_dfig.png
```

```python
from pydfig import inject_png_ddat, decode_png, build_payload

png = open("chart.png", "rb").read()
out = inject_png_ddat(png, build_payload("scatter", points=[{"x": 1.0, "y": 2.0}]))
data = decode_png(out)
```

## Structure comparison without RDKit

`pydfig.structure` provides dependency-free element-multiset comparison, used
by the structure-reconstruction benchmark (can a vision model recover the
SMILES / POSCAR that dFIG embeds exactly?):

```python
from pydfig import parse_smiles_composition, composition_f1

gt = parse_smiles_composition("c1ccccc1")      # {'C': 6}
composition_f1(gt, {"C": 5, "H": 6})           # -> (precision, recall, f1)
```

## API surface

| Group | Symbols |
|---|---|
| Decode | `decode_svg`, `decode_png`, `decode_dfigz`, `decode_any`, `extract_datapoints` |
| Encode | `build_payload`, `embed_in_svg`, `inject_png_ddat`, `encode_dfigz` |
| Generate | `scatter_svg`, `line_svg`, `bar_svg`, `molecule_svg`, `slab_svg`, `save_svg` |
| Schema | `validate`, `SCHEMA_VERSION`, `DFIG_NS` |
| Structure | `parse_smiles_composition`, `parse_poscar`, `parse_pdb`, `structure_composition`, `composition_f1` |

## Changelog

**0.2.0** — dFIG-native generators promoted into the package (`scatter_svg`,
`line_svg`, `molecule_svg`, `slab_svg`, new `bar_svg`); JSON Schema shipped as
package data; `dfig` console entry point; Python ≥ 3.8 support declared.

**0.1.x** — schema 2.0 payload builder, SVG/PNG/`.dfigz` carriers, CLI,
structure utilities.

## Relationship to prior art

ChartQA / PlotQA / FigureQA / SciCap / DePlot et al. all *extract* data from
figure pixels (OCR/VQA); FAIR, executable papers and Vega-Lite keep data in
*separate* files. dFIG is, to our knowledge, the first format to systematically
embed exact, LLM-parseable scientific data — including domain chemistry
(SMILES, PDB/CIF/POSCAR) — **inside** the figure file, positioning the figure
as the primary data carrier for AI training. See the paper for the full
related-work analysis.

## Citing

See [`CITATION.cff`](CITATION.cff). If you use dFIG, please cite the AI4C
paper (forthcoming) and this package.

## License

MIT — see [`LICENSE`](LICENSE).
