# diffusive_size_factor_AI#

PoreSpy’s diffusive_size_factor_AI includes the steps for predicting the diffusive size factors of the conduit images decribed 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.

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

[1]:

import os

if not os.path.exists("sf-model-zoo"):
!git clone https://github.com/PMEAL/sf-model-zoo


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

[2]:

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:

[3]:

import inspect
import os
import warnings

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

ps.visualization.set_mpl_style()
warnings.filterwarnings("ignore")
inspect.signature(ps.networks.diffusive_size_factor_AI)

[3]:

<Signature (regions, throat_conns, model, g_train, voxel_size=1)>


## model , g_train#

[4]:

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()


## regions#

We can create a 3D image using PoreSpy’s poly_disperese_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.

[5]:

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);


## throat_conns#

PoreSpy’s diffusive_size_factor_AI method takes in the segmented image, model, training ground truth values, and the conncetions 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.

[6]:

conns = ps.networks.find_conns(regions)
size_factors = ps.networks.diffusive_size_factor_AI(regions,
model=model,
g_train=g_train,
throat_conns=conns)


## Compare with finite difference#

Assuming a diffusivity of 1, the diffusive conductance of the conduits will be equal to their diffusive size factors. Now let’s compare the AI-based diffusive conductances with the conductance values calculated by finite difference method. The finite difference method results are found using the steps explained here.

[7]:

fname = os.path.join(path, 'g_finite_difference120-phi7.hdf5')
g_FD = h5py.File(fname, 'r')['g_finite_difference'][()]
g_AI = size_factors
plt.figure(figsize=[4, 4])
plt.xlim([0, 80])
plt.ylim([0, 80])
plt.plot(g_FD, g_AI, '*', [0, 80], [0, 80], 'r')
plt.xlabel('g reference')
plt.ylabel('g prediction')
r2 = r2_score(g_FD, g_AI)
print(f"The R^2 prediction accuracy is {r2:.3}")

The R^2 prediction accuracy is 0.952


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 here.

## Apply on one conduit#

PoreSpy’s diffusive_size_factor_AI method can take in an image of a pair of regions. An image of a conduit and its diffusive size factor was saved for comparison:

[8]:

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 = pair_in['size_factor'][()]
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}")

Diffusive size factor from FD: 9.87, and AI: 9.91