diffusive_size_factor_AI#

PoreSpy’s diffusive_size_factor_AI includes the steps for predicting the diffusive size factors of the conduit images described here. Note that the diffusive conductance of the conduits can be then calculated by multiplying the size factor by diffusivity of the phase. The function takes in the images of segmented porous medium and returns an array of diffusive size factors for all conduits in the image. Therefore, the framework can be applied to both one conduit image as well as a segmented image of porous medium.

PS_dl

Trained model and supplementary materials#

To use the diffusive_size_factor_AI, the trained model, and training data distribution are required. The AI model files and additional files used in this example are available here. The folder contains following files:

  • Trained model weights: This file includes only weights of the deep learning layers. To use this file, the Resnet50 model structure must be built first.

  • Trained data distribution: This file will be used in denormalizing predicted values based on normalized transform applied on training data. The denormalizing step is included in diffusive_size_factor_AI method.

  • Finite difference diffusive conductance: Archived reference values for the original segmented image. This example recomputes reference values for its selected connections instead of using this file

  • Pair of regions: This file is used in this example to compare the prediction results with finite difference method for a pair of regions

Let’s download the tensorflow files required to run this notebook:

try:
    import tensorflow as tf
except ImportError:
    !pip install tensorflow

try:
    import sklearn
except ImportError:
    !pip install scikit-learn

import os

if not os.path.exists("sf-model-lib"):
    !git clone https://github.com/PMEAL/sf-model-lib
2026-11-26 04:15:31.453554: I external/local_xla/xla/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
2026-11-26 04:15:31.453886: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2026-11-26 04:15:31.507280: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 AVX512F AVX512_VNNI AVX512_BF16 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2026-11-26 04:15:33.017683: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2026-11-26 04:15:33.020273: I external/local_xla/xla/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
Cloning into 'sf-model-lib'...
remote: Enumerating objects: 36, done.
remote: Counting objects:  20% (1/5)
remote: Counting objects:  40% (2/5)
remote: Counting objects:  60% (3/5)
remote: Counting objects:  80% (4/5)
remote: Counting objects: 100% (5/5)
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects:  20% (1/5)
remote: Compressing objects:  40% (2/5)
remote: Compressing objects:  60% (3/5)
remote: Compressing objects:  80% (4/5)
remote: Compressing objects: 100% (5/5)
remote: Compressing objects: 100% (5/5), done.
Receiving objects:   2% (1/36)
Receiving objects:   5% (2/36)
Receiving objects:   8% (3/36)
Receiving objects:  11% (4/36)
Receiving objects:  13% (5/36)
Receiving objects:  16% (6/36)
Receiving objects:  16% (6/36), 31.35 MiB | 31.30 MiB/s
Receiving objects:  16% (6/36), 77.02 MiB | 38.44 MiB/s
Receiving objects:  19% (7/36), 77.02 MiB | 38.44 MiB/s
Receiving objects:  19% (7/36), 117.94 MiB | 39.23 MiB/s
Receiving objects:  19% (7/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  22% (8/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  25% (9/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  27% (10/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  30% (11/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  33% (12/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  36% (13/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  38% (14/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  41% (15/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  44% (16/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  47% (17/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  50% (18/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  52% (19/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  55% (20/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  58% (21/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  61% (22/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  63% (23/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  66% (24/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  69% (25/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  72% (26/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  75% (27/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  77% (28/36), 162.69 MiB | 40.61 MiB/s
Receiving objects:  77% (28/36), 204.77 MiB | 42.73 MiB/s
Receiving objects:  77% (28/36), 238.41 MiB | 41.21 MiB/s
Receiving objects:  80% (29/36), 252.34 MiB | 38.91 MiB/s
Receiving objects:  80% (29/36), 272.65 MiB | 37.96 MiB/s
Receiving objects:  80% (29/36), 322.38 MiB | 40.28 MiB/s
remote: Total 36 (delta 0), reused 2 (delta 0), pack-reused 31 (from 1)
Receiving objects:  83% (30/36), 322.38 MiB | 40.28 MiB/s
Receiving objects:  86% (31/36), 322.38 MiB | 40.28 MiB/s
Receiving objects:  88% (32/36), 322.38 MiB | 40.28 MiB/s
Receiving objects:  91% (33/36), 322.38 MiB | 40.28 MiB/s
Receiving objects:  94% (34/36), 322.38 MiB | 40.28 MiB/s
Receiving objects:  97% (35/36), 322.38 MiB | 40.28 MiB/s
Receiving objects: 100% (36/36), 322.38 MiB | 40.28 MiB/s
Receiving objects: 100% (36/36), 334.57 MiB | 40.06 MiB/s, done.
Resolving deltas:   0% (0/8)
Resolving deltas:  12% (1/8)
Resolving deltas:  25% (2/8)
Resolving deltas:  37% (3/8)
Resolving deltas:  50% (4/8)
Resolving deltas:  62% (5/8)
Resolving deltas:  75% (6/8)
Resolving deltas:  87% (7/8)
Resolving deltas: 100% (8/8)
Resolving deltas: 100% (8/8), done.
Updating files:  62% (5/8)
Updating files:  75% (6/8)
Updating files:  87% (7/8)
Updating files: 100% (8/8)
Updating files: 100% (8/8), done.

Also, since the model weights have been stored in chunks, they need to be recombined first:

import importlib

h5tools = importlib.import_module("sf-model-lib.h5tools")
DIR_WEIGHTS = "sf-model-lib/diffusion"
fname_in = [f"{DIR_WEIGHTS}/model_weights_part{j}.h5" for j in [0, 1]]
h5tools.combine(fname_in, fname_out=f"{DIR_WEIGHTS}/model_weights.h5")

Note that to use diffusive_size_factor_AI, Scikit-learn and Tensorflow must be installed. Import necessary packages and the AI model:

import inspect
import os
import warnings

import h5py
import numpy as np
import scipy as sp
from matplotlib import pyplot as plt
from sklearn.metrics import r2_score

import porespy as ps

ps.visualization.set_mpl_style()
warnings.filterwarnings("ignore")
inspect.signature(ps.networks.diffusive_size_factor_AI)
<Signature (regions, throat_conns, model, g_train, voxel_size=1)>

model , g_train#

Import AI model and training data from the downloaded folder:

path = "./sf-model-lib/diffusion"
path_train = os.path.join(path, "g_train_original.hdf5")
path_weights = os.path.join(path, "model_weights.h5")
g_train = h5py.File(path_train, "r")["g_train"][()]
model = ps.networks.create_model()
model.load_weights(path_weights)
2026-11-26 04:15:49.815252: E external/local_xla/xla/stream_executor/cuda/cuda_platform.cc:51] failed call to cuInit: INTERNAL: CUDA error: Failed call to cuInit: UNKNOWN ERROR (303)

regions#

We can create a 3D image using PoreSpy’s polydisperse_spheres generator and segment the image using snow_partitioning method. Note that find_conns method returns the connections in the segmented region. The order of values in conns is similar to the network extraction conns. Therefore, the region with label=1 in the segmented image is mapped to indice 0 in conns.

np.random.seed(17)
shape = [120, 120, 120]
dist = sp.stats.norm(loc=7, scale=5)
im = ps.generators.polydisperse_spheres(shape=shape, porosity=0.7, dist=dist, r_min=7)
results = ps.filters.snow_partitioning(im=im.astype(bool))
regions = results["regions"]
fig, ax = plt.subplots(1, 1, figsize=[4, 4])
ax.imshow(regions[:, :, 20], origin="lower", interpolation="none")
ax.axis(False);
../../../_images/06c32aea3156fab4356083f84cfd47445c62b5b70c123557202b69d9954f7d50.png

throat_conns#

PoreSpy’s diffusive_size_factor_AI method takes in the segmented image, model, training ground truth values, and the connections of regions in the segmented image (throat conns). In this example we have created an image with voxel_size=1. For a different voxel size, the voxel_size argument needs to be passed to the method.

To keep this demonstration small enough to run during the documentation build, we predict the first eight connections. Pass the full connection list to process the entire image. The finite-difference comparison below uses these same connections from this same generated image.

conns = ps.networks.find_conns(regions)[:8]
size_factors = ps.networks.diffusive_size_factor_AI(
    regions, model=model, g_train=g_train, throat_conns=conns
)
1/8 ━━━━━━━━━━━━━━━━━━━━ 9s 1s/step

2/8 ━━━━━━━━━━━━━━━━━━━━ 1s 185ms/step

3/8 ━━━━━━━━━━━━━━━━━━━━ 0s 198ms/step

4/8 ━━━━━━━━━━━━━━━━━━━━ 0s 195ms/step

5/8 ━━━━━━━━━━━━━━━━━━━━ 0s 189ms/step

6/8 ━━━━━━━━━━━━━━━━━━━━ 0s 187ms/step

7/8 ━━━━━━━━━━━━━━━━━━━━ 0s 185ms/step

8/8 ━━━━━━━━━━━━━━━━━━━━ 0s 183ms/step

8/8 ━━━━━━━━━━━━━━━━━━━━ 3s 184ms/step

Compare with finite difference#

Assuming a diffusivity of 1, the diffusive conductance of the conduits will be equal to their diffusive size factors. Compare the AI predictions with finite-difference values computed for the same eight conduits. This small subset illustrates the API; it is not an accuracy benchmark.

We calculate the reference values here with diffusive_size_factor_DNS. The archived g_finite_difference120-phi7.hdf5 values correspond to an earlier generated image and must not be paired with a new segmentation: changes in dependencies can change the regions and connection ordering even with a fixed random seed. Limiting the comparison to eight connections keeps the finite-difference calculation manageable.

g_FD = ps.networks.diffusive_size_factor_DNS(regions, throat_conns=conns)
g_AI = size_factors
max_val = np.max([g_FD, g_AI])
plt.figure(figsize=[4, 4])
plt.plot(g_FD, g_AI, "*", [0, max_val], [0, max_val], "r")
plt.xlabel("g reference")
plt.ylabel("g prediction")
r2 = r2_score(g_FD, g_AI)
print(f"R^2 for this {len(conns)}-conduit demonstration: {r2:.3}")
R^2 for this 8-conduit demonstration: 0.87
../../../_images/26751e99cc42d353dffaa8d7b6feaf2783286ad28e58d24273342b363ea029cb.png

Note on runtime: A larger part of AI_size_factors runtime is related to extracting the pairs of conduits, which is the common step required for both AI and finite difference method. Once the data is prepared, AI Prediction on the tensor takes a smaller amount of time in contrast to finite difference method, as it was shown in the cited reference paper.

Apply on one conduit#

PoreSpy’s diffusive_size_factor_AI method can take in an image of a pair of regions. Let’s predict the diffusive size factor for a pair of image using both AI and DNS methods:

fname = os.path.join(path, "pair.hdf5")
pair_in = h5py.File(fname, "r")
im_pair = pair_in["pair"][()]
conns = ps.networks.find_conns(im_pair)
sf_FD = ps.networks.diffusive_size_factor_DNS(im_pair, throat_conns=conns)
sf_AI = ps.networks.diffusive_size_factor_AI(
    im_pair, model=model, g_train=g_train, throat_conns=conns
)
print(f"Diffusive size factor from FD: {sf_FD[0]:.2f}, and AI: {sf_AI[0]:.2f}")
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 1s/step

1/1 ━━━━━━━━━━━━━━━━━━━━ 1s 1s/step
Diffusive size factor from FD: 8.39, and AI: 8.47