Show code
import os
os.environ["RAYON_NUM_THREADS"] = "8"
import pandas as pd
import mofography as mgr
from ase.io import read
import numpy as npThis tutorial demonstrates how to compute pore-structure properties of a hyper-crosslinked polymer (HCP) with mofography. Using the 75X_0DVB_4 structure as an example, it builds a periodic pore graph and computes the largest cavity diameter, pore limiting diameter, N₂ accessible surface area, percolating pore volume, average pore and window sizes, pore connectivity, percolating backbone fraction, and fractional free volume.
The structure is taken from https://doi.org/10.1021/acs.jctc.2c00798
For detailed definitions of these properties, see our paper about methane diffusion: Zheng, C.; Gopalan, A.; Shi, K. Revisiting Percolation and Molecular Diffusion in Disordered Pore Networks (https://doi.org/10.26434/chemrxiv.15011012/v1). Requirements
The workflow has six steps:
Limit Rust to eight threads (change this to match your machine), then import the libraries.
This polymer is modelled with united-atom sites, so the default Bondi radii do not apply. Instead each atom type gets half its TraPPE Lennard-Jones sigma as its radius.
Next, the distance grid and segmentation parameters. The spacing is the voxel size of the distance grid. h, threshold_abs, min_distance and min_region_size control which local maxima become pockets. preserve_threshold, smooth_threshold and max_smooth_radius control selective smoothing. extra_padding sets the padding around the cell for periodic segmentation, and minimum_window_separation the minimum distance between windows. See Tuning and safe ranges for what each one does.
The two probe radii are the methane probe (half the TraPPE sigma of CH₄), used for percolation, and the N₂ probe, used for the accessible surface area.
spacing = 0.5
mask_thickness = 0.0
h = 0.1
threshold_abs = 0.3
min_region_size = 0.00005
preserve_threshold = 103.0
smooth_threshold = 106.0
max_smooth_radius = 2.0
extra_padding = 2
min_distance = 1.0
minimum_window_separation = 1.5
# probe radii (Å)
probe_radius = 1.865 # CH4 (TraPPE sigma / 2), for percolation analysis
n2_probe_radius = 1.82 # N2, for accessible surface areaThe pore graph does not carry volumes or per-pore connectivity by default, so three helpers add them as node attributes.
add_volume_to_graph stores the cell volume (in litres) on every node. add_pixel_ratio_to_graph counts the voxels of each pocket and stores the fraction of the whole grid that pocket occupies. That fraction is later summed to get pore volumes.
def add_volume_to_graph(graph, mat_atoms):
vol = mat_atoms.get_volume()
vol_L=vol/(1E27)
for i in graph.nodes():
graph.nodes[i]['cell_volume']=vol_L
return graph
def add_pixel_ratio_to_graph(graph, regions_pbc):
n=regions_pbc.size
for i in graph.nodes():
pixel_counts = np.count_nonzero(regions_pbc == i)
graph.nodes[i]['pixel_counts']=pixel_counts
graph.nodes[i]['total_pixel_amounts']=n
graph.nodes[i]['pixel_ratio']=pixel_counts/n
return graphadd_connectivities_to_nodes looks at all windows (edges) touching each pore. For each pore it records the number of windows (the connectivity), the average and minimum window radius, the average window-to-pore radius ratio, and the clearance of the windows relative to the probe (window radius minus probe radius). It also stores each of these multiplied by the connectivity, which the weighted averages below use.
def add_connectivities_to_nodes(
graph,
probe_radius,
pore_radius_attr="pocket_radius",
pixel_count_attr="pixel_counts",
edge_radius_attr="window_radius",
):
for node in graph.nodes():
edges = {
(u, v, key): data
for u, v, key, data in (
list(graph.in_edges(node, keys=True, data=True))
+ list(graph.out_edges(node, keys=True, data=True))
)
}
connectivity = len(edges)
if connectivity == 0:
continue
radii = np.array([
float(data[edge_radius_attr])
for data in edges.values()
])
pore_radius = float(graph.nodes[node][pore_radius_attr])
pixel_count = float(graph.nodes[node][pixel_count_attr])
avg_radius = float(np.mean(radii))
min_radius = float(np.min(radii))
clearances = radii - probe_radius
avg_clearance = float(np.mean(clearances))
graph.nodes[node]["connectivity"] = connectivity
graph.nodes[node]["pixel_count_times_connectivity"] = pixel_count * connectivity
graph.nodes[node]["avg_window_radius"] = avg_radius
graph.nodes[node]["avg_window_pore_ratio"] = avg_radius / pore_radius
graph.nodes[node]["avg_radius_times_connectivity"] = connectivity * avg_radius
graph.nodes[node]["min_window_radius"] = min_radius
graph.nodes[node]["min_radius_times_connectivity"] = connectivity * min_radius
graph.nodes[node]["avg_window_clearance"] = avg_clearance
graph.nodes[node]["clearance_times_connectivity"] = connectivity * avg_clearance
return graphRead the CIF with store_tags=True so the atom site labels (C1, C2, …) are kept. Look up each atom’s radius from its label and compute the distance grid with these radii. The grid stores, for every voxel, the distance to the nearest framework surface.
Run the watershed segmentation with periodic boundary conditions. It splits the pore space into pockets, merges the pieces that touch across cell boundaries, and finds the windows between neighbouring pockets (compute_connections=True). The result is one dictionary.
results = mgr.do_periodic_segmentation_rust(
dgrid,
mat_atoms,
mask_thickness=mask_thickness,
h=h,
spacing=spacing,
return_dgrid=False,
threshold_abs=threshold_abs,
min_distance=min_distance,
return_padded_regions=True,
preserve_threshold=preserve_threshold,
smooth_threshold=smooth_threshold,
max_smooth_radius=max_smooth_radius,
extra_padding=extra_padding,
compute_connections=True,
min_region_size=min_region_size,
minimum_window_separation=minimum_window_separation,
watershed_backend="rust_det",
)Pull out the pieces used below: the label grid for the unit cell (regions), the periodic label grid (regions_pbc), the list of windows (connections), and the maxima. Voxels labelled 0 are framework atoms, which is used later for the free volume.
Each node is a pore in the unit cell, and each edge is one window between two pores. Only windows between pores that own part of the original unit cell are kept, so every window is counted once. Windows that cross the cell boundary are kept as edges with a non-zero relative_offset.
The largest cavity diameter is twice the largest value in the distance grid, whether or not that cavity is reachable from outside.
The pore limiting radius is the largest probe radius that can still travel through the periodic network (winding-number percolation). The diameter is twice that.
Surface area is estimated by Monte Carlo sampling on a shell around the framework (50,000 samples). Only sample points that the N₂ probe can reach through the percolating network count as accessible. The seed makes the number reproducible.
# N2-accessible surface area (m²/g): surface area accessible to an N2-sized probe in the percolating pore network
np.random.seed(0)
n2_asa = (mgr.compute_surface_area_mc_winding(
results,
mat_atoms,
probe_radius=n2_probe_radius,
n_samples=50000,
shell_thickness=1,
return_details=False,
window_fp=False,
winding_kwargs=None,
)["accessible_surface_area"]
)Keep only the pores and windows that a methane-sized probe can use to cross the cell. Two versions are extracted:
Connectivity data is added to each version.
# Methane-accessible percolating pore network
# before pruning: the whole percolating network, including self-loops and dangling branches
# after pruning: only the shortest percolating backbone pathways
percolation_pore_graph_before_pruning = (mgr.extract_percolating_pore_graph(graph,threshold=probe_radius,expand_components=True,include_dangling=True))
percolation_pore_graph_before_pruning = (add_connectivities_to_nodes(percolation_pore_graph_before_pruning,probe_radius=probe_radius))
percolation_pore_graph_after_pruning = (mgr.extract_percolating_pore_graph(graph,threshold=probe_radius,expand_components=False,include_dangling=False))
percolation_pore_graph_after_pruning = (add_connectivities_to_nodes(percolation_pore_graph_after_pruning,probe_radius=probe_radius))The pore volume fraction is the sum of the voxel fractions of the pores in the percolating network. Dividing by the framework bulk density turns it into a gravimetric pore volume in cm³/g.
Average the pore radius, the mean window radius per pore, and the window-to-pore radius ratio over the pores in the percolating network.
# Average percolating pore radius (Å): mean radius of the pores in the percolating network
average_pore_radius = np.mean([percolation_pore_graph_before_pruning.nodes[n]["pocket_radius"] for n in percolation_pore_graph_before_pruning.nodes()])
# Average accessible window radius (Å): for each pore, the mean radius of the accessible windows connected to it,
# averaged over all pores in the percolating network
average_accessible_window_radius = np.mean([percolation_pore_graph_before_pruning.nodes[n]["avg_window_radius"] for n in percolation_pore_graph_before_pruning.nodes()])
# Average window-to-pore radius ratio: mean of (average radius of the windows connected to a pore / radius of that pore)
w_to_p = np.mean([percolation_pore_graph_before_pruning.nodes[n]["avg_window_radius"] / percolation_pore_graph_before_pruning.nodes[n]["pocket_radius"] for n in percolation_pore_graph_before_pruning.nodes()])The plain average connectivity counts windows per pore. The window-size-weighted version gives more weight to pores with wide windows.
# Average pore connectivity: average number of accessible windows connected to each pore
average_connectivity = np.mean([percolation_pore_graph_before_pruning.nodes[n]["connectivity"]for n in percolation_pore_graph_before_pruning.nodes()])
# Average-window-radius-weighted connectivity = sum_i(c_i * r_w,i) / sum_i(r_w,i),
# where c_i is the connectivity of pore i and r_w,i is the mean radius of its accessible windows
average_window_size_weighted_connectivity = (sum(percolation_pore_graph_before_pruning.nodes[n]["avg_radius_times_connectivity"]for n in percolation_pore_graph_before_pruning.nodes())/sum(percolation_pore_graph_before_pruning.nodes[n]["avg_window_radius"]for n in percolation_pore_graph_before_pruning.nodes()))The backbone fraction compares the pore volume of the shortest percolating pathways to that of the whole percolating network. A low value means most of the percolating volume sits in side branches and dead ends.
# Percolating backbone fraction = n_b / n_p: grid points in the shortest percolating backbone
# divided by grid points in the whole percolating network
percolating_pore_volume_fraction_backbone=sum(percolation_pore_graph_after_pruning.nodes[node]["pixel_ratio"]for node in percolation_pore_graph_after_pruning.nodes())
fB=percolating_pore_volume_fraction_backbone/percolating_pore_volume_fractionVoxels labelled 0 belong to the framework. The fractional free volume uses their share of the grid together with the 1.3 factor from the cited definition.
All properties in one table.
summary = pd.DataFrame(
[
["Largest cavity diameter (LCD)", lcd, "Å"],
["Pore limiting diameter (PLD)", pld, "Å"],
["N₂-accessible surface area", n2_asa, "m²/g"],
["Percolating pore volume fraction", percolating_pore_volume_fraction, "–"],
["Percolating gravimetric pore volume", percolating_gravimetric_pore_volume, "cm³/g"],
["Average percolating pore radius", average_pore_radius, "Å"],
["Average accessible window radius", average_accessible_window_radius, "Å"],
["Average window-to-pore radius ratio", w_to_p, "–"],
["Average pore connectivity", average_connectivity, "–"],
["Average-window-radius-weighted connectivity", average_window_size_weighted_connectivity, "–"],
["Percolating backbone fraction (fB)", fB, "–"],
["Fractional free volume (FFV)", ffv, "–"],
],
columns=["Property", "Value", "Unit"],
)
summary| Property | Value | Unit | |
|---|---|---|---|
| 0 | Largest cavity diameter (LCD) | 9.163111 | Å |
| 1 | Pore limiting diameter (PLD) | 4.072923 | Å |
| 2 | N₂-accessible surface area | 835.987770 | m²/g |
| 3 | Percolating pore volume fraction | 0.257681 | – |
| 4 | Percolating gravimetric pore volume | 0.314245 | cm³/g |
| 5 | Average percolating pore radius | 3.154000 | Å |
| 6 | Average accessible window radius | 2.521294 | Å |
| 7 | Average window-to-pore radius ratio | 0.815319 | – |
| 8 | Average pore connectivity | 2.692308 | – |
| 9 | Average-window-radius-weighted connectivity | 2.802774 | – |
| 10 | Percolating backbone fraction (fB) | 0.294555 | – |
| 11 | Fractional free volume (FFV) | 0.328138 | – |