Pore diameters with the winding method: parity with Zeo++

In this notebook we take the IZA zeolite dataset from MOFDB and compare the LCD and PLD tabulated there (Zeo++) with the values computed by mofography’s winding-number percolation (get_pore_dia_mgr_winding, the standard method), and make parity plots. The older face-merging method is run at the end for comparison only.

Importing the necessary libraries

Show code
import warnings, logging
warnings.filterwarnings("ignore")
logging.disable(logging.WARNING)
import numpy as np
import pandas as pd
import mofography as mgr
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.metrics import r2_score, mean_absolute_error

# for the parallel workflow
import dask
from dask import delayed
from dask.distributed import Client

Load the dataset

get_data_from_mofdb is an async function (it queries the MOFDB web API), so it must be awaited. In a notebook cell use top-level await; in a script use asyncio.run(...).

Show code
iza_df = await mgr.get_data_from_mofdb(params={"database": "IZA"})
print(iza_df.shape)
iza_df[["name", "lcd", "pld"]].head()


(216, 21)
name lcd pld
0 ABW-0 3.60282 2.88024
1 ACO-0 3.92937 2.93515
2 AEI-0 6.69320 3.21360
3 AEL-0 4.99656 3.98810
4 AEN-0 3.79191 3.03180

Create ASE atoms objects from the dataframe

Show code
iza_atoms = mgr.atoms_from_mofdb_df(iza_df)

Pore diameter calculation (winding method)

get_pore_dia_mgr_winding(mat_atoms, kwargs=...) takes a distance grid (computed with dgrid_from_atoms_rust, as float32), builds the periodic segmentation and the pore graph, then returns (lcd, pld, lis, dgrid) (diameters in Å). LIS (largest included sphere along percolating pathways) is what older code calls DFSD. We run it over the whole dataset with dask. (There is no compute_pore_diameters_winding function; this is the one-call entry point.)

The defaults used here, all tunable through kwargs, are: grid spacing=0.5 Å, segmentation mask_thickness=0.05, watershed smoothing h=0.2, threshold_abs=1.5, min_distance=1.5 and extra_padding=2. The atomic radii are the Bondi/CRC table (radii=None in the distance-grid call). Grid spacing matters most for narrow pores, as we show below; see Parameter tuning for the others.

Show code
# defaults of get_pore_dia_mgr_winding, written out so they are easy to tune
SEG_KWARGS = dict(mask_thickness=0.05, h=0.2, threshold_abs=1.5, min_distance=1.5, extra_padding=2)

def get_pore_dia_winding(mat_atoms, spacing=0.5):
    # pass a float32 dgrid: the Rust segmentation rejects float64 grids
    dgrid = mgr.dgrid_from_atoms_rust(mat_atoms, spacing=spacing).astype(np.float32)
    lcd, pld, lis, _ = mgr.get_pore_dia_mgr_winding(mat_atoms, dgrid=dgrid, kwargs=dict(spacing=spacing, **SEG_KWARGS))
    return lcd, pld, lis

def safe_result(f):
    # blocks until the task finishes; failed structures become None
    try:
        return f.result()
    except Exception:
        return None

client = Client(processes=True)
futures = client.compute([delayed(get_pore_dia_winding)(a) for a in iza_atoms])
iza_pore_dias = [safe_result(f) for f in futures]
n_ok = sum(d is not None for d in iza_pore_dias)
print(f"{n_ok}/{len(iza_pore_dias)} structures finished")
212/216 structures finished

IZA parity plot (winding vs Zeo++)

MOFDB tabulates only LCD and PLD, so LIS is not compared here; an LIS reference is added in the Zeo++ section below.

Show code
# grab the lcd and pld values from both
lcd_mgr = np.array([d[0] if d is not None else None for d in iza_pore_dias])
lcd_zeo = iza_df['lcd'].values
pld_mgr = np.array([d[1] if d is not None else None for d in iza_pore_dias])
pld_zeo = iza_df['pld'].values

# Create subplots
fig = make_subplots(rows=1, cols=2, subplot_titles=("(a) LCD", "(b) PLD"),
                    horizontal_spacing=0.1)

# LCD subplot
fig.add_trace(
    go.Scatter(
        x=lcd_mgr,
        y=lcd_zeo,
        mode='markers',
        marker=dict(size=10, line=dict(color='black', width=1)),
        name='LCD Data'
    ),
    row=1, col=1
)
fig.add_trace(
    go.Scatter(
        x=[0, max(lcd_zeo)+3],
        y=[0, max(lcd_zeo)+3],
        mode='lines',
        line=dict(color='black', width=1, dash='dash'),
        name='LCD Parity Line'
    ),
    row=1, col=1
)

# PLD subplot
fig.add_trace(
    go.Scatter(
        x=pld_mgr,  # Assuming you have pld_mgr data
        y=pld_zeo,  # Assuming you have pld_zeo data
        mode='markers',
        marker=dict(size=10, line=dict(color='black', width=1)),
        name='PLD Data'
    ),
    row=1, col=2
)
fig.add_trace(
    go.Scatter(
        x=[0, max(pld_zeo)+3],
        y=[0, max(pld_zeo)+3],
        mode='lines',
        line=dict(color='black', width=1, dash='dash'),
        name='PLD Parity Line'
    ),
    row=1, col=2
)

# Update layout for both subplots
fig.update_layout(
    template='simple_white',
    showlegend=False,
    font=dict(family='Arial'),
    width=1200,
    height=600,
    autosize=False,
)

# Update x and y axes for both subplots
for i in [1, 2]:
    fig.update_xaxes(
        title=dict(text='MOFography (\u212b)', font=dict(size=14)),
        tickfont=dict(size=12),
        mirror=True,
        showgrid=False,
        range=[0, max(lcd_zeo if i == 1 else pld_zeo) + 3],
        row=1, col=i
    )
    fig.update_yaxes(
        title=dict(text='Zeo++ (\u212b)', font=dict(size=14)),
        tickfont=dict(size=12),
        mirror=True,
        showgrid=False,
        range=[0, max(lcd_zeo if i == 1 else pld_zeo) + 3],
        row=1, col=i
    )
# Function to remove NaN entries from both arrays
def remove_nan_pairs(arr1, arr2):
    arr1 = np.array(arr1, dtype=float)
    arr2 = np.array(arr2, dtype=float)
    mask = ~np.isnan(arr1) & ~np.isnan(arr2)
    return arr1[mask], arr2[mask]

# Remove NaN entries and compute R² and MAE for LCD
lcd_zeo_clean, lcd_mgr_clean = remove_nan_pairs(lcd_zeo, lcd_mgr)
lcd_r2 = r2_score(lcd_zeo_clean, lcd_mgr_clean)
lcd_mae = mean_absolute_error(lcd_zeo_clean, lcd_mgr_clean)

# Remove NaN entries and compute R² and MAE for PLD
pld_zeo_clean, pld_mgr_clean = remove_nan_pairs(pld_zeo, pld_mgr)
pld_r2 = r2_score(pld_zeo_clean, pld_mgr_clean)
pld_mae = mean_absolute_error(pld_zeo_clean, pld_mgr_clean)

# Add annotations for LCD
fig.add_annotation(
    text=f"R²: {lcd_r2:.2f}<br>MAE: {lcd_mae:.2f} Å",
    xref="x1", yref="y1",
    x=0.05 * max(lcd_zeo), y=0.95 * max(lcd_zeo),
    showarrow=False,
    font=dict(size=14),
    bgcolor="white",
    opacity=0.8,
    row=1, col=1
)

# Add annotations for PLD
fig.add_annotation(
    text=f"R²: {pld_r2:.2f}<br>MAE: {pld_mae:.2f} Å",
    xref="x2", yref="y2",
    x=0.05 * max(pld_zeo), y=0.95 * max(pld_zeo),
    showarrow=False,
    font=dict(size=14),
    bgcolor="white",
    opacity=0.8,
    row=1, col=2
)

fig.show()

Finer grid: 0.25 Å spacing

For small pores a 0.5 Å grid is coarse, so the largest sphere and the narrowest window are only resolved to within a voxel. Here is the same calculation at 0.25 Å, with everything else unchanged. It costs more time and memory (about 8x the voxels), and R² and MAE against the MOFDB Zeo++ values both improve, though modestly: part of the remaining gap is the unknown radii and settings in the MOFDB run. The gain is larger against the matched-radii reference in the next section.

Show code
futures_025 = client.compute([delayed(get_pore_dia_winding)(a, spacing=0.25) for a in iza_atoms])
iza_pore_dias_025 = [safe_result(f) for f in futures_025]
print(f"{sum(d is not None for d in iza_pore_dias_025)}/{len(iza_pore_dias_025)} structures finished")

def parity_stats(dias, col, idx):
    x = np.array([d[idx] if d is not None else np.nan for d in dias], dtype=float)
    y = iza_df[col].values.astype(float)
    m = ~np.isnan(x) & ~np.isnan(y)
    return r2_score(y[m], x[m]), mean_absolute_error(y[m], x[m])

stats = pd.DataFrame(
    {f"{s} \u00c5": {f"{p.upper()} {m}": v for p, i in [("lcd", 0), ("pld", 1)]
                      for m, v in zip(["R\u00b2", "MAE (\u00c5)"], parity_stats(d, p, i))}
     for s, d in [("0.5", iza_pore_dias), ("0.25", iza_pore_dias_025)]}
).round(3)
stats
212/216 structures finished
0.5 Å 0.25 Å
LCD R² 0.956 0.961
LCD MAE (Å) 0.213 0.170
PLD R² 0.983 0.986
PLD MAE (Å) 0.168 0.150
Show code
fig = make_subplots(rows=1, cols=2, subplot_titles=("(a) LCD", "(b) PLD"), horizontal_spacing=0.1)
for i, (p, idx) in enumerate([("lcd", 0), ("pld", 1)], 1):
    x = np.array([d[idx] if d is not None else np.nan for d in iza_pore_dias_025], dtype=float)
    y = iza_df[p].values.astype(float)
    lim = np.nanmax([x, y]) * 1.05
    fig.add_trace(go.Scatter(x=[0, lim], y=[0, lim], mode="lines", line=dict(color="black", width=1, dash="dash")), row=1, col=i)
    fig.add_trace(go.Scatter(x=x, y=y, mode="markers", text=iza_df["name"],
                             marker=dict(size=9, line=dict(color="black", width=1))), row=1, col=i)
    fig.update_xaxes(title="MOFography, 0.25 \u00c5 grid (\u00c5)", range=[0, lim], mirror=True, showgrid=False, row=1, col=i)
    fig.update_yaxes(title="Zeo++ from MOFDB (\u00c5)", range=[0, lim], mirror=True, showgrid=False, row=1, col=i)
fig.update_layout(template="simple_white", showlegend=False, width=1200, height=500, font=dict(family="Arial"))
fig.show()

Comparison only: face merging (older, less accurate)

The previous percolation method labels the voxel grid and merges labels across periodic faces (get_pore_dia_mgr). It is the closer analogue of voxel-sweep tools such as PoreBlazer and is less accurate than the winding method on contorted frameworks, because it cannot follow paths that wrap around the cell obliquely. It is shown here only to compare against the winding results above; do not use it for new work.

Show code
def get_pore_dia_face_merging(mat_atoms):
    lcd, pld, lis, _ = mgr.get_pore_dia_mgr(mat_atoms, kwargs=dict(spacing=0.5))
    return lcd, pld, lis

futures_fm = client.compute([delayed(get_pore_dia_face_merging)(a) for a in iza_atoms])
iza_fm = [safe_result(f) for f in futures_fm]

def mae_vs_zeo(dias, col, idx):
    x = np.array([d[idx] if d is not None else np.nan for d in dias], dtype=float)
    y = iza_df[col].values.astype(float)
    m = ~np.isnan(x) & ~np.isnan(y)
    return mean_absolute_error(y[m], x[m]), r2_score(y[m], x[m])

print(f"{'method':<22s} {'LCD MAE':>8s} {'LCD R2':>8s} {'PLD MAE':>8s} {'PLD R2':>8s}")
for name, dias in [("winding (standard)", iza_pore_dias), ("face merging (legacy)", iza_fm)]:
    lm, lr = mae_vs_zeo(dias, "lcd", 0); pm, pr = mae_vs_zeo(dias, "pld", 1)
    print(f"{name:<22s} {lm:8.3f} {lr:8.3f} {pm:8.3f} {pr:8.3f}")
client.close()
method                  LCD MAE   LCD R2  PLD MAE   PLD R2
winding (standard)        0.213    0.956    0.168    0.983
face merging (legacy)     0.198    0.955    0.227    0.975

Independent Zeo++ reference with consistent radii

The MOFDB values above are a convenient reference, but we do not control how MOFDB ran Zeo++ (probe, radii table, settings), so differences can be partly a radii or settings mismatch rather than a real difference between methods. To isolate the method from the radii, we also compare against a Zeo++ run where the radii are known.

The reference was generated for the same 216 IZA structures (the CIFs we just pulled from MOFDB) with Zeo++ using an explicit radii file passed with -r:

network -r mgr.rad -ha -res iza_entry.res iza_entry.cif

mgr.rad is a plain element radius table (Å). For the elements in all-silica IZA zeolites (Si, O) the radii are the Bondi/CRC values, which are also mofography’s default (default_vdw_radii_angstrom, the bondi_crc_fallback table). The LCD, PLD and LIS (Zeo++’s largest included sphere along the free path) from the .res files are stored in a small CSV, data/iza_zeopp_reference.csv, so this notebook needs no Zeo++ install.

Here we recompute with mofography at a 0.25 Å grid, passing the CRC radii explicitly so that both tools use the same atomic radii.

Show code
from mofography.vdw_radii import default_vdw_radii_angstrom

zeo_ref = pd.read_csv("data/iza_zeo_ha.csv").set_index("material")
print(zeo_ref.shape)
zeo_ref.head()
(216, 3)
lcd pld lis
material
ABW-0 3.61163 3.10046 3.61163
ACO-0 3.91932 3.15925 3.91898
AEI-0 6.90319 3.44131 6.90319
AEL-0 5.22554 4.07159 5.22554
AEN-0 3.90726 3.18878 3.90265
Show code
def get_pore_dia_winding_crc(mat_atoms, spacing=0.25):
    radii = default_vdw_radii_angstrom(mat_atoms)  # Bondi / CRC
    dgrid = mgr.dgrid_from_atoms_rust(mat_atoms, spacing=spacing, radii=radii).astype(np.float32)
    lcd, pld, lis, _ = mgr.get_pore_dia_mgr_winding(mat_atoms, dgrid=dgrid, kwargs=dict(spacing=spacing))
    return lcd, pld, lis

client = Client(processes=True)
futures = client.compute([delayed(get_pore_dia_winding_crc)(a) for a in iza_atoms])
iza_crc = [safe_result(f) for f in futures]
client.close()
print(f"{sum(d is not None for d in iza_crc)}/{len(iza_crc)} structures finished")
212/216 structures finished
Show code
names = iza_df["name"].values
ref = zeo_ref.loc[names]
res = pd.DataFrame({
    "name": names,
    **{f"{p}_mgr": [d[i] if d is not None else np.nan for d in iza_crc] for i, p in enumerate(["lcd", "pld", "lis"])},
    **{f"{p}_zeo": ref[p].values for p in ["lcd", "pld", "lis"]},
})

fig = make_subplots(rows=1, cols=3, subplot_titles=("(a) LCD", "(b) PLD", "(c) LIS"), horizontal_spacing=0.08)
for i, p in enumerate(["lcd", "pld", "lis"], 1):
    d = res.dropna(subset=[f"{p}_mgr", f"{p}_zeo"])
    x, y = d[f"{p}_mgr"], d[f"{p}_zeo"]
    r2, mae = r2_score(y, x), mean_absolute_error(y, x)
    lim = max(x.max(), y.max()) * 1.05
    fig.add_trace(go.Scatter(x=[0, lim], y=[0, lim], mode="lines", line=dict(color="black", width=1, dash="dash")), row=1, col=i)
    fig.add_trace(go.Scatter(x=x, y=y, mode="markers", text=d["name"],
                             marker=dict(size=9, line=dict(color="black", width=1))), row=1, col=i)
    fig.add_annotation(text=f"R\u00b2 = {r2:.3f}<br>MAE = {mae:.3f} \u00c5", x=0.05, y=0.95, showarrow=False, align="left",
                       xref="x domain" if i == 1 else f"x{i} domain", yref="y domain" if i == 1 else f"y{i} domain")
    fig.update_xaxes(title="MOFography, CRC radii (\u00c5)", range=[0, lim], mirror=True, showgrid=False, row=1, col=i)
    fig.update_yaxes(title="Zeo++ with mgr.rad (\u00c5)", range=[0, lim], mirror=True, showgrid=False, row=1, col=i)
fig.update_layout(template="simple_white", showlegend=False, width=1300, height=450, font=dict(family="Arial"))
fig.show()

With the radii matched and a 0.25 Å grid, mofography and Zeo++ agree closely for LCD and PLD, and LIS agrees well apart from a few structures. The residual scatter is the grid resolution of the voxel-based method (compare the 0.5 Å results above) and the different algorithms, not the radii.

Pick out outliers in LIS

Sorting by the absolute LIS difference picks out the structures where the two tools disagree most:

Show code
res["lis_abs_diff"] = (res["lis_mgr"] - res["lis_zeo"]).abs()
res.sort_values("lis_abs_diff", ascending=False).head(3)[["name", "lis_mgr", "lis_zeo", "lis_abs_diff"]]
name lis_mgr lis_zeo lis_abs_diff
108 LOS-0 3.660096 5.85558 2.195484
109 LOV-0 4.244981 3.73556 0.509421
55 EDI-0 4.444345 4.88186 0.437515

Why LIS can be off by 2 Å

LIS is the largest cavity a PLD-sized probe can reach. It changes in steps: once the probe is wider than the window of a cage, that cage drops out. If a cage sits behind a window close to the PLD, a small error in that window decides whether the cage counts, and LIS jumps between two cage sizes.

LOS-0 is the largest outlier. Its small cages (about 3.7 Å) are joined along c by 2.04 Å windows; its large cages (about 5.9 Å) are joined to each other by 6-rings of 2.15 Å (exact values). Zeo++ finds the large-cage network, so its PLD is 2.16 Å and its LIS is the large cage. On the grid the 6-rings come out too narrow, the large-cage network closes first, the PLD path moves to the small-cage channel, and LIS drops to the small cage.

The plot scans the probe size and records the largest cavity in any percolating network.

Show code
from mofography import winding_percolation as wp

def lis_vs_probe(atoms, spacing, probes):
    dgrid = mgr.dgrid_from_atoms_rust(atoms, spacing=spacing).astype(np.float32)
    res = mgr.do_periodic_segmentation_rust(dgrid, atoms, spacing=spacing, return_dgrid=True,
                                            return_padded_regions=True, **SEG_KWARGS)
    graph = wp.make_directed_graph_from_segmentation_results(res)
    base = wp.build_base_region_labels_from_results(res)
    regions = np.asarray(res["regions"])
    lis = []
    for d in probes:
        clusters, _, _ = wp.percolation_all_axes_winding(res, d / 2, graph=graph, base_region_labels=base,
                                                         include_dangling=True, expand_components=True)
        labels = {l for groups in clusters.values() for g in groups for l in g}
        lis.append(2 * dgrid[np.isin(regions, list(labels))].max() if labels else 0)
    return np.array(lis)
Show code
los = iza_atoms[list(iza_df["name"]).index("LOS-0")]
probes = np.arange(1.5, 2.3, 0.005)

fig = go.Figure()
for spacing in (0.5, 0.25):
    fig.add_trace(go.Scatter(x=probes, y=lis_vs_probe(los, spacing, probes), mode="lines",
                             line_shape="hv", name=f"mofography, {spacing} Å grid"))
z = zeo_ref.loc["LOS-0"]
fig.add_trace(go.Scatter(x=[z["pld"]], y=[z["lis"]], mode="markers",
                         marker=dict(size=10, color="black"), name="Zeo++ (PLD, LIS)"))
fig.update_layout(template="simple_white", width=700, height=450,
                  xaxis_title="probe diameter (Å)", yaxis_title="largest reachable cavity (Å)")
fig.show()

Each curve drops where a network closes. On the grid the large-cage network closes before the small-cage channel (1.80 vs 2.06 Å at 0.5 Å spacing, 2.02 vs 2.05 Å at 0.25 Å), so at the PLD only the small cages are left. In the exact geometry the order is reversed (2.15 vs 2.04 Å), which is what Zeo++ reports. A finer grid closes the gap; at 0.2 Å the large cages come back and LIS is 5.85 Å. Structures whose largest cage sits behind a window close to the PLD are the ones to check.

The other outliers can be checked the same way, or by loading their CIFs in the mofography web app.

CoRE-MOF 2019 (not executed here)

The same workflow scales to a CoRE-MOF 2019 subset (7506 MOFs with void fraction above 0.5 were used in our test). It is too heavy for the docs build, so the code is shown but not run. Fetch the subset from MOFDB first (see the MOFDB tutorial):

core_df = await mgr.get_data_from_mofdb(params={"database": "CoREMOF 2019", "vf_min": 0.5})
core_atoms = mgr.atoms_from_mofdb_df(core_df)
futures = client.compute([delayed(get_pore_dia_winding)(a) for a in core_atoms])
core_dias = [safe_result(f) for f in futures]

Then reuse the parity-plot cell above with core_df and core_dias.

Conclusions

  • Computed LCD and PLD for the 216 all-silica IZA zeolites with the winding method and compared them with the Zeo++ values tabulated in MOFDB.
  • Face merging was run for comparison only; the winding method is the standard.
  • A 0.5 Å grid is the default; a 0.25 Å grid improves R² and MAE against Zeo++, most clearly when the Zeo++ radii are matched.
  • Repeating the comparison against a Zeo++ run with known radii (-r mgr.rad, Bondi/CRC for Si and O) at a 0.25 Å grid separates radii effects from method differences.