Using AI based diffusive size factors for extracted networks#

This notebook illustrates the use of the deep learning based diffusive conductance algorithm decribed here. PoreSpy’s diffusive_size_factor_AI includes the steps for predicting the diffusive size factors of the conduit images. 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:


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: This file is used in this example to compare the prediction results with finite difference method for segmented regions

  • 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:

import os

if not os.path.exists("sf-model-zoo"):
    !git clone

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

import importlib
h5tools = importlib.import_module("sf-model-zoo.h5tools")
DIR_WEIGHTS = "sf-model-zoo/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 os
import warnings

import h5py
import numpy as np
import openpnm as op
import porespy as ps
import scipy as sp
from matplotlib import pyplot as plt
from sklearn.metrics import r2_score

path = "./sf-model-zoo/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()

Create test image#

We can create a 3D image using PoreSpy’s poly_disperese_spheres generator:

shape = [120, 120, 120]
dist = sp.stats.norm(loc=7, scale=5)
im = ps.generators.polydisperse_spheres(shape=shape,
fig, ax = plt.subplots(1, 1, figsize=[4, 4])
ax.imshow(im[:, :, 20], origin='lower', interpolation='none')

Extract the network#

We then extract the pore network of the porous medium image using PoreSpy’s snow2 algorithm. snow2 returns the segmented image of the porous medium as well as extracted network data.

snow = ps.networks.snow2(im, boundary_width=0, parallelization=None)
regions = snow.regions
net =

Apply diffusive_size_factor_AI#

AI_based diffusive size factors of conduits in the extracted network can then be calculated applying diffusive_size_factor_AI on the segmented regions. We can then define throat.diffusive_size_factor_AI property and assign the predicted size_factor to this property.

conns = net['throat.conns']
size_factors = ps.networks.diffusive_size_factor_AI(regions,
net['throat.diffusive_size_factor_AI'] = size_factors

The resulting network can then be imported to OpenPNM for later use such as diffusive mass transport simulations problems. Let’s visualize the network:

    pn, geo =
except AttributeError:
    pn, geo =
fig, ax = plt.subplots(1, 1, figsize=[5, 5])
ax = op.topotools.plot_connections(network=pn, alpha=0.8, color='grey', ax=ax)
ax = op.topotools.plot_coordinates(network=pn, ax=ax, color='b', markersize=50)

Compare with finite difference method#

Now that the extracted network includes AI_based diffusive size factor data, we can use the network to compare the accuracy of diffusive_size_factor_AI, shape factor method,and geometry method (no shape factor) in contrast to finite difference method. Assuming a generic phase with diffusivity of 1, the diffusive conductance of the conduits will be equal to their diffusive size factors. The diffusive conductance of the conduits can be calculated using OpenPNM’s generic_diffusive method. The diffusive conductance of the conduits using shape factor based method assuming cones and cylinders shapes for pores and throats can be calculated as follows:

    phase = op.phases.GenericPhase(network=pn)
except AttributeError:
    phase = op.phase.GenericPhase(network=pn)
phys = op.physics.GenericPhysics(network=pn, phase=phase, geometry=geo)
phase['pore.diffusivity'] = 1
phase['throat.diffusivity'] = 1
g_SF = phys['throat.diffusive_conductance']

To find the diffusive conductance of the conduit using geometry method (no shape factor) we assume cylindrical pores and throats:

cn = pn.conns
L1, Lt, L2 = geo['pore.diameter'][
    cn[:, 0]] / 2, geo['throat.length'], geo['pore.diameter'][cn[:, 1]] / 2
D1, Dt, D2 = geo['pore.diameter'][
    cn[:, 0]], geo['throat.diameter'], geo['pore.diameter'][cn[:, 1]]
A1, At, A2 = np.pi * D1**2 / 4, np.pi * Dt**2 / 4, np.pi * D2**2 / 4
g_Geo = 1 / (L1 / A1 + L2 / A2 + Lt / At)

The diffusive conductance of the conduit using AI-based method:

g_AI = phys['throat.diffusive_conductance']

Now let’s compare the diffusive conductance calculated from geometry-based method, shape factor based-method, and AI-based method with reference finite difference method. he reference diffusive conductance values for comparisons are calculated using finite difference method explained here and saved in the example data folder.

fname = os.path.join(path, 'g_finite_difference120-phi7.hdf5')
g_FD = h5py.File(fname, 'r')['g_finite_difference'][()]

fig, ax = plt.subplots(1, 3, figsize=[10, 4])

ax[0].plot(g_FD, g_Geo, '*', [0, 80], [0, 80], 'r')
ax[0].set_xlim([0, 80])
ax[0].set_ylim([0, 80])
ax[0].set_xlabel('finite difference $g_d$')
ax[0].set_ylabel('geometry based $g_d$')
ax[0].set_title('$R^2$ = ' + str(np.round(r2_score(g_FD, g_Geo), 2)))

ax[1].plot(g_FD, g_SF, '*', [0, 80], [0, 80], 'r')
ax[1].set_xlim([0, 80])
ax[1].set_ylim([0, 80])
ax[1].set_xlabel('finite difference $g_d$')
ax[1].set_ylabel('shape factor based $g_d$')
ax[1].set_title('$R^2$ = ' + str(np.round(r2_score(g_FD, g_SF), 2)))

ax[2].plot(g_FD, g_AI, '*', [0, 80], [0, 80], 'r')
ax[2].set_xlim([0, 80])
ax[2].set_ylim([0, 80])
ax[2].set_xlabel('finite difference $g_d$')
ax[2].set_ylabel('AI based $g_d$')
ax[2].set_title(r'$R^2$ = ' + str(np.round(r2_score(g_FD, g_AI), 2)));

As shown in the scatter plots, the AI-based diffusive conductance method predicts the conductance values with a higher accuracy than geometry-based and shape factor-based methods. A comprehensive comparison between these methods for a large dataset can be found here.