Ejemplo n.º 1
0
def snow_n(im,
           voxel_size=1,
           boundary_faces=['top', 'bottom', 'left', 'right', 'front', 'back'],
           marching_cubes_area=False,
           alias=None):
    r"""
    Analyzes an image that has been segemented into N phases and extracts all
    a network for each of the N phases, including geometerical information as
    well as network connectivity between each phase.

    Parameters
    ----------
    im : ND-array
        Image of porous material where each phase is represented by unique
        integer. Phase integer should start from 1 (0 is ignored)

    voxel_size : scalar
        The resolution of the image, expressed as the length of one side of a
        voxel, so the volume of a voxel would be **voxel_size**-cubed.  The
        default is 1, which is useful when overlaying the PNM on the original
        image since the scale of the image is always 1 unit lenth per voxel.

    boundary_faces : list of strings
        Boundary faces labels are provided to assign hypothetical boundary
        nodes having zero resistance to transport process. For cubical
        geometry, the user can choose ‘left’, ‘right’, ‘top’, ‘bottom’,
        ‘front’ and ‘back’ face labels to assign boundary nodes. If no label is
        assigned then all six faces will be selected as boundary nodes
        automatically which can be trimmed later on based on user requirements.

    marching_cubes_area : bool
        If ``True`` then the surface area and interfacial area between regions
        will be calculated using the marching cube algorithm. This is a more
        accurate representation of area in extracted network, but is quite
        slow, so it is ``False`` by default.  The default method simply counts
        voxels so does not correctly account for the voxelated nature of the
        images.

    alias : dict (Optional)
        A dictionary that assigns unique image label to specific phases. For
        example {1: 'Solid'} will show all structural properties associated
        with label 1 as Solid phase properties. If ``None`` then default
        labelling will be used i.e {1: 'Phase1',..}.

    Returns
    -------
    A dictionary containing all N phases size data, as well as the
    network topological information.  The dictionary names use the OpenPNM
    convention (i.e. 'pore.coords', 'throat.conns') so it may be converted
    directly to an OpenPNM network object using the ``update`` command.
    """
    # -------------------------------------------------------------------------
    # Get alias if provided by user
    al = _create_alias_map(im, alias=alias)
    # -------------------------------------------------------------------------
    # Perform snow on each phase and merge all segmentation and dt together
    snow = snow_partitioning_n(im,
                               r_max=4,
                               sigma=0.4,
                               return_all=True,
                               mask=True,
                               randomize=False,
                               alias=al)
    # -------------------------------------------------------------------------
    # Add boundary regions
    f = boundary_faces
    regions = add_boundary_regions(regions=snow.regions, faces=f)
    # -------------------------------------------------------------------------
    # Padding distance transform to extract geometrical properties
    dt = pad_faces(im=snow.dt, faces=f)
    # -------------------------------------------------------------------------
    # For only one phase extraction with boundary regions
    phases_num = np.unique(im).astype(int)
    phases_num = np.trim_zeros(phases_num)
    if len(phases_num) == 1:
        if f is not None:
            snow.im = pad_faces(im=snow.im, faces=f)
        regions = regions * (snow.im.astype(bool))
        regions = make_contiguous(regions)
    # -------------------------------------------------------------------------
    # Extract N phases sites and bond information from image
    net = regions_to_network(im=regions, dt=dt, voxel_size=voxel_size)
    # -------------------------------------------------------------------------
    # Extract marching cube surface area and interfacial area of regions
    if marching_cubes_area:
        areas = region_surface_areas(regions=regions)
        interface_area = region_interface_areas(regions=regions,
                                                areas=areas,
                                                voxel_size=voxel_size)
        net['pore.surface_area'] = areas * voxel_size**2
        net['throat.area'] = interface_area.area
    # -------------------------------------------------------------------------
    # Find interconnection and interfacial area between ith and jth phases
    net = add_phase_interconnections(net=net,
                                     snow_partitioning_n=snow,
                                     marching_cubes_area=marching_cubes_area,
                                     alias=al)
    # -------------------------------------------------------------------------
    # label boundary cells
    net = label_boundary_cells(network=net, boundary_faces=f)
    # -------------------------------------------------------------------------

    temp = _net_dict(net)
    temp.im = im.copy()
    temp.dt = dt
    temp.regions = regions
    return temp
Ejemplo n.º 2
0
def add_phase_interconnections(net,
                               snow_partitioning_n,
                               voxel_size=1,
                               marching_cubes_area=False,
                               alias=None):
    r"""
    This function connects networks of two or more phases together by
    interconnecting neighbouring nodes inside different phases.

    The resulting network can be used for the study of transport and kinetics
    at interphase of two phases.

    Parameters
    ----------
    network : 2D or 3D network
        A dictoionary containing structural information of two or more
        phases networks. The dictonary format must be same as porespy
        region_to_network function.

    snow_partitioning_n : tuple
        The output generated by snow_partitioning_n function. The tuple should
        have phases_max_labels and original image of material.

    voxel_size : scalar
        The resolution of the image, expressed as the length of one side of a
        voxel, so the volume of a voxel would be **voxel_size**-cubed.  The
        default is 1, which is useful when overlaying the PNM on the original
        image since the scale of the image is alway 1 unit lenth per voxel.

    marching_cubes_area : bool
        If ``True`` then the surface area and interfacial area between regions
        will be causing the marching cube algorithm. This is a more accurate
        representation of area in extracted network, but is quite slow, so
        it is ``False`` by default.  The default method simply counts voxels
        so does not correctly account for the voxelated nature of the images.

    alias : dict (Optional)
        A dictionary that assigns unique image label to specific phase.
        For example {1: 'Solid'} will show all structural properties associated
        with label 1 as Solid phase properties.
        If ``None`` then default labelling will be used i.e {1: 'Phase1',..}.

    Returns
    -------
    A dictionary containing network information of individual and connected
    networks. The dictionary names use the OpenPNM convention so it may be
    converted directly to an OpenPNM network object using the ``update``
    command.

    """
    # -------------------------------------------------------------------------
    # Get alias if provided by user
    im = snow_partitioning_n.im
    al = _create_alias_map(im, alias=alias)
    # -------------------------------------------------------------------------
    # Find interconnection and interfacial area between ith and jth phases
    conns1 = net['throat.conns'][:, 0]
    conns2 = net['throat.conns'][:, 1]
    label = net['pore.label'] - 1

    num = snow_partitioning_n.phase_max_label
    num = [0, *num]
    phases_num = np.unique(im * 1)
    phases_num = np.trim_zeros(phases_num)
    for i in phases_num:
        loc1 = np.logical_and(conns1 >= num[i - 1], conns1 < num[i])
        loc2 = np.logical_and(conns2 >= num[i - 1], conns2 < num[i])
        loc3 = np.logical_and(label >= num[i - 1], label < num[i])
        net['throat.{}'.format(al[i])] = loc1 * loc2
        net['pore.{}'.format(al[i])] = loc3
        if i == phases_num[-1]:
            loc4 = np.logical_and(conns1 < num[-1], conns2 >= num[-1])
            loc5 = label >= num[-1]
            net['throat.boundary'] = loc4
            net['pore.boundary'] = loc5
        for j in phases_num:
            if j > i:
                pi_pj_sa = np.zeros_like(label)
                loc6 = np.logical_and(conns2 >= num[j - 1], conns2 < num[j])
                pi_pj_conns = loc1 * loc6
                net['throat.{}_{}'.format(al[i], al[j])] = pi_pj_conns
                if any(pi_pj_conns):
                    # ---------------------------------------------------------
                    # Calculates phase[i] interfacial area that connects with
                    # phase[j] and vice versa
                    p_conns = net['throat.conns'][:, 0][pi_pj_conns]
                    s_conns = net['throat.conns'][:, 1][pi_pj_conns]
                    ps = net['throat.area'][pi_pj_conns]
                    p_sa = np.bincount(p_conns, ps)
                    # trim zeros at head/tail position to avoid extra bins
                    p_sa = np.trim_zeros(p_sa)
                    i_index = np.arange(min(p_conns), max(p_conns) + 1)
                    j_index = np.arange(min(s_conns), max(s_conns) + 1)
                    s_pa = np.bincount(s_conns, ps)
                    s_pa = np.trim_zeros(s_pa)
                    pi_pj_sa[i_index] = p_sa
                    pi_pj_sa[j_index] = s_pa
                    # ---------------------------------------------------------
                    # Calculates interfacial area using marching cube method
                    if marching_cubes_area:
                        ps_c = net['throat.area'][pi_pj_conns]
                        p_sa_c = np.bincount(p_conns, ps_c)
                        p_sa_c = np.trim_zeros(p_sa_c)
                        s_pa_c = np.bincount(s_conns, ps_c)
                        s_pa_c = np.trim_zeros(s_pa_c)
                        pi_pj_sa[i_index] = p_sa_c
                        pi_pj_sa[j_index] = s_pa_c
                    net['pore.{}_{}_area'.format(
                        al[i], al[j])] = (pi_pj_sa * voxel_size**2)
    return net
Ejemplo n.º 3
0
def snow_partitioning_n(im, r_max=4, sigma=0.4, return_all=True,
                        mask=True, randomize=False, alias=None):
    r"""
    This function partitions an imaging oontain an arbitrary number of phases
    into regions using a marker-based watershed segmentation. Its an extension
    of snow_partitioning function with all phases partitioned together.

    Parameters
    ----------
    im : ND-array
        Image of porous material where each phase is represented by unique
        integer starting from 1 (0's are ignored).
    r_max : scalar
        The radius of the spherical structuring element to use in the Maximum
        filter stage that is used to find peaks.  The default is 4.
    sigma : scalar
        The standard deviation of the Gaussian filter used.  The default is
        0.4. If 0 is given then the filter is not applied, which is useful if a
        distance transform is supplied as the ``im`` argument that has already
        been processed.
    return_all : boolean (default is False)
        If set to ``True`` a named tuple is returned containing the original
        image, the combined distance transform, list of each phase max label,
        and the final combined regions of all phases.
    mask : boolean (default is True)
        Apply a mask to the regions which are not under concern.
    randomize : boolean
        If ``True`` (default), then the region colors will be randomized before
        returning.  This is helpful for visualizing otherwise neighboring
        regions have similar coloring and are hard to distinguish.
    alias : dict (Optional)
        A dictionary that assigns unique image label to specific phases. For
        example {1: 'Solid'} will show all structural properties associated
        with label 1 as Solid phase properties. If ``None`` then default
        labelling will be used i.e {1: 'Phase1',..}.

    Returns
    -------
    An image the same shape as ``im`` with the all phases partitioned into
    regions using a marker based watershed with the peaks found by the
    SNOW algorithm [1].  If ``return_all`` is ``True`` then a **named tuple**
    is returned with the following attribute:

        * ``im`` : The actual image of the porous material
        * ``dt`` : The combined distance transform of the image
        * ``phase_max_label`` : The list of max label of each phase in order to
        distinguish between each other
        * ``regions`` : The partitioned regions of n phases using a marker
        based watershed with the peaks found by the SNOW algorithm

    References
    ----------
    [1] Gostick, J. "A versatile and efficient network extraction algorithm
    using marker-based watershed segmentation".  Physical Review E. (2017)

    [2] Khan, ZA et al. "Dual network extraction algorithm to investigate
    multiple transport processes in porous materials: Image-based modeling
    of pore and grain-scale processes".  Computers in Chemical Engineering.
    (2019)

    See Also
    ----------
    snow_partitioning

    Notes
    -----
    In principle it is possible to perform a distance transform on each
    phase separately, merge these into a single image, then apply the
    watershed only once. This, however, has been found to create edge artifacts
    between regions arising from the way watershed handles plateaus in the
    distance transform. To overcome this, this function applies the watershed
    to each of the distance transforms separately, then merges the segmented
    regions back into a single image.

    """
    # Get alias if provided by user
    al = _create_alias_map(im=im, alias=alias)
    # Perform snow on each phase and merge all segmentation and dt together
    phases_num = sp.unique(im * 1)
    phases_num = sp.trim_zeros(phases_num)
    combined_dt = 0
    combined_region = 0
    num = [0]
    for i in phases_num:
        print('_' * 60)
        if alias is None:
            print('Processing Phase {}'.format(i))
        else:
            print('Processing Phase {}'.format(al[i]))
        phase_snow = snow_partitioning(im == i,
                                       dt=None, r_max=r_max, sigma=sigma,
                                       return_all=return_all, mask=mask,
                                       randomize=randomize)
        if len(phases_num) == 1 and phases_num == 1:
            combined_dt = phase_snow.dt
            combined_region = phase_snow.regions
        else:
            combined_dt += phase_snow.dt
            phase_snow.regions *= phase_snow.im
            phase_snow.regions += num[i - 1]
            phase_ws = phase_snow.regions * phase_snow.im
            phase_ws[phase_ws == num[i - 1]] = 0
            combined_region += phase_ws
        num.append(sp.amax(combined_region))
    if return_all:
        tup = namedtuple('results', field_names=['im', 'dt', 'phase_max_label',
                                                 'regions'])
        tup.im = im
        tup.dt = combined_dt
        tup.phase_max_label = num[1:]
        tup.regions = combined_region
        return tup
    else:
        return combined_region