code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def ignore_warnings(warning=RuntimeWarning):
r"""
Decorator for catching warnings. Useful in pore-scale models where
nans are inevitable, and numpy gets annoying by throwing lots of
RuntimeWarnings.
Parameters
----------
warning : Warning
Python warning type that you want to temporarily ignore
Examples
--------
>>> from openpnm.utils import ignore_warnings
>>> @ignore_warnings()
... def myfun(x):
... return 1/x
>>> import numpy as np
>>> x = np.arange(5)
>>> myfun(x)
array([ inf, 1. , 0.5 , 0.33333333, 0.25 ])
"""
def _ignore_warning(function):
@functools.wraps(function)
def __ignore_warning(*args, **kwargs):
with warnings.catch_warnings(record=True):
# Catch all warnings of this type
warnings.simplefilter("always", warning)
# Execute the function
result = function(*args, **kwargs)
return result
return __ignore_warning
return _ignore_warning
|
Decorator for catching warnings. Useful in pore-scale models where
nans are inevitable, and numpy gets annoying by throwing lots of
RuntimeWarnings.
Parameters
----------
warning : Warning
Python warning type that you want to temporarily ignore
Examples
--------
>>> from openpnm.utils import ignore_warnings
>>> @ignore_warnings()
... def myfun(x):
... return 1/x
>>> import numpy as np
>>> x = np.arange(5)
>>> myfun(x)
array([ inf, 1. , 0.5 , 0.33333333, 0.25 ])
|
ignore_warnings
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def is_symmetric(a, rtol=1e-10):
r"""
Is ``a`` a symmetric matrix?
Parameters
----------
a : ndarray or sparse matrix
Object to check for being a symmetric matrix.
rtol : float
Relative tolerance with respect to the smallest entry in ``a``
that is used to determine if ``a`` is symmetric.
Returns
-------
bool
``True`` if ``a`` is a symmetric matrix, ``False`` otherwise.
"""
if not isinstance(a, np.ndarray) and not sparse.issparse(a):
raise Exception("'a' must be either a sparse matrix or an ndarray.")
if a.shape[0] != a.shape[1]:
raise Exception("'a' must be a square matrix.")
atol = np.amin(np.absolute(a.data)) * rtol
if sparse.issparse(a):
issym = False if ((a - a.T) > atol).nnz else True
elif isinstance(a, np.ndarray):
issym = False if np.any((a - a.T) > atol) else True
return issym
|
Is ``a`` a symmetric matrix?
Parameters
----------
a : ndarray or sparse matrix
Object to check for being a symmetric matrix.
rtol : float
Relative tolerance with respect to the smallest entry in ``a``
that is used to determine if ``a`` is symmetric.
Returns
-------
bool
``True`` if ``a`` is a symmetric matrix, ``False`` otherwise.
|
is_symmetric
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def get_mixture_model_args(
phase,
composition='xs',
args={
'mus': 'pore.viscosity',
'MWs': 'param.molecular_weight',
}
):
r"""
This is used in tests to run models generically
"""
from openpnm.models.phase.misc import mole_to_mass_fraction
vals = {}
if composition in ['ws']:
temp = np.vstack(list(mole_to_mass_fraction(phase=phase).values()))[:, 0]
vals[composition] = temp
else:
temp = np.vstack(list(phase['pore.mole_fraction'].values()))[:, 0]
vals[composition] = temp
for item in args.keys():
temp = np.vstack(list(phase.get_comp_vals(args[item]).values()))[:, 0]
vals[item] = temp
return vals
|
This is used in tests to run models generically
|
get_mixture_model_args
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def dict_to_struct(d):
r"""
Converts a dictionary of numpy arrays to a numpy struct
Parameters
----------
d : dict
A dictionary wtih numpy arrays in each key. The arrays must be all
the same size.
Returns
-------
s : numpy struct
A numpy struct with the fields or names take from the dictionary keys
"""
struct = rf.unstructured_to_structured(np.vstack(list(d.values())).T,
names=list(d.keys()))
return struct
|
Converts a dictionary of numpy arrays to a numpy struct
Parameters
----------
d : dict
A dictionary wtih numpy arrays in each key. The arrays must be all
the same size.
Returns
-------
s : numpy struct
A numpy struct with the fields or names take from the dictionary keys
|
dict_to_struct
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def struct_to_dict(s):
r"""
Converts a numpy struct array into a dictionary using the struct labels as
keys
Parameters
----------
s : numpy struct
The struct array
Returns
-------
d : dict
A dictionary with the struct labels or fields as the keys
"""
d = {}
for key in s.dtype.names:
d[key] = s[key]
return d
|
Converts a numpy struct array into a dictionary using the struct labels as
keys
Parameters
----------
s : numpy struct
The struct array
Returns
-------
d : dict
A dictionary with the struct labels or fields as the keys
|
struct_to_dict
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def is_valid_propname(propname):
r"""
Checks if ``propname`` is a valid OpenPNM propname, i.e. starts with
'pore.' or 'throat.'
Parameters
----------
propname : str
Property name to check whether it's a valid OpenPNM propname.
Returns
-------
bool
Whether or not ``propname`` is a valid name
"""
if not isinstance(propname, str):
return False
temp = propname.split(".")
if temp[0] not in ["pore", "throat"]:
return False
if len(temp) == 1:
return False
for field in temp:
if len(field) == 0:
return False
return True
|
Checks if ``propname`` is a valid OpenPNM propname, i.e. starts with
'pore.' or 'throat.'
Parameters
----------
propname : str
Property name to check whether it's a valid OpenPNM propname.
Returns
-------
bool
Whether or not ``propname`` is a valid name
|
is_valid_propname
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def nbr_to_str(nbr, t_precision=12):
r"""
Converts a scalar into a string in scientific (exponential) notation
without the decimal point.
Parameters
----------
nbr : scalar
The number to be converted into a scalar.
t_precision : integer
The time precision (number of decimal places). Default value is 12.
Returns
-------
num : str
The string represenation of the given number in scientific notation
"""
from decimal import Decimal as dc
n = int(-dc(str(round(nbr, t_precision))).as_tuple().exponent
* (round(nbr, t_precision) != int(nbr)))
nbr_str = (str(int(round(nbr, t_precision)*10**n)) + ('e-'+str(n))*(n != 0))
return nbr_str
|
Converts a scalar into a string in scientific (exponential) notation
without the decimal point.
Parameters
----------
nbr : scalar
The number to be converted into a scalar.
t_precision : integer
The time precision (number of decimal places). Default value is 12.
Returns
-------
num : str
The string represenation of the given number in scientific notation
|
nbr_to_str
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def copy(self, name=None):
r"""
Creates a deep copy of the current project
A deep copy means that new, unique versions of all the objects are
created but with identical data and properties.
Parameters
----------
name : str
The name to give to the new project. If not supplied, a name
is automatically generated.
Returns
-------
proj : list
A new Project object containing copies of all objects
Notes
-----
Because they are new objects, they are given a new uuid
(``obj.settings['uuid']``), but the uuid of the original object
is also stored (``obj.settings['original_uuid']``) for reference.
"""
name = ws._validate_name(name)
proj = deepcopy(self)
for item in proj:
item.settings['uuid'] = str(uuid.uuid4())
proj.settings['uuid'] = str(uuid.uuid4())
proj.settings['name'] = name
ws[name] = proj
return proj
|
Creates a deep copy of the current project
A deep copy means that new, unique versions of all the objects are
created but with identical data and properties.
Parameters
----------
name : str
The name to give to the new project. If not supplied, a name
is automatically generated.
Returns
-------
proj : list
A new Project object containing copies of all objects
Notes
-----
Because they are new objects, they are given a new uuid
(``obj.settings['uuid']``), but the uuid of the original object
is also stored (``obj.settings['original_uuid']``) for reference.
|
copy
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_project.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_project.py
|
MIT
|
def _get_locations(self, label):
r"""
Find locations indicated by the given label regardless of which object
it is defined on
Parameters
----------
label : str
The label whose locations are sought, such as 'pore.left'
Returns
-------
locations : ndarray
A boolean array with ``True`` values indicating which locations
have the given label
Notes
-----
The returns the first instance of ``label`` that it finds
"""
for item in self:
try:
return item[label]
except KeyError:
pass
raise KeyError(label)
|
Find locations indicated by the given label regardless of which object
it is defined on
Parameters
----------
label : str
The label whose locations are sought, such as 'pore.left'
Returns
-------
locations : ndarray
A boolean array with ``True`` values indicating which locations
have the given label
Notes
-----
The returns the first instance of ``label`` that it finds
|
_get_locations
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_project.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_project.py
|
MIT
|
def _create_console_handles(self, project):
r"""
Adds all objects in the given project to the console as variables
with handle names taken from each object's name.
"""
import __main__
for item in project:
__main__.__dict__[item.name] = item
|
Adds all objects in the given project to the console as variables
with handle names taken from each object's name.
|
_create_console_handles
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def save_workspace(self, filename=None):
r"""
Saves all projects in the current workspace as a single file
Parameters
----------
filename : str
The filename to use when saving. If not provided, the present
date and time are used.
Notes
-----
The file is actually zip archive containing ``pnm`` files, one for
each project in the workspace. This archive can be extracted and each
``pnm`` file can be loaded manually using ``load_project`` or the
``openpnm.io.PNM`` class.
"""
if filename is None:
dt = datetime.now()
filename = dt.strftime("%Y_%m_%d_%H_%M_%S")
from zipfile import ZipFile
with ZipFile(filename + '.wrk', 'w') as z:
for prj in self.values():
prj.save_project()
z.write(prj.name + '.pnm')
|
Saves all projects in the current workspace as a single file
Parameters
----------
filename : str
The filename to use when saving. If not provided, the present
date and time are used.
Notes
-----
The file is actually zip archive containing ``pnm`` files, one for
each project in the workspace. This archive can be extracted and each
``pnm`` file can be loaded manually using ``load_project`` or the
``openpnm.io.PNM`` class.
|
save_workspace
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def load_workspace(self, filename):
r"""
Loads project(s) from a saved workspace into current workspace
Parameters
----------
filename : str or Path
The filename containing the saved workspace
"""
from zipfile import ZipFile
with ZipFile(filename, 'r') as z:
logger.info('Loading projects contained in ' + filename)
files = z.filelist
for f in files:
self.load_project(f.orig_filename)
|
Loads project(s) from a saved workspace into current workspace
Parameters
----------
filename : str or Path
The filename containing the saved workspace
|
load_workspace
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def save_project(self, project, filename=None):
r"""
Saves given Project to a ``pnm`` file
This will include all of associated objects, including algorithms.
Parameters
----------
project : Project
The project to save.
filename : str, optional
If no filename is given, the given project name is used. See Notes
for more information.
See Also
--------
save_workspace
Notes
-----
The filename can be a string such as 'saved_file.pnm'. The string can
include absolute path such as 'C:\networks\saved_file.pnm', or can
be a relative path such as '..\..\saved_file.pnm', which will look
2 directories above the current working directory. Can also be a
path object object such as that produced by ``pathlib`` or
``os.path`` in the Python standard library.
"""
if filename is None:
dt = datetime.now()
filename = dt.strftime("%Y_%m_%d_%H_%M_%S")
with open(filename.split('.')[-1]+'.pnm', 'wb') as f:
pickle.dump(project, f)
|
Saves given Project to a ``pnm`` file
This will include all of associated objects, including algorithms.
Parameters
----------
project : Project
The project to save.
filename : str, optional
If no filename is given, the given project name is used. See Notes
for more information.
See Also
--------
save_workspace
Notes
-----
The filename can be a string such as 'saved_file.pnm'. The string can
include absolute path such as 'C:\networks\saved_file.pnm', or can
be a relative path such as '..\..\saved_file.pnm', which will look
2 directories above the current working directory. Can also be a
path object object such as that produced by ``pathlib`` or
``os.path`` in the Python standard library.
|
save_project
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def load_project(self, filename):
r"""
Loads a Project from the specified 'pnm' file
The loaded project is added to the Workspace. This will *not* delete
any existing Projects in the Workspace and will rename any Projects
being loaded if necessary.
Parameters
----------
filename : str or Path
The name of the file to open. See Notes for more information.
See Also
--------
load_workspace
Notes
-----
The filename can be a string such as 'saved_file.pnm'. The string can
include absolute path such as 'C:\networks\saved_file.pnm', or can
be a relative path such as '..\..\saved_file.pnm', which will look
2 directories above the current working directory. Can also be a
path object object such as that produced by ``pathlib`` or
``os.path`` in the Python standard library.
"""
with open(filename, 'rb') as f:
proj = pickle.load(f)
proj.settings.uuid = str(uuid4())
proj.name = self._validate_name(proj.name)
self[proj.name] = proj
return proj
|
Loads a Project from the specified 'pnm' file
The loaded project is added to the Workspace. This will *not* delete
any existing Projects in the Workspace and will rename any Projects
being loaded if necessary.
Parameters
----------
filename : str or Path
The name of the file to open. See Notes for more information.
See Also
--------
load_workspace
Notes
-----
The filename can be a string such as 'saved_file.pnm'. The string can
include absolute path such as 'C:\networks\saved_file.pnm', or can
be a relative path such as '..\..\saved_file.pnm', which will look
2 directories above the current working directory. Can also be a
path object object such as that produced by ``pathlib`` or
``os.path`` in the Python standard library.
|
load_project
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def new_project(self, name=None):
r"""
Creates a new empty Project object
Parameters
----------
name : str, optional
The unique name to give to the project. If none is given, one
will be automatically generated (e.g. 'proj_01`)
Returns
-------
proj : list
An empty Project object, suitable for passing into a Network
generator
"""
from openpnm.utils import Project
proj = Project(name=name)
return proj
|
Creates a new empty Project object
Parameters
----------
name : str, optional
The unique name to give to the project. If none is given, one
will be automatically generated (e.g. 'proj_01`)
Returns
-------
proj : list
An empty Project object, suitable for passing into a Network
generator
|
new_project
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_workspace.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_workspace.py
|
MIT
|
def draw_conduit(network, throat):
"""Draws a subset of a network given throat numbers."""
pn = network
P1, P2 = find_connected_sites(g=pn, bonds=throat)
new_net = Network(coords=pn.coords[[P1, P2], :], conns=np.atleast_2d([0, 1]))
new_net.regenerate_models()
new_net['pore.diameter'] = pn['pore.diameter'][[P1, P2]]
new_net['throat.diameter'] = [pn['throat.diameter'][throat]]
new_net['throat.length'] = throat_length.circles_and_rectangles(new_net)
new_net['throat.endpoints'] = throat_endpoints.spheres_and_cylinders(new_net)
Pcrds = np.vstack((pn.coords[0, :], pn.coords[0, :]))
Pcrds[1, :] = Pcrds[1, :] + np.array([new_net['throat.spacing'], 0, 0])
fig, ax = plt.subplots(figsize=[10, 5])
patches = []
for i, P in enumerate([0, 1]):
x, y, r = Pcrds[P, 0], Pcrds[P, 1], new_net['pore.diameter'][P]/2
circle = Circle((x, y), r)
patches.append(circle)
Tcrds = np.vstack(list(new_net['throat.endpoints'].values()))
Tcrds = rotate_coords(Tcrds, b=270)
H = new_net['throat.diameter'][0]
W = new_net['throat.length'][0]
R1 = new_net['pore.diameter'][0]/2
R2 = new_net['pore.diameter'][1]/2
rect = Rectangle(xy=(Tcrds[0, 0], Tcrds[0, 1]-H/2), height=H, width=W)
patches.append(rect)
p = PatchCollection(patches, alpha=0.5, edgecolor='k', linewidth=3)
p.set_array([1, 1, 2])
p.cmap = plt.cm.bwr
ax.add_collection(p)
ax.scatter(*Pcrds[0, :2], marker='+', c='k', s=100)
ax.scatter(*Pcrds[1, :2], marker='+', c='k', s=100)
left = min(Pcrds[:, 0])-R1
right = max(Pcrds[:, 0])+R2
ax.set_xlim([left - abs(left-right)/32, right + abs(left-right)/32])
temp = (Pcrds[:, 1]).mean()
ax.set_ylim([temp - abs(left-right)/4, temp + abs(left-right)/4])
ax.annotate(text='',
xy=Pcrds[0, :2],
xytext=(Pcrds[0, 0], Pcrds[0, 1]-R1),
arrowprops=dict(arrowstyle='<-', lw=2))
ax.annotate(text=f"{R1}",
xy=Pcrds[0, :2],
xytext=(Pcrds[0, 0], Pcrds[0, 1]-R1/2),
textcoords='data')
return ax
|
Draws a subset of a network given throat numbers.
|
draw_conduit
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_conduit_visualizer.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_conduit_visualizer.py
|
MIT
|
def plot_connections(network,
throats=None,
ax=None,
size_by=None,
color_by=None,
label_by=None,
cmap='jet',
color='b',
alpha=1.0,
linestyle='solid',
linewidth=1,
**kwargs): # pragma: no cover
r"""
Produce a 3D plot of the network topology.
This shows how throats connect for quick visualization without having
to export data to veiw in Paraview.
Parameters
----------
network : Network
The network whose topological connections to plot
throats : array_like (optional)
The list of throats to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no throats are
specified then all throats are shown.
fig : Matplotlib figure handle and line property arguments (optional)
If a ``fig`` is supplied, then the topology will be overlaid on this
plot. This makes it possible to combine coordinates and connections,
and to color throats differently for instance.
size_by : array_like (optional)
An ndarray of throat values (e.g. alg['throat.rate']). These
values are used to scale the ``linewidth``, so if the lines are too
thin, then increase ``linewidth``.
color_by : array_like (optional)
An ndarray of throat values (e.g. alg['throat.rate']).
label_by : array_like (optional)
An array or list of values to use as labels
cmap : str or cmap object (optional)
The matplotlib colormap to use if specfying a throat property
for ``color_by``
color : str, optional (optional)
A matplotlib named color (e.g. 'r' for red).
alpha : float (optional)
The transparency of the lines, with 1 being solid and 0 being invisible
linestyle : str (optional)
Can be one of {'solid', 'dashed', 'dashdot', 'dotted'}. Default is
'solid'.
linewidth : float (optional)
Controls the thickness of drawn lines. Is used to scale the thickness
if ``size_by`` is given. Default is 1. If a value is provided for
``size_by`` then they are used to scale the ``linewidth``.
font : dict
A dictionary of key-value pairs that are used to control the font
appearance if `label_by` is provided.
**kwargs : dict
All other keyword arguments are passed on to the ``Line3DCollection``
class of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
lc : LineCollection or Line3DCollection
Matplotlib object containing the lines representing the throats.
Notes
-----
To create a single plot containing both pore coordinates and throats,
consider creating an empty figure and then pass the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_coordinates
Examples
--------
>>> import openpnm as op
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> mpl.use('Agg')
>>> pn = op.network.Cubic(shape=[10, 10, 3])
>>> pn.add_boundary_pores()
>>> Ts = pn.throats('*boundary', mode='not') # find internal throats
>>> fig, ax = plt.subplots() # create empty figure
>>> _ = op.visualization.plot_connections(network=pn,
... throats=Ts) # plot internal throats
>>> Ts = pn.throats('*boundary') # find boundary throats
>>> _ = op.visualization.plot_connections(network=pn,
... throats=Ts,
... ax=ax,
... color='r') # plot boundary throats in red
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import colors as mcolors
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from openpnm.topotools import dimensionality
Ts = network.Ts if throats is None else network._parse_indices(throats)
dim = dimensionality(network)
ThreeD = True if dim.sum() == 3 else False
# Add a dummy axis for 1D networks
if dim.sum() == 1:
dim[np.argwhere(~dim)[0]] = True
if "fig" in kwargs.keys():
raise Exception("'fig' argument is deprecated, use 'ax' instead.")
if ax is None:
fig, ax = plt.subplots()
else:
# The next line is necessary if ax was created using plt.subplots()
fig, ax = ax.get_figure(), ax.get_figure().gca()
if ThreeD and ax.name != '3d':
fig.delaxes(ax)
ax = fig.add_subplot(111, projection='3d')
# Collect coordinates
Ps = np.unique(network['throat.conns'][Ts])
X, Y, Z = network['pore.coords'][Ps].T
xyz = network["pore.coords"][:, dim]
P1, P2 = network["throat.conns"][Ts].T
throat_pos = np.column_stack((xyz[P1], xyz[P2])).reshape((Ts.size, 2, dim.sum()))
# Deal with optional style related arguments
if 'c' in kwargs.keys():
color = kwargs.pop('c')
color = mcolors.to_rgb(color) + tuple([alpha])
if isinstance(cmap, str):
try:
cmap = plt.colormaps.get_cmap(cmap)
except AttributeError:
cmap = plt.cm.get_cmap(cmap)
# Override colors with color_by if given
if color_by is not None:
color_by = np.array(color_by, dtype=np.float16)
if len(color_by) != len(Ts):
color_by = color_by[Ts]
if not np.all(np.isfinite(color_by)):
color_by[~np.isfinite(color_by)] = 0
logger.warning('nans or infs found in color_by array, setting to 0')
vmin = kwargs.pop('vmin', color_by.min())
vmax = kwargs.pop('vmax', color_by.max())
cscale = (color_by - vmin) / (vmax - vmin)
color = cmap(cscale)
color[:, 3] = alpha
if size_by is not None:
if len(size_by) != len(Ts):
size_by = size_by[Ts]
if not np.all(np.isfinite(size_by)):
size_by[~np.isfinite(size_by)] = 0
logger.warning('nans or infs found in size_by array, setting to 0')
linewidth = size_by / size_by.max() * linewidth
if label_by is not None:
if len(label_by) != len(Ts):
label_by = label_by[Ts]
fontkws = kwargs.pop('font', {})
if ThreeD:
lc = Line3DCollection(throat_pos, colors=color, cmap=cmap,
linestyles=linestyle, linewidths=linewidth,
antialiaseds=np.ones_like(network.Ts), **kwargs)
else:
lc = LineCollection(throat_pos, colors=color, cmap=cmap,
linestyles=linestyle, linewidths=linewidth,
antialiaseds=np.ones_like(network.Ts), **kwargs)
if label_by is not None:
for count, (P1, P2) in enumerate(network.conns[Ts, :]):
i, j, k = np.mean(network.coords[[P1, P2], :], axis=0)
ax.text(i, j, label_by[count],
ha='center', va='center',
**fontkws)
ax.add_collection(lc)
if np.size(Ts) > 0:
_scale_axes(ax=ax, X=X, Y=Y, Z=Z)
_label_axes(ax=ax, X=X, Y=Y, Z=Z)
fig.tight_layout()
return lc
|
Produce a 3D plot of the network topology.
This shows how throats connect for quick visualization without having
to export data to veiw in Paraview.
Parameters
----------
network : Network
The network whose topological connections to plot
throats : array_like (optional)
The list of throats to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no throats are
specified then all throats are shown.
fig : Matplotlib figure handle and line property arguments (optional)
If a ``fig`` is supplied, then the topology will be overlaid on this
plot. This makes it possible to combine coordinates and connections,
and to color throats differently for instance.
size_by : array_like (optional)
An ndarray of throat values (e.g. alg['throat.rate']). These
values are used to scale the ``linewidth``, so if the lines are too
thin, then increase ``linewidth``.
color_by : array_like (optional)
An ndarray of throat values (e.g. alg['throat.rate']).
label_by : array_like (optional)
An array or list of values to use as labels
cmap : str or cmap object (optional)
The matplotlib colormap to use if specfying a throat property
for ``color_by``
color : str, optional (optional)
A matplotlib named color (e.g. 'r' for red).
alpha : float (optional)
The transparency of the lines, with 1 being solid and 0 being invisible
linestyle : str (optional)
Can be one of {'solid', 'dashed', 'dashdot', 'dotted'}. Default is
'solid'.
linewidth : float (optional)
Controls the thickness of drawn lines. Is used to scale the thickness
if ``size_by`` is given. Default is 1. If a value is provided for
``size_by`` then they are used to scale the ``linewidth``.
font : dict
A dictionary of key-value pairs that are used to control the font
appearance if `label_by` is provided.
**kwargs : dict
All other keyword arguments are passed on to the ``Line3DCollection``
class of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
lc : LineCollection or Line3DCollection
Matplotlib object containing the lines representing the throats.
Notes
-----
To create a single plot containing both pore coordinates and throats,
consider creating an empty figure and then pass the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_coordinates
Examples
--------
>>> import openpnm as op
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> mpl.use('Agg')
>>> pn = op.network.Cubic(shape=[10, 10, 3])
>>> pn.add_boundary_pores()
>>> Ts = pn.throats('*boundary', mode='not') # find internal throats
>>> fig, ax = plt.subplots() # create empty figure
>>> _ = op.visualization.plot_connections(network=pn,
... throats=Ts) # plot internal throats
>>> Ts = pn.throats('*boundary') # find boundary throats
>>> _ = op.visualization.plot_connections(network=pn,
... throats=Ts,
... ax=ax,
... color='r') # plot boundary throats in red
|
plot_connections
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def plot_coordinates(network,
pores=None,
ax=None,
size_by=None,
color_by=None,
label_by=None,
cmap='jet',
color='r',
alpha=1.0,
marker='o',
markersize=10,
**kwargs): # pragma: no cover
r"""
Produce a 3D plot showing specified pore coordinates as markers.
Parameters
----------
network : Network
The network whose topological connections to plot.
pores : array_like (optional)
The list of pores to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no pores
are specified then all are shown.
ax : Matplotlib axis handle
If ``ax`` is supplied, then the coordinates will be overlaid.
This enables the plotting of multiple different sets of pores as
well as throat connections from ``plot_connections``.
size_by : str or array_like
An ndarray of pore values (e.g. alg['pore.concentration']). These
values are normalized by scaled by ``markersize``. Note that this controls
the marker *area*, so if you want the markers to be proportional to diameter
you should do `size_by=net['pore.diameter']**2`.
color_by : str or array_like
An ndarray of pore values (e.g. alg['pore.concentration']).
label_by : array_like (optional)
An array or list of values to use as labels
cmap : str or cmap object
The matplotlib colormap to use if specfying a pore property
for ``color_by``
color : str
A matplotlib named color (e.g. 'r' for red).
alpha : float
The transparency of the lines, with 1 being solid and 0 being invisible
marker : 's'
The marker to use. The default is a circle. Options are explained
`here <https://matplotlib.org/3.2.1/api/markers_api.html>`_
markersize : scalar
Controls size of marker, default is 1.0. This value is used to scale
the ``size_by`` argument if given.
font : dict
A dictionary of key-value pairs that are used to control the font
appearance if `label_by` is provided.
**kwargs
All other keyword arguments are passed on to the ``scatter``
function of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
pc : PathCollection
Matplotlib object containing the markers representing the pores.
Notes
-----
To create a single plot containing both pore coordinates and throats,
consider creating an empty figure and then pass the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_connections
Examples
--------
>>> import openpnm as op
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> mpl.use('Agg')
>>> pn = op.network.Cubic(shape=[10, 10, 3])
>>> pn['pore.internal'] = True
>>> pn.add_boundary_pores()
>>> Ps = pn.pores('internal') # find internal pores
>>> fig, ax = plt.subplots() # create empty figure
>>> _ = op.visualization.plot_coordinates(network=pn,
... pores=Ps,
... color='b',
... ax=ax) # plot internal pores
>>> Ps = pn.pores('*boundary') # find boundary pores
>>> _ = op.visualization.plot_coordinates(network=pn,
... pores=Ps,
... color='r',
... ax=ax) # plot boundary pores in red
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from openpnm.topotools import dimensionality
Ps = network.Ps if pores is None else network._parse_indices(pores)
dim = dimensionality(network)
ThreeD = True if dim.sum() == 3 else False
# Add a dummy axis for 1D networks
if dim.sum() == 1:
dim[np.argwhere(~dim)[0]] = True
# Add 2 dummy axes for 0D networks (1 pore only)
if dim.sum() == 0:
dim[[0, 1]] = True
if "fig" in kwargs.keys():
raise Exception("'fig' argument is deprecated, use 'ax' instead.")
if ax is None:
fig, ax = plt.subplots()
else:
# The next line is necessary if ax was created using plt.subplots()
fig, ax = ax.get_figure(), ax.get_figure().gca()
if ThreeD and ax.name != '3d':
fig.delaxes(ax)
ax = fig.add_subplot(111, projection='3d')
# Collect specified coordinates
X, Y, Z = network['pore.coords'][Ps].T
# The bounding box for fig is the entire ntwork (to fix the problem with
# overwriting figures' axes lim)
Xl, Yl, Zl = network['pore.coords'].T
# Parse formatting kwargs
if 'c' in kwargs.keys():
color = kwargs.pop('c')
if 's' in kwargs.keys():
markersize = kwargs.pop('s')
if isinstance(cmap, str):
try:
cmap = plt.colormaps.get_cmap(cmap)
except AttributeError:
cmap = plt.cm.get_cmap(cmap)
if color_by is not None:
color_by = np.array(color_by, dtype=np.float16)
if len(color_by) != len(Ps):
color_by = color_by[Ps]
if not np.all(np.isfinite(color_by)):
color_by[~np.isfinite(color_by)] = 0
logger.warning('nans or infs found in color_by array, setting to 0')
vmin = kwargs.pop('vmin', color_by.min())
vmax = kwargs.pop('vmax', color_by.max())
cscale = (color_by - vmin) / (vmax - vmin)
color = cmap(cscale)
if size_by is not None:
if len(size_by) != len(Ps):
size_by = size_by[Ps]
if not np.all(np.isfinite(size_by)):
size_by[~np.isfinite(size_by)] = 0
logger.warning('nans or infs found in size_by array, setting to 0')
markersize = size_by / size_by.max() * markersize
if label_by is not None:
if len(label_by) != len(Ps):
label_by = label_by[Ps]
fontkws = kwargs.pop('font', {})
if ThreeD:
sc = ax.scatter(X, Y, Z,
c=color,
s=markersize,
marker=marker,
alpha=alpha,
**kwargs)
_scale_axes(ax=ax, X=Xl, Y=Yl, Z=Zl)
else:
_X, _Y = np.column_stack((X, Y, Z))[:, dim].T
sc = ax.scatter(_X, _Y,
c=color,
s=markersize,
marker=marker,
alpha=alpha,
**kwargs)
if label_by is not None:
for count, (i, j, k) in enumerate(network.coords[Ps, :]):
ax.text(i, j, label_by[count],
ha='center', va='center',
**fontkws)
_scale_axes(ax=ax, X=Xl, Y=Yl, Z=np.zeros_like(Yl))
_label_axes(ax=ax, X=Xl, Y=Yl, Z=Zl)
fig.tight_layout()
return sc
|
Produce a 3D plot showing specified pore coordinates as markers.
Parameters
----------
network : Network
The network whose topological connections to plot.
pores : array_like (optional)
The list of pores to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no pores
are specified then all are shown.
ax : Matplotlib axis handle
If ``ax`` is supplied, then the coordinates will be overlaid.
This enables the plotting of multiple different sets of pores as
well as throat connections from ``plot_connections``.
size_by : str or array_like
An ndarray of pore values (e.g. alg['pore.concentration']). These
values are normalized by scaled by ``markersize``. Note that this controls
the marker *area*, so if you want the markers to be proportional to diameter
you should do `size_by=net['pore.diameter']**2`.
color_by : str or array_like
An ndarray of pore values (e.g. alg['pore.concentration']).
label_by : array_like (optional)
An array or list of values to use as labels
cmap : str or cmap object
The matplotlib colormap to use if specfying a pore property
for ``color_by``
color : str
A matplotlib named color (e.g. 'r' for red).
alpha : float
The transparency of the lines, with 1 being solid and 0 being invisible
marker : 's'
The marker to use. The default is a circle. Options are explained
`here <https://matplotlib.org/3.2.1/api/markers_api.html>`_
markersize : scalar
Controls size of marker, default is 1.0. This value is used to scale
the ``size_by`` argument if given.
font : dict
A dictionary of key-value pairs that are used to control the font
appearance if `label_by` is provided.
**kwargs
All other keyword arguments are passed on to the ``scatter``
function of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
pc : PathCollection
Matplotlib object containing the markers representing the pores.
Notes
-----
To create a single plot containing both pore coordinates and throats,
consider creating an empty figure and then pass the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_connections
Examples
--------
>>> import openpnm as op
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> mpl.use('Agg')
>>> pn = op.network.Cubic(shape=[10, 10, 3])
>>> pn['pore.internal'] = True
>>> pn.add_boundary_pores()
>>> Ps = pn.pores('internal') # find internal pores
>>> fig, ax = plt.subplots() # create empty figure
>>> _ = op.visualization.plot_coordinates(network=pn,
... pores=Ps,
... color='b',
... ax=ax) # plot internal pores
>>> Ps = pn.pores('*boundary') # find boundary pores
>>> _ = op.visualization.plot_coordinates(network=pn,
... pores=Ps,
... color='r',
... ax=ax) # plot boundary pores in red
|
plot_coordinates
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def plot_networkx(network,
plot_throats=True,
labels=None,
colors=None,
scale=1,
ax=None,
alpha=1.0): # pragma: no cover
r"""
Creates a pretty 2D plot for 2D OpenPNM networks.
Parameters
----------
network : Network
plot_throats : bool, optional
Plots throats as well as pores, if True.
labels : list, optional
List of OpenPNM labels
colors : list, optional
List of corresponding colors to the given `labels`.
scale : float, optional
Scale factor for size of pores.
ax : matplotlib.Axes, optional
Matplotlib axes object
alpha: float, optional
Transparency value, 1 is opaque and 0 is transparent
"""
import matplotlib.pyplot as plt
from matplotlib.collections import PathCollection
from networkx import Graph, draw_networkx_edges, draw_networkx_nodes
from openpnm.topotools import dimensionality
dims = dimensionality(network)
if dims.sum() > 2:
raise Exception("NetworkX plotting only works for 2D networks.")
temp = network['pore.coords'].T[dims].squeeze()
if dims.sum() == 1:
x = temp
y = np.zeros_like(x)
if dims.sum() == 2:
x, y = temp
try:
node_size = scale * network['pore.diameter']
except KeyError:
node_size = np.ones_like(x) * scale * 0.5
G = Graph()
pos = {network.Ps[i]: [x[i], y[i]] for i in range(network.Np)}
if not np.isfinite(node_size).all():
node_size[~np.isfinite(node_size)] = np.nanmin(node_size)
node_color = np.array(['k'] * len(network.Ps))
if labels:
if not isinstance(labels, list):
labels = [labels]
if not isinstance(colors, list):
colors = [colors]
if len(labels) != len(colors):
raise Exception('len(colors) must be equal to len(labels)!')
for label, color in zip(labels, colors):
node_color[network.pores(label)] = color
if ax is None:
fig, ax = plt.subplots()
ax.set_aspect('equal', adjustable='datalim')
offset = node_size.max() * 0.5
ax.set_xlim((x.min() - offset, x.max() + offset))
ax.set_ylim((y.min() - offset, y.max() + offset))
ax.axis("off")
# Keep track of already plotted nodes
temp = [id(item) for item in ax.collections if isinstance(item, PathCollection)]
# Plot pores
gplot = draw_networkx_nodes(G, ax=ax, pos=pos, nodelist=network.Ps.tolist(),
alpha=alpha, node_color=node_color, edgecolors=node_color,
node_size=node_size)
# (Optionally) Plot throats
if plot_throats:
draw_networkx_edges(G, pos=pos, edge_color='k', alpha=alpha,
edgelist=network['throat.conns'].tolist(), ax=ax)
spi = 2700 # 1250 was obtained by trial and error
figwidth, figheight = ax.get_figure().get_size_inches()
figsize_ratio = figheight / figwidth
data_ratio = ax.get_data_ratio()
corr = min(figsize_ratio / data_ratio, 1)
xrange = np.ptp(ax.get_xlim())
markersize = np.atleast_1d((corr*figwidth)**2 / xrange**2 * node_size**2 * spi)
for item in ax.collections:
if isinstance(item, PathCollection) and id(item) not in temp:
item.set_sizes(markersize)
return gplot
|
Creates a pretty 2D plot for 2D OpenPNM networks.
Parameters
----------
network : Network
plot_throats : bool, optional
Plots throats as well as pores, if True.
labels : list, optional
List of OpenPNM labels
colors : list, optional
List of corresponding colors to the given `labels`.
scale : float, optional
Scale factor for size of pores.
ax : matplotlib.Axes, optional
Matplotlib axes object
alpha: float, optional
Transparency value, 1 is opaque and 0 is transparent
|
plot_networkx
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def plot_tutorial(network,
pore_labels=None,
throat_labels=None,
font_size=12,
line_width=2,
node_color='b',
edge_color='r',
node_size=500): # pragma: no cover
r"""
Generate a network plot suitable for tutorials and explanations.
Parameters
----------
network : Network
The network to plot, should be 2D, since the z-coordinate will be
ignored.
pore_labels : array_like
A list of values to use for labeling the pores. If not provided then pore
index is used.
throat_labels : array_like
A list of values to use for labeling the throat. If not provided then throat
index is used.
font_size : int
Size of font to use for labels.
line_width : int
Thickness of edge lines and node borders.
node_color : str
Color of node border.
edge_color : str
Color of edge lines.
node_size : int
Size of node circle.
Returns
-------
g : NetworkX plot object
"""
import matplotlib.pyplot as plt
import networkx as nx
from openpnm.io import network_to_networkx
G = network_to_networkx(network=network)
pos = {i: network['pore.coords'][i, 0:2] for i in network.Ps}
if pore_labels is None:
labels = {i: i for i in network.Ps}
else:
labels = {i: pore_labels[i] for i in network.Ps}
if throat_labels is None:
edge_labels = {tuple(network['throat.conns'][i, :]): i for i in network.Ts}
else:
edge_labels = {tuple(network['throat.conns'][i, :]): throat_labels[i]
for i in network.Ts}
gplot = nx.draw_networkx_nodes(G, pos,
node_size=node_size,
node_color='w',
edgecolors=node_color,
linewidths=line_width)
nx.draw_networkx_edges(
G, pos, width=line_width, edge_color=edge_color)
nx.draw_networkx_labels(
G, pos, labels=labels, font_size=font_size, font_color='k')
nx.draw_networkx_edge_labels(
G, pos, edge_labels=edge_labels, font_size=font_size, font_color='k')
# Prettify the figure (margins, etc.)
plt.axis('off')
ax = plt.gca()
ax.margins(0.1, 0.1)
ax.set_aspect("equal")
fig = plt.gcf()
fig.tight_layout()
dims = op.topotools.dimensionality(network)
xy_range = np.ptp(network.coords, axis=0)[dims]
aspect_ratio = xy_range[0] / xy_range[1]
fig.set_size_inches(5, 5 / aspect_ratio)
return gplot
|
Generate a network plot suitable for tutorials and explanations.
Parameters
----------
network : Network
The network to plot, should be 2D, since the z-coordinate will be
ignored.
pore_labels : array_like
A list of values to use for labeling the pores. If not provided then pore
index is used.
throat_labels : array_like
A list of values to use for labeling the throat. If not provided then throat
index is used.
font_size : int
Size of font to use for labels.
line_width : int
Thickness of edge lines and node borders.
node_color : str
Color of node border.
edge_color : str
Color of edge lines.
node_size : int
Size of node circle.
Returns
-------
g : NetworkX plot object
|
plot_tutorial
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def plot_notebook(network,
node_color=0,
edge_color=0,
node_size=1,
node_scale=20,
edge_scale=5,
colormap='viridis'):
r"""
Visualize a network in 3D using Plotly.
The pores and throats are scaled and colored by their properties.
The final figure can be rotated and zoomed.
Parameters
----------
network : Network
The network to visualize
node_color : ndarray
An array of values used for coloring the pores. If not given, the
lowest value of the employed colormap is assigned to all markers.
edge_color : ndarray
An array of values used for coloring the throats. If not given, the
lowest value of the employed colormap is assigned to all lines.
node_size : ndarray
An array of values controlling the size of the markers. If not given
all markers will be the same size
node_scale : scalar
A scaler to resize the markers
edge_scale : scalar
A scaler to the line thickness
colormap : str
The colormap to use
Returns
-------
fig : Plotly graph object
The graph object containing the generated plots. The object has
several useful methods.
Notes
-----
**Important**
a) This does not work in Spyder. It should only be called from a
Jupyter Notebook.
b) This is only meant for relatively small networks. For proper
visualization use Paraview.
"""
try:
import plotly.graph_objects as go
except ImportError:
raise Exception('Plotly is not installed.'
'Please install Plotly using "pip install plotly"')
# Get xyz coords for points
x_nodes, y_nodes, z_nodes = network.coords.T
node_size = np.ones(network.Np)*node_size
node_color = np.ones(network.Np)*node_color
edge_color = np.ones(network.Nt)*edge_color
node_labels = [str(i) + ': ' + str(x) for i, x in
enumerate(zip(node_size, node_color))]
edge_labels = [str(i) + ': ' + str(x) for i, x in enumerate(edge_color)]
# Create edges and nodes coordinates
N = network.Nt*3
x_edges = np.zeros(N)
x_edges[np.arange(0, N, 3)] = network.coords[network.conns[:, 0]][:, 0]
x_edges[np.arange(1, N, 3)] = network.coords[network.conns[:, 1]][:, 0]
x_edges[np.arange(2, N, 3)] = np.nan
y_edges = np.zeros(network.Nt*3)
y_edges[np.arange(0, N, 3)] = network.coords[network.conns[:, 0]][:, 1]
y_edges[np.arange(1, N, 3)] = network.coords[network.conns[:, 1]][:, 1]
y_edges[np.arange(2, N, 3)] = np.nan
z_edges = np.zeros(network.Nt*3)
z_edges[np.arange(0, N, 3)] = network.coords[network.conns[:, 0]][:, 2]
z_edges[np.arange(1, N, 3)] = network.coords[network.conns[:, 1]][:, 2]
z_edges[np.arange(2, N, 3)] = np.nan
# Create plotly's Scatter3d object for pores and throats
trace_edges = go.Scatter3d(x=x_edges,
y=y_edges,
z=z_edges,
mode='lines',
line=dict(color=edge_color,
width=edge_scale,
colorscale=colormap),
text=edge_labels, hoverinfo='text')
trace_nodes = go.Scatter3d(x=x_nodes,
y=y_nodes,
z=z_nodes,
mode='markers',
marker=dict(symbol='circle',
size=node_size*node_scale,
color=node_color,
colorscale=colormap,
line=dict(color='black', width=0.5)),
text=node_labels, hoverinfo='text')
axis = dict(showbackground=False,
showline=False,
zeroline=False,
showgrid=False,
showticklabels=False,
title='')
layout = go.Layout(width=650,
height=625,
showlegend=False,
scene=dict(xaxis=dict(axis),
yaxis=dict(axis),
zaxis=dict(axis),),
margin=dict(t=100),
hovermode='closest')
data = [trace_edges, trace_nodes]
fig = go.Figure(data=data, layout=layout)
return fig
|
Visualize a network in 3D using Plotly.
The pores and throats are scaled and colored by their properties.
The final figure can be rotated and zoomed.
Parameters
----------
network : Network
The network to visualize
node_color : ndarray
An array of values used for coloring the pores. If not given, the
lowest value of the employed colormap is assigned to all markers.
edge_color : ndarray
An array of values used for coloring the throats. If not given, the
lowest value of the employed colormap is assigned to all lines.
node_size : ndarray
An array of values controlling the size of the markers. If not given
all markers will be the same size
node_scale : scalar
A scaler to resize the markers
edge_scale : scalar
A scaler to the line thickness
colormap : str
The colormap to use
Returns
-------
fig : Plotly graph object
The graph object containing the generated plots. The object has
several useful methods.
Notes
-----
**Important**
a) This does not work in Spyder. It should only be called from a
Jupyter Notebook.
b) This is only meant for relatively small networks. For proper
visualization use Paraview.
|
plot_notebook
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def _generate_voxel_image(network, pore_shape, throat_shape, max_dim=200):
r"""
Generates a 3d numpy array from an OpenPNM network
Parameters
----------
network : OpenPNM Network
Network from which voxel image is to be generated
pore_shape : str
Shape of pores in the network, valid choices are "sphere", "cube"
throat_shape : str
Shape of throats in the network, valid choices are "cylinder", "cuboid"
max_dim : int
Number of voxels in the largest dimension of the network
Returns
-------
im : ndarray
Voxelated image corresponding to the given pore network model
Notes
-----
(1) The generated voxel image is labeled with 0s, 1s and 2s signifying
solid phase, pores, and throats respectively.
"""
from porespy.tools import insert_cylinder, overlay
from skimage.morphology import ball, cube
xyz = network["pore.coords"]
cn = network["throat.conns"]
# Distance bounding box from the network by a fixed amount
delta = network["pore.diameter"].mean() / 2
if isinstance(network, op.network.Cubic):
try:
delta = op.topotools.get_spacing(network).mean() / 2
except AttributeError:
delta = network.spacing.mean() / 2
# Shift everything to avoid out-of-bounds
extra_clearance = int(max_dim * 0.05)
# Transform points to satisfy origin at (0, 0, 0)
xyz0 = xyz.min(axis=0) - delta
xyz += -xyz0
res = (np.ptp(xyz, axis=0).max() + 2 * delta) / max_dim
shape = np.rint((xyz.max(axis=0) + delta) / res).astype(int) + 2 * extra_clearance
# Transforming from real coords to matrix coords
xyz = np.rint(xyz / res).astype(int) + extra_clearance
pore_radi = np.rint(network["pore.diameter"] * 0.5 / res).astype(int)
throat_radi = np.rint(network["throat.diameter"] * 0.5 / res).astype(int)
im_pores = np.zeros(shape, dtype=np.uint8)
im_throats = np.zeros_like(im_pores)
if pore_shape == "cube":
pore_elem = cube
rp = pore_radi * 2 + 1 # +1 since num_voxel must be odd
rp_max = int(2 * round(delta / res)) + 1
if pore_shape == "sphere":
pore_elem = ball
rp = pore_radi
rp_max = int(round(delta / res))
if throat_shape == "cuboid":
raise Exception("Not yet implemented, try 'cylinder'.")
# Generating voxels for pores
for i, pore in enumerate(tqdm(network.Ps)):
elem = pore_elem(rp[i])
try:
im_pores = overlay(im1=im_pores, im2=elem, c=xyz[i])
except ValueError:
elem = pore_elem(rp_max)
im_pores = overlay(im1=im_pores, im2=elem, c=xyz[i])
# Get rid of pore overlaps
im_pores[im_pores > 0] = 1
# Generating voxels for throats
for i, throat in enumerate(tqdm(network.Ts)):
try:
im_throats = insert_cylinder(
im_throats, r=throat_radi[i], xyz0=xyz[cn[i, 0]], xyz1=xyz[cn[i, 1]])
except ValueError:
im_throats = insert_cylinder(
im_throats, r=rp_max, xyz0=xyz[cn[i, 0]], xyz1=xyz[cn[i, 1]])
# Get rid of throat overlaps
im_throats[im_throats > 0] = 1
# Subtract pore-throat overlap from throats
im_throats = (im_throats.astype(bool) * ~im_pores.astype(bool)).astype(np.uint8)
im = im_pores * 1 + im_throats * 2
return im[extra_clearance:-extra_clearance,
extra_clearance:-extra_clearance,
extra_clearance:-extra_clearance]
|
Generates a 3d numpy array from an OpenPNM network
Parameters
----------
network : OpenPNM Network
Network from which voxel image is to be generated
pore_shape : str
Shape of pores in the network, valid choices are "sphere", "cube"
throat_shape : str
Shape of throats in the network, valid choices are "cylinder", "cuboid"
max_dim : int
Number of voxels in the largest dimension of the network
Returns
-------
im : ndarray
Voxelated image corresponding to the given pore network model
Notes
-----
(1) The generated voxel image is labeled with 0s, 1s and 2s signifying
solid phase, pores, and throats respectively.
|
_generate_voxel_image
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def generate_voxel_image(network, pore_shape="sphere", throat_shape="cylinder",
max_dim=None, rtol=0.1):
r"""
Generate a voxel image from a Network
Parameters
----------
network : OpenPNM Network
Network from which voxel image is to be generated
pore_shape : str
Shape of pores in the network, valid choices are "sphere", "cube"
throat_shape : str
Shape of throats in the network, valid choices are "cylinder", "cuboid"
max_dim : int
Number of voxels in the largest dimension of the network
rtol : float
Stopping criteria for finding the smallest voxel image such that
further increasing the number of voxels in each dimension by 25% would
improve the predicted porosity of the image by less that ``rtol``
Returns
-------
im : ndarray
Voxelated image corresponding to the given pore network model
Notes
-----
(1) The generated voxelated image is labeled with 0s, 1s and 2s signifying
solid phase, pores, and throats respectively.
(2) If max_dim is not provided, the method calculates it such that the
further increasing it doesn't change porosity by much.
"""
# If max_dim is provided, generate voxel image using max_dim
if max_dim is not None:
return _generate_voxel_image(
network, pore_shape, throat_shape, max_dim=max_dim)
max_dim = 200
# If max_dim is not provided, find best max_dim that predicts porosity
err = 100
eps_old = 200
while err > rtol:
im = _generate_voxel_image(
network, pore_shape, throat_shape, max_dim=max_dim)
eps = im.astype(bool).sum() / np.prod(im.shape)
err = abs(1 - eps / eps_old)
eps_old = eps
max_dim = int(max_dim * 1.25)
return im
|
Generate a voxel image from a Network
Parameters
----------
network : OpenPNM Network
Network from which voxel image is to be generated
pore_shape : str
Shape of pores in the network, valid choices are "sphere", "cube"
throat_shape : str
Shape of throats in the network, valid choices are "cylinder", "cuboid"
max_dim : int
Number of voxels in the largest dimension of the network
rtol : float
Stopping criteria for finding the smallest voxel image such that
further increasing the number of voxels in each dimension by 25% would
improve the predicted porosity of the image by less that ``rtol``
Returns
-------
im : ndarray
Voxelated image corresponding to the given pore network model
Notes
-----
(1) The generated voxelated image is labeled with 0s, 1s and 2s signifying
solid phase, pores, and throats respectively.
(2) If max_dim is not provided, the method calculates it such that the
further increasing it doesn't change porosity by much.
|
generate_voxel_image
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def plot_vispy(
network,
pore_color=None,
pore_size=None,
throat_color=None,
throat_size=None,
bgcolor='grey',
):
r"""
Creates a pretty network plot using VisPy.
Parameters
----------
network
"""
try:
from vispy import scene
except ModuleNotFoundError:
raise Exception("vispy must be installed to use this function")
canvas = scene.SceneCanvas(keys='interactive', show=True, bgcolor=bgcolor)
view = canvas.central_widget.add_view()
view.camera = 'turntable'
view.camera.fov = 30
view.camera.distance = 3*np.max(network['pore.coords'])
if pore_color is None:
pore_color = create_pore_colors_from_array(network['pore.diameter'],
cmap='viridis')
else:
pore_color = create_pore_colors_from_array(pore_color,
cmap='viridis')
if throat_color is None:
throat_color = create_throat_colors_from_array(network['throat.diameter'],
cmap='viridis')
else:
throat_color = create_throat_colors_from_array(throat_color,
cmap='viridis')
if pore_size is None:
pore_size = network['pore.diameter']
if throat_size is None:
throat_size = 2
else:
throat_size = np.max(throat_size) # Arrays not supported here
# plot spheres
vis = scene.visuals.Markers(
pos=network['pore.coords'],
size=pore_size,
antialias=0,
face_color=pore_color,
edge_width=0,
scaling=True,
spherical=True,
)
vis.parent = view.scene
# plot axis
# vispy.scene.visuals.XYZAxis(parent=view.scene)
# set camera center
view.camera.center = np.array((network['pore.coords'][:, 0].max()/2,
network['pore.coords'][:, 1].max()/2,
network['pore.coords'][:, 2].max()/2))
# data preparation
lines = np.zeros((len(network['throat.conns']), 2, 3))
for i in range(len(network['throat.conns'])):
pair = network['throat.conns'][i]
line = np.array([[network['pore.coords'][pair[0]],
network['pore.coords'][pair[1]]]])
lines[i, :, :] = line
# plot throats
vis2 = scene.visuals.Line(lines,
width=throat_size,
color=throat_color,
connect='segments',
antialias=True,)
vis2.parent = view.scene
|
Creates a pretty network plot using VisPy.
Parameters
----------
network
|
plot_vispy
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def set_mpl_style(): # pragma: no cover
r"""
Prettifies matplotlib's output by adjusting fonts, markersize etc.
"""
sfont = 12
mfont = 12
lfont = 12
image_props = {'interpolation': 'none',
'cmap': 'viridis'}
line_props = {'linewidth': 2,
'markersize': 7,
'markerfacecolor': 'w'}
font_props = {'size': sfont}
axes_props = {'titlesize': lfont,
'labelsize': mfont,
'linewidth': 2,
'labelpad': 8}
xtick_props = {'labelsize': sfont,
'top': True,
'direction': 'in',
'major.size': 6,
'major.width': 2}
ytick_props = {'labelsize': sfont,
'right': True,
'direction': 'in',
'major.size': 6,
'major.width': 2}
legend_props = {'fontsize': mfont,
'frameon': False}
figure_props = {'titlesize': sfont,
'autolayout': True}
plt.rc('font', **font_props)
plt.rc('lines', **line_props)
plt.rc('axes', **axes_props)
plt.rc('xtick', **xtick_props)
plt.rc('ytick', **ytick_props)
plt.rc('legend', **legend_props)
plt.rc('figure', **figure_props)
plt.rc('image', **image_props)
try:
import IPython
IPython.display.set_matplotlib_formats('png2x')
except ModuleNotFoundError:
pass
|
Prettifies matplotlib's output by adjusting fonts, markersize etc.
|
set_mpl_style
|
python
|
PMEAL/OpenPNM
|
openpnm/visualization/_plottools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/visualization/_plottools.py
|
MIT
|
def info(network):
r"""
Prints an overview of the network dictionary
"""
d = _pdict(network)
d._key = 'Attribute'
d._value = 'Description'
print(d)
|
Prints an overview of the network dictionary
|
info
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/__init__.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/__init__.py
|
MIT
|
def bcc(shape, spacing=1, mode='kdtree', node_prefix='node', edge_prefix='edge'):
r"""
Generate a body-centered cubic lattice
Parameters
----------
shape : array_like
The number of corner sites in each direction. A cubic lattice of
this size is created and then 'body-centered' nodes are added
afterward.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
mode : str
Dictate how neighbors are found. Options are:
=============== ======================================================
mode meaning
=============== ======================================================
'kdtree' Uses ``scipy.spatial.KDTree`` to find all neighbors
within the unit cell
'triangulation' Uses ``scipy.spatial.Delaunay`` to find all neighbors
=============== ======================================================
Returns
-------
network : dict
A dictionary containing 'coords', 'conns' and various boolean labels
(i.e. 'node.center')
Notes
-----
It is not clear whether KDTree or Delaunay are faster. In fact it is
surely possible to find the neighbors formulaically but this is not
implemented yet.
"""
shape = np.array(shape)
spacing = np.array(spacing)
net1 = cubic(shape=shape, spacing=1,
node_prefix=node_prefix, edge_prefix=edge_prefix)
net2 = cubic(shape=shape-1, spacing=1,
node_prefix=node_prefix, edge_prefix=edge_prefix)
net2[node_prefix + '.coords'] += 0.5
crds = np.concatenate(
(net1[node_prefix + '.coords'],
net2[node_prefix + '.coords']))
corner_label = np.concatenate(
(np.ones(net1[node_prefix + '.coords'].shape[0], dtype=bool),
np.zeros(net2[node_prefix + '.coords'].shape[0], dtype=bool)))
body_label = np.concatenate(
(np.zeros(net1[node_prefix + '.coords'].shape[0], dtype=bool),
np.ones(net2[node_prefix + '.coords'].shape[0], dtype=bool)))
if mode.startswith('tri'):
tri = sptl.Delaunay(points=crds)
am = tri_to_am(tri)
conns = np.vstack((am.row, am.col)).T
# Trim diagonal connections between cubic pores
L = np.sqrt(np.sum(np.diff(crds[conns], axis=1)**2, axis=2)).flatten()
conns = conns[L <= 1]
elif mode.startswith('kd'):
tree1 = sptl.KDTree(crds)
# Method 1
hits = tree1.query_ball_point(crds, r=1)
# Method 2: Not sure which is faster
# tree2 = sptl.KDTree(crds)
# hits = tree1.query_ball_tree(tree1, r=1)
indices = np.hstack(hits)
# Convert to CSR matrix
indptr = [len(i) for i in hits]
indptr.insert(0, 0)
indptr = np.cumsum(indptr)
am = sprs.csr_matrix((np.ones_like(indices), indices, indptr))
am = sprs.triu(am, k=1)
am = am.tocoo()
conns = np.vstack((am.row, am.col)).T
d = {}
d[node_prefix+'.coords'] = crds*spacing
d[edge_prefix+'.conns'] = conns
d[node_prefix+'.corner'] = corner_label
d[node_prefix+'.body'] = body_label
return d
|
Generate a body-centered cubic lattice
Parameters
----------
shape : array_like
The number of corner sites in each direction. A cubic lattice of
this size is created and then 'body-centered' nodes are added
afterward.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
mode : str
Dictate how neighbors are found. Options are:
=============== ======================================================
mode meaning
=============== ======================================================
'kdtree' Uses ``scipy.spatial.KDTree`` to find all neighbors
within the unit cell
'triangulation' Uses ``scipy.spatial.Delaunay`` to find all neighbors
=============== ======================================================
Returns
-------
network : dict
A dictionary containing 'coords', 'conns' and various boolean labels
(i.e. 'node.center')
Notes
-----
It is not clear whether KDTree or Delaunay are faster. In fact it is
surely possible to find the neighbors formulaically but this is not
implemented yet.
|
bcc
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_bcc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_bcc.py
|
MIT
|
def cubic(shape, spacing=1, connectivity=6, node_prefix='node', edge_prefix='edge'):
r"""
Generate a simple cubic lattice
Parameters
----------
shape : array_like
The number of unit cells in each direction. A unit cell has 1 vertex
at its center.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
Returns
-------
network : dict
A dictionary containing ``coords`` and ``conns`` of a cubic network with the
specified spacing and connectivity.
"""
# Take care of 1D/2D networks
shape = np.array(shape, ndmin=1)
shape = np.concatenate((shape, [1] * (3 - shape.size))).astype(int)
arr = np.atleast_3d(np.empty(shape))
spacing = np.float64(spacing)
if spacing.size == 2:
spacing = np.concatenate((spacing, [1]))
spacing = np.ones(3, dtype=float) * np.array(spacing, ndmin=1)
z = np.tile(np.arange(shape[2]), shape[0] * shape[1])
y = np.tile(np.repeat(np.arange(shape[1]), shape[2]), shape[0])
x = np.repeat(np.arange(shape[0]), shape[1] * shape[2])
points = (np.vstack([x, y, z]).T).astype(float) + 0.5
idx = np.arange(arr.size).reshape(arr.shape)
face_joints = [(idx[:, :, :-1], idx[:, :, 1:]),
(idx[:, :-1], idx[:, 1:]),
(idx[:-1], idx[1:])]
corner_joints = [(idx[:-1, :-1, :-1], idx[1:, 1:, 1:]),
(idx[:-1, :-1, 1:], idx[1:, 1:, :-1]),
(idx[:-1, 1:, :-1], idx[1:, :-1, 1:]),
(idx[1:, :-1, :-1], idx[:-1, 1:, 1:])]
edge_joints = [(idx[:, :-1, :-1], idx[:, 1:, 1:]),
(idx[:, :-1, 1:], idx[:, 1:, :-1]),
(idx[:-1, :, :-1], idx[1:, :, 1:]),
(idx[1:, :, :-1], idx[:-1, :, 1:]),
(idx[1:, 1:, :], idx[:-1, :-1, :]),
(idx[1:, :-1, :], idx[:-1, 1:, :])]
if connectivity == 6:
joints = face_joints
elif connectivity == 6 + 8:
joints = face_joints + corner_joints
elif connectivity == 6 + 12:
joints = face_joints + edge_joints
elif connectivity == 12 + 8:
joints = edge_joints + corner_joints
elif connectivity == 6 + 8 + 12:
joints = face_joints + corner_joints + edge_joints
else:
raise Exception("Invalid connectivity. Must be 6, 14, 18, 20 or 26.")
tails, heads = np.array([], dtype=int), np.array([], dtype=int)
for T, H in joints:
tails = np.concatenate((tails, T.flatten()))
heads = np.concatenate((heads, H.flatten()))
pairs = np.vstack([tails, heads]).T
# NOTE: pairs is already sorted for connectivity = 6
if connectivity != 6:
pairs = np.sort(pairs, axis=1)
d = {}
d[f"{node_prefix}.coords"] = points * spacing
d[f"{edge_prefix}.conns"] = pairs
return d
|
Generate a simple cubic lattice
Parameters
----------
shape : array_like
The number of unit cells in each direction. A unit cell has 1 vertex
at its center.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
Returns
-------
network : dict
A dictionary containing ``coords`` and ``conns`` of a cubic network with the
specified spacing and connectivity.
|
cubic
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_cubic.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_cubic.py
|
MIT
|
def delaunay(
points,
shape=[1, 1, 1],
reflect=False,
f=1,
trim=True,
node_prefix='node',
edge_prefix='edge',
):
r"""
Generate a network based on Delaunay triangulation of random points
Parameters
----------
points : array_like or int
Can either be an N-by-3 array of point coordinates which will be used,
or a scalar value indicating the number of points to generate
shape : array_like
Indicates the size and shape of the domain
reflect : boolean, optional (default = ``False``)
If ``True`` then points are reflected across each face of the domain
prior to performing the tessellation. These reflected points are
automatically trimmed. Enabling this behavior prevents long-range
connections between surface pores.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
trim : boolean, optional (default = ``True``)
If ``True`` then any points laying outside the domain are removed. This is
mostly only useful if ``reflect=True``.
Returns
-------
network : dict
A dictionary containing 'node.coords' and 'edge.conns'
tri : Delaunay tessellation object
The Delaunay tessellation object produced by ``scipy.spatial.Delaunay``
"""
points = tools.parse_points(points=points, shape=shape, reflect=reflect, f=f)
mask = ~np.all(points == 0, axis=0)
tri = sptl.Delaunay(points=points[:, mask])
coo = tri_to_am(tri)
d = {}
d[node_prefix+'.coords'] = points
d[edge_prefix+'.conns'] = np.vstack((coo.row, coo.col)).T
if trim:
trim = isoutside(d, shape=shape)
d = trim_nodes(network=d, inds=np.where(trim)[0])
return d, tri
|
Generate a network based on Delaunay triangulation of random points
Parameters
----------
points : array_like or int
Can either be an N-by-3 array of point coordinates which will be used,
or a scalar value indicating the number of points to generate
shape : array_like
Indicates the size and shape of the domain
reflect : boolean, optional (default = ``False``)
If ``True`` then points are reflected across each face of the domain
prior to performing the tessellation. These reflected points are
automatically trimmed. Enabling this behavior prevents long-range
connections between surface pores.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
trim : boolean, optional (default = ``True``)
If ``True`` then any points laying outside the domain are removed. This is
mostly only useful if ``reflect=True``.
Returns
-------
network : dict
A dictionary containing 'node.coords' and 'edge.conns'
tri : Delaunay tessellation object
The Delaunay tessellation object produced by ``scipy.spatial.Delaunay``
|
delaunay
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_delaunay.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_delaunay.py
|
MIT
|
def fcc(shape, spacing=1, mode='kdtree', node_prefix='node', edge_prefix='edge'):
r"""
Generate a face-centered cubic lattice
Parameters
----------
shape : array_like
The number of corner sites in each direction. A sipmle cubic lattice
is created then the 'face-sites' are added afterwards.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
mode : str
Dictate how neighbors are found. Options are:
=============== =====================================================
mode meaning
=============== =====================================================
'kdtree' Uses ``scipy.spatial.KDTree`` to find all neighbors
within the unit cell.
'triangulation' Uses ``scipy.spatial.Delaunay`` to find all neighbors.
=============== =====================================================
Returns
-------
network : dict
A dictionary containing 'coords', 'conns' and various boolean labels
(i.e. 'node.center')
Notes
-----
It is not clear whether KDTree of Delaunay are faster. In fact it is
surely possible to find the neighbors formulaically but this is not
implemented yet.
"""
shape = np.array(shape)
# Create base cubic network of corner sites
net1 = cubic(shape=shape,
node_prefix=node_prefix, edge_prefix=edge_prefix)
# Create 3 networks to become face sites
net2 = cubic(shape=shape - [1, 1, 0],
node_prefix=node_prefix, edge_prefix=edge_prefix)
net3 = cubic(shape=shape - [1, 0, 1],
node_prefix=node_prefix, edge_prefix=edge_prefix)
net4 = cubic(shape=shape - [0, 1, 1],
node_prefix=node_prefix, edge_prefix=edge_prefix)
# Offset pore coords by 1/2 a unit cell
net2[node_prefix+'.coords'] += np.array([0.5, 0.5, 0])
net3[node_prefix+'.coords'] += np.array([0.5, 0, 0.5])
net4[node_prefix+'.coords'] += np.array([0, 0.5, 0.5])
crds = np.concatenate((net1[node_prefix+'.coords'],
net2[node_prefix+'.coords'],
net3[node_prefix+'.coords'],
net4[node_prefix+'.coords']))
corner_labels = np.concatenate(
(np.ones(net1[node_prefix+'.coords'].shape[0], dtype=bool),
np.zeros(net2[node_prefix+'.coords'].shape[0], dtype=bool),
np.zeros(net3[node_prefix+'.coords'].shape[0], dtype=bool),
np.zeros(net4[node_prefix+'.coords'].shape[0], dtype=bool)))
if mode.startswith('tri'):
tri = sptl.Delaunay(points=crds)
am = tri_to_am(tri)
conns = np.vstack((am.row, am.col)).T
# Trim diagonal connections between cubic pores
L = np.sqrt(np.sum(np.diff(crds[conns], axis=1)**2, axis=2)).flatten()
conns = conns[L <= 0.75]
elif mode.startswith('kd'):
tree1 = sptl.KDTree(crds)
# Method 1
hits = tree1.query_ball_point(crds, r=.75)
# Method 2: Not sure which is faster
# tree2 = sptl.KDTree(crds)
# hits = tree1.query_ball_tree(tree1, r=1)
indices = np.hstack(hits)
# Convert to CSR matrix
indptr = [len(i) for i in hits]
indptr.insert(0, 0)
indptr = np.cumsum(indptr)
am = sprs.csr_matrix((np.ones_like(indices), indices, indptr))
am = sprs.triu(am, k=1)
am = am.tocoo()
conns = np.vstack((am.row, am.col)).T
conns = np.vstack((net1[edge_prefix+'.conns'], conns))
d = {}
d[node_prefix + '.coords'] = crds*spacing
d[edge_prefix + '.conns'] = conns
d[node_prefix + '.corner'] = corner_labels
d[node_prefix + '.face'] = ~corner_labels
return d
|
Generate a face-centered cubic lattice
Parameters
----------
shape : array_like
The number of corner sites in each direction. A sipmle cubic lattice
is created then the 'face-sites' are added afterwards.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
mode : str
Dictate how neighbors are found. Options are:
=============== =====================================================
mode meaning
=============== =====================================================
'kdtree' Uses ``scipy.spatial.KDTree`` to find all neighbors
within the unit cell.
'triangulation' Uses ``scipy.spatial.Delaunay`` to find all neighbors.
=============== =====================================================
Returns
-------
network : dict
A dictionary containing 'coords', 'conns' and various boolean labels
(i.e. 'node.center')
Notes
-----
It is not clear whether KDTree of Delaunay are faster. In fact it is
surely possible to find the neighbors formulaically but this is not
implemented yet.
|
fcc
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_fcc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_fcc.py
|
MIT
|
def cubic_template(template, spacing=1, connectivity=6,
node_prefix='node', edge_prefix='edge'):
r"""
Generate a simple cubic lattice matching the shape of the provided tempate
Parameters
----------
templte : ndarray
Each ``True`` value will be treated as a vertex while all others
will be trimmed.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
Returns
-------
network : dict
A dictionary containing 'node.coords' and 'edge.conns'
"""
template = np.atleast_3d(template).astype(bool)
# Generate a full cubic network
temp = cubic(shape=template.shape, spacing=spacing,
connectivity=connectivity,
node_prefix=node_prefix, edge_prefix=edge_prefix)
# Store some info about template
coords = np.unravel_index(range(template.size), template.shape)
coords = np.vstack(coords).T
Np = coords.shape[0]
temp[node_prefix+'.template_coords'] = coords
temp[node_prefix+'.template_indices'] = np.arange(Np)
# Trim pores not present in template
temp = trim_nodes(network=temp, inds=~template.flatten())
return temp
|
Generate a simple cubic lattice matching the shape of the provided tempate
Parameters
----------
templte : ndarray
Each ``True`` value will be treated as a vertex while all others
will be trimmed.
spacing : array_like or float
The size of a unit cell in each direction. If an scalar is given it is
applied in all 3 directions.
Returns
-------
network : dict
A dictionary containing 'node.coords' and 'edge.conns'
|
cubic_template
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_template.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_template.py
|
MIT
|
def voronoi(
points,
shape=[1, 1, 1],
trim=True,
reflect=False,
f=1,
relaxation=0,
node_prefix='node',
edge_prefix='edge',
):
r"""
Generate a network based on a Voronoi tessellation of base points
Parameters
----------
points : array_like or int
Can either be an N-by-3 array of point coordinates which will be used
directly, or a scalar indicating the number of points to generate.
shape : array_like
The size and shape of the domain
trim : boolean
If ``True`` (default) then any vertices laying outside the domain
given by ``shape`` are removed (as are the edges connected to them).
reflect : boolean, optional (default = ``False``)
If ``True`` then points are reflected across each face of the domain
prior to performing the tessellation. Enabling this behavior creates
flat faces on all sizes of the domain.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
relaxation : int, optional (default = 0)
The number of iterations to use for relaxing the base points. This is
sometimes called `Lloyd's algorithm
<https://en.wikipedia.org/wiki/Lloyd%27s_algorithm>`_. This function computes
the new base points as the simple average of the Voronoi vertices instead
of rigorously finding the center of mass, which is quite time consuming.
To use the rigorous method, call the ``lloyd_relaxation`` function manually
to obtain relaxed points, then pass the points directly to this funcion.
The results are quite stable after only a few iterations.
Returns
-------
network : dict
A dictionary containing node coordinates and edge connections
vor : Voronoi tessellation object
The Voronoi tessellation object produced by ``scipy.spatial.Voronoi``
"""
points = tools.parse_points(points=points, shape=shape, reflect=reflect, f=f)
mask = ~np.all(points == 0, axis=0)
# Perform tessellation
vor = sptl.Voronoi(points=points[:, mask])
for _ in range(relaxation):
points = tools.lloyd_relaxation(vor, mode='rigorous')
# Reparse points
d = {}
d[node_prefix+'.coords'] = points
keep = ~isoutside(network=d, shape=shape)
points = points[keep]
points = tools.parse_points(points=points, shape=shape, reflect=reflect)
vor = sptl.Voronoi(points=points[:, mask])
# Convert to adjecency matrix
coo = vor_to_am(vor)
# Write values to dictionary
d = {}
conns = np.vstack((coo.row, coo.col)).T
d[edge_prefix+'.conns'] = conns
# Convert coords to 3D if necessary
# Rounding is crucial since some voronoi verts endup outside domain
pts = np.around(vor.vertices, decimals=10)
if mask.sum() < 3:
coords = np.zeros([pts.shape[0], 3], dtype=float)
coords[:, mask] = pts
else:
coords = pts
d[node_prefix+'.coords'] = coords
if trim:
hits = isoutside(d, shape=shape)
d = trim_nodes(d, hits)
return d, vor
|
Generate a network based on a Voronoi tessellation of base points
Parameters
----------
points : array_like or int
Can either be an N-by-3 array of point coordinates which will be used
directly, or a scalar indicating the number of points to generate.
shape : array_like
The size and shape of the domain
trim : boolean
If ``True`` (default) then any vertices laying outside the domain
given by ``shape`` are removed (as are the edges connected to them).
reflect : boolean, optional (default = ``False``)
If ``True`` then points are reflected across each face of the domain
prior to performing the tessellation. Enabling this behavior creates
flat faces on all sizes of the domain.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
relaxation : int, optional (default = 0)
The number of iterations to use for relaxing the base points. This is
sometimes called `Lloyd's algorithm
<https://en.wikipedia.org/wiki/Lloyd%27s_algorithm>`_. This function computes
the new base points as the simple average of the Voronoi vertices instead
of rigorously finding the center of mass, which is quite time consuming.
To use the rigorous method, call the ``lloyd_relaxation`` function manually
to obtain relaxed points, then pass the points directly to this funcion.
The results are quite stable after only a few iterations.
Returns
-------
network : dict
A dictionary containing node coordinates and edge connections
vor : Voronoi tessellation object
The Voronoi tessellation object produced by ``scipy.spatial.Voronoi``
|
voronoi
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_voronoi.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_voronoi.py
|
MIT
|
def voronoi_delaunay_dual(
points,
shape,
trim=True,
reflect=True,
f=1,
relaxation=0,
node_prefix='node',
edge_prefix='edge',
return_tri=False,
):
r"""
Generate a dual Voronoi-Delaunay network from given base points
Parameters
----------
points : array_like or scalar
The points to be tessellated. If a scalar is given a set of points
of that size is generated inside the given ``shape``.
shape : array_like
The size of the domain in which the points lie
trim : bool, optional
If ``True`` (default) then all points lying beyond the given domain
shape will be removed
reflect : bool, optionl
If ``True`` (Default) then points are reflected across each face of the
domain prior to performing the tessellation.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
relaxation : int, optional (default = 0)
The number of iterations to use for relaxing the base points. This is
sometimes called `Lloyd's algorithm
<https://en.wikipedia.org/wiki/Lloyd%27s_algorithm>`_. This function computes
the new base points as the simple average of the Voronoi vertices instead
of rigorously finding the center of mass, which is quite time consuming.
To use the rigorous method, call the ``lloyd_relaxation`` function manually
to obtain relaxed points, then pass the points directly to this funcion.
The results are quite stable after only a few iterations.
Returns
-------
network : dict
A dictionary containing '<node_prefix>.coords' and '<edge_prefix>.conns'
vor : Voronoi object
The Voronoi tessellation object produced by ``scipy.spatial.Voronoi``
tri : Delaunay object
The Delaunay triangulation object produced by ``scipy.spatial.Delaunay``
"""
# Generate a set of base points if scalar was given
points = tools.parse_points(
points=points,
shape=shape,
reflect=reflect,
f=f,
)
# Generate mask to remove any dims with all 0's
mask = ~np.all(points == 0, axis=0)
# Perform tessellations
vor = sptl.Voronoi(points=points[:, mask])
for _ in range(relaxation):
points = tools.lloyd_relaxation(vor, mode='fast')
vor = sptl.Voronoi(points=points[:, mask])
# Collect delaunay edges
conns_del = vor.ridge_points
# Deal with voronoi edges
v = vor.ridge_vertices.copy() # Assuming 'ridge' means facet between regions
# Add row [0] to close the facet on itself, add -1 to break connection to
# next facet in list as connections with -1 get deleted later
_ = [row.extend([row[0], -1]) for row in v]
v = np.hstack(v)
conns_vor = np.vstack((v[:-1], v[1:])).T
mask = np.any(conns_vor < 0, axis=1)
conns_vor = conns_vor[~mask] + vor.npoints
# Finally, get interconnecting edges
idx = [vor.regions[vor.point_region[i]] for i in range(0, len(vor.regions)-1)]
conns_inter = [([i]*len(idx[i]), idx[i]) for i in range(0, len(idx))]
conns_inter = np.hstack(conns_inter).astype(int).T
mask = np.any(conns_inter < 0, axis=1)
conns_inter = conns_inter[~mask, :] + np.array([0, vor.npoints], dtype=int)
conns = np.vstack((conns_del, conns_vor, conns_inter))
# Tidy up
am = conns_to_am(conns)
conns = np.vstack((am.row, am.col)).T
# Combine delaunay and voronoi points
pts_all = np.vstack((vor.points, vor.vertices))
# Rounding is crucial since some voronoi verts endup outside domain
pts_all = np.around(pts_all, decimals=10)
# Convert coords to 3D if necessary
mask = ~np.all(points == 0, axis=0)
if mask.sum() < 3:
coords = np.zeros([pts_all.shape[0], 3], dtype=float)
coords[:, mask] = pts_all
else:
coords = pts_all
# Assign coords and conns to network dict
network = {}
network[node_prefix+'.coords'] = coords
network[edge_prefix+'.conns'] = conns
n_nodes = coords.shape[0]
n_edges = conns.shape[0]
# Label all pores and throats by type
network[node_prefix+'.delaunay'] = np.zeros(n_nodes, dtype=bool)
network[node_prefix+'.delaunay'][0:vor.npoints] = True
network[node_prefix+'.voronoi'] = np.zeros(n_nodes, dtype=bool)
network[node_prefix+'.voronoi'][vor.npoints:] = True
# Label throats between Delaunay pores
network[edge_prefix+'.delaunay'] = np.zeros(n_edges, dtype=bool)
Ts = np.all(network[edge_prefix+'.conns'] < vor.npoints, axis=1)
network[edge_prefix+'.delaunay'][Ts] = True
# Label throats between Voronoi pores
network[edge_prefix+'.voronoi'] = np.zeros(n_edges, dtype=bool)
Ts = np.all(network[edge_prefix+'.conns'] >= vor.npoints, axis=1)
network[edge_prefix+'.voronoi'][Ts] = True
# Label throats connecting a Delaunay and a Voronoi pore
Ts = np.sum(network[node_prefix+'.delaunay'][conns].astype(int), axis=1) == 1
network[edge_prefix+'.interconnect'] = Ts
if trim:
# Find all delaunay nodes outside the domain
Ps = isoutside(network=network, shape=shape)*network[node_prefix+'.delaunay']
if np.any(Ps): # only occurs if points were reflected
# Find voronoi nodes connected to these and mark them as surface nodes
inds = np.where(Ps)[0]
Ns = find_neighbor_nodes(network=network, inds=inds)
network[node_prefix+'.surface'] = np.zeros(n_nodes, dtype=bool)
network[node_prefix+'.surface'][Ns] = True
Ps = isoutside(network=network, shape=shape)
inds = np.where(Ps)[0]
network = trim_nodes(network=network, inds=inds)
else:
trim = isoutside(network=network, shape=shape)
inds = np.where(trim)[0]
network = trim_nodes(network=network, inds=inds)
if return_tri:
tri = sptl.Delaunay(points=points[:, mask])
else:
tri = None
return network, vor, tri
|
Generate a dual Voronoi-Delaunay network from given base points
Parameters
----------
points : array_like or scalar
The points to be tessellated. If a scalar is given a set of points
of that size is generated inside the given ``shape``.
shape : array_like
The size of the domain in which the points lie
trim : bool, optional
If ``True`` (default) then all points lying beyond the given domain
shape will be removed
reflect : bool, optionl
If ``True`` (Default) then points are reflected across each face of the
domain prior to performing the tessellation.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
relaxation : int, optional (default = 0)
The number of iterations to use for relaxing the base points. This is
sometimes called `Lloyd's algorithm
<https://en.wikipedia.org/wiki/Lloyd%27s_algorithm>`_. This function computes
the new base points as the simple average of the Voronoi vertices instead
of rigorously finding the center of mass, which is quite time consuming.
To use the rigorous method, call the ``lloyd_relaxation`` function manually
to obtain relaxed points, then pass the points directly to this funcion.
The results are quite stable after only a few iterations.
Returns
-------
network : dict
A dictionary containing '<node_prefix>.coords' and '<edge_prefix>.conns'
vor : Voronoi object
The Voronoi tessellation object produced by ``scipy.spatial.Voronoi``
tri : Delaunay object
The Delaunay triangulation object produced by ``scipy.spatial.Delaunay``
|
voronoi_delaunay_dual
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/_voronoi_delaunay_dual.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/_voronoi_delaunay_dual.py
|
MIT
|
def lloyd_relaxation(vor, mode='rigorous'):
r"""
Computes the center of mass for each polyhedra in a Voronoi tessellaion
Parameters
----------
vor : Scipy Voronoi object
The object returned by ``scipy.spatial.Voronoi``
mode : str
Options are:
=========== ================================================================
mode description
=========== ================================================================
rigorous Computes a Delaunay triangulation of the input points then finds
the true centroid by computing the area/volume of each triangle/
tetrahedron to find the weighted average center of mass.
fast Computes the basic average of the input points without
accounting for the distribution of points. This is a decent
approximation and is *much* faster.
=========== ================================================================
"""
pts = vor.points
for i, r in enumerate(vor.point_region):
if np.all(np.array(vor.regions[r]) > 0):
pts[i, :pts.shape[1]] = \
get_centroid(vor.vertices[vor.regions[r]], mode=mode)
if pts.shape[1] == 2:
pts = np.c_[pts, np.zeros_like(pts[:, 0])]
return pts
|
Computes the center of mass for each polyhedra in a Voronoi tessellaion
Parameters
----------
vor : Scipy Voronoi object
The object returned by ``scipy.spatial.Voronoi``
mode : str
Options are:
=========== ================================================================
mode description
=========== ================================================================
rigorous Computes a Delaunay triangulation of the input points then finds
the true centroid by computing the area/volume of each triangle/
tetrahedron to find the weighted average center of mass.
fast Computes the basic average of the input points without
accounting for the distribution of points. This is a decent
approximation and is *much* faster.
=========== ================================================================
|
lloyd_relaxation
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def get_centroid(pts, mode='rigorous'):
r"""
Finds the centroid of a given set of points
Parameters
----------
pts : ndarray
The points in 2D or 3D
mode : str
Options are:
=========== ================================================================
mode description
=========== ================================================================
rigorous Computes a Delaunay triangulation of the input points then finds
the true centroid by computing the area/volume of each triangle/
tetrahedron to find the weighted average center of mass.
fast Computes the basic average of the input points without
accounting for the distribution of points. This is a decent
approximation and is *much* faster.
=========== ================================================================
Returns
-------
pt : ndarray
A single coordinate representing the center of mass of the input points
"""
if mode == 'rigorous':
tri = sptl.Delaunay(pts)
CoM = center_of_mass(simplices=tri.simplices.astype(np.int_),
points=tri.points.astype(float))
elif mode == 'fast':
CoM = pts.mean(axis=0)
return CoM
|
Finds the centroid of a given set of points
Parameters
----------
pts : ndarray
The points in 2D or 3D
mode : str
Options are:
=========== ================================================================
mode description
=========== ================================================================
rigorous Computes a Delaunay triangulation of the input points then finds
the true centroid by computing the area/volume of each triangle/
tetrahedron to find the weighted average center of mass.
fast Computes the basic average of the input points without
accounting for the distribution of points. This is a decent
approximation and is *much* faster.
=========== ================================================================
Returns
-------
pt : ndarray
A single coordinate representing the center of mass of the input points
|
get_centroid
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def parse_points(shape, points, reflect=False, f=1):
r"""
Converts given points argument to consistent format
Parameters
----------
shape : array_like
The shape of the domain
points : int or array_like
If a scalar value then this indicates the number of points to generate. If
an array, then these points are used directly.
reflect : bool, optional
If ``True`` the base points are reflected across the borders of the domain.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Returns
-------
points : ndarray
The points after being cleaned and parsed correctly
"""
# Deal with input arguments
shape = np.array(shape, dtype=float)
if isinstance(points, int):
points = generate_base_points(num_points=points,
domain_size=shape,
reflect=False)
else:
points = np.array(points)
# Add 3rd column to 2D points
if points.shape[1] == 2:
zeros = np.atleast_2d(np.zeros_like(points[:, 0])).T
points = np.hstack((points, zeros))
# Ensure z-axis is all 0's if shape ends in 0 (ie. square or disk)
if shape[-1] == 0:
points[:, -1] = 0.0
if reflect:
if np.any(tools.isoutside(points, shape=shape)):
raise Exception('Some points lie outside the domain, '
+ 'cannot safely apply reflection')
if len(shape) == 3:
points = reflect_base_points(points=points, domain_size=shape, f=f)
elif len(shape) == 2:
# Convert xyz to cylindrical, and back
R, Q, Z = tools.cart2cyl(*points.T)
R, Q, Z = reflect_base_points(np.vstack((R, Q, Z)), domain_size=shape, f=f)
# Convert back to cartesean coordinates
points = np.vstack(tools.cyl2cart(R, Q, Z)).T
elif len(shape) == 1:
# Convert to spherical coordinates
R, Q, P = tools.cart2sph(*points.T)
R, Q, P = reflect_base_points(np.vstack((R, Q, P)), domain_size=shape, f=f)
# Convert to back to cartesean coordinates
points = np.vstack(tools.sph2cart(R, Q, P)).T
return points
|
Converts given points argument to consistent format
Parameters
----------
shape : array_like
The shape of the domain
points : int or array_like
If a scalar value then this indicates the number of points to generate. If
an array, then these points are used directly.
reflect : bool, optional
If ``True`` the base points are reflected across the borders of the domain.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Returns
-------
points : ndarray
The points after being cleaned and parsed correctly
|
parse_points
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def add_all_label(network):
r"""
Add 'node.all' and 'edge.all' to network dictionary
Parameters
----------
network : dict
The network dictionary, containing 'node.coords' and 'edge.conns'
Returns
-------
network : dict
The supplied dictionary with the 'all' labels added
Notes
-----
This function is helpful for working with OpenPNM
"""
node_prefix = tools.get_node_prefix(network)
edge_prefix = tools.get_edge_prefix(network)
coords = network[node_prefix+'.coords']
conns = network[edge_prefix+'.conns']
network['pore.all'] = np.ones(coords.shape[0], dtype=bool)
network['throat.all'] = np.ones(conns.shape[0], dtype=bool)
return network
|
Add 'node.all' and 'edge.all' to network dictionary
Parameters
----------
network : dict
The network dictionary, containing 'node.coords' and 'edge.conns'
Returns
-------
network : dict
The supplied dictionary with the 'all' labels added
Notes
-----
This function is helpful for working with OpenPNM
|
add_all_label
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def label_faces_cubic(network, rtol=0.0):
r"""
Label the nodes sitting on the faces of the domain assuming the domain
is cubic
Parameters
----------
network : dict
The network dictionary contain 'node.coords'
rtol : float
Controls how closely a node must be to a face to be counted. It is
computed relative to the fraction of domain size, as:
``hi_label = abs(1 - x[i]/x.max()) < rtol`` and
``lo_label = abs(x[i]/x.max()) < rtol``
Returns
-------
network : dict
The network dictionary with the face labels added
"""
node_prefix = tools.get_node_prefix(network)
coords = network[node_prefix+'.coords']
dims = tools.dimensionality(network)
coords = np.around(coords, decimals=10)
min_labels = ['left', 'front', 'bottom']
max_labels = ['right', 'back', 'top']
min_coords = np.amin(coords, axis=0)
max_coords = np.amax(coords, axis=0)
for ax in np.where(dims)[0]:
network[node_prefix + '.' + min_labels[ax]] = \
abs((coords[:, ax]-min_coords[ax])/max_coords[ax]) <= rtol
network[node_prefix + '.' + max_labels[ax]] = \
abs(1-coords[:, ax]/max_coords[ax]) <= rtol
return network
|
Label the nodes sitting on the faces of the domain assuming the domain
is cubic
Parameters
----------
network : dict
The network dictionary contain 'node.coords'
rtol : float
Controls how closely a node must be to a face to be counted. It is
computed relative to the fraction of domain size, as:
``hi_label = abs(1 - x[i]/x.max()) < rtol`` and
``lo_label = abs(x[i]/x.max()) < rtol``
Returns
-------
network : dict
The network dictionary with the face labels added
|
label_faces_cubic
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def _template_sphere_disc(dim, outer_radius, inner_radius):
r"""
This private method generates an image array of a sphere/shell-disc/ring.
It is useful for passing to Cubic networks as a ``template`` to make
networks with desired shapes.
Parameters
----------
dim : int
Network dimension
outer_radius : int
Number of the nodes in the outer radius of the network
inner_radius : int
Number of the nodes in the inner radius of the network
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the desired shape, and 0's
elsewhere.
"""
rmax = np.array(outer_radius, ndmin=1)
rmin = np.array(inner_radius, ndmin=1)
ind = 2 * rmax - 1
coord = np.indices((ind * np.ones(dim, dtype=int)))
coord = coord - (ind - 1)/2
x = coord[0, :]
y = coord[1, :]
if dim == 2:
img = (x ** 2 + y ** 2) < rmax ** 2
elif dim == 3:
z = coord[2, :]
img = (x ** 2 + y ** 2 + z ** 2) < rmax ** 2
if rmin[0] != 0:
if dim == 2:
img_min = (x ** 2 + y ** 2) > rmin ** 2
elif dim == 3:
img_min = (x ** 2 + y ** 2 + z ** 2) > rmin ** 2
img = img * img_min
return img
|
This private method generates an image array of a sphere/shell-disc/ring.
It is useful for passing to Cubic networks as a ``template`` to make
networks with desired shapes.
Parameters
----------
dim : int
Network dimension
outer_radius : int
Number of the nodes in the outer radius of the network
inner_radius : int
Number of the nodes in the inner radius of the network
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the desired shape, and 0's
elsewhere.
|
_template_sphere_disc
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def template_sphere_shell(r_outer, r_inner=0):
r"""
This method generates an image array of a sphere-shell.
It is useful for passing to Cubic networks as a ``template`` to make
spherical shaped networks.
Parameters
----------
r_outer : int
Number of nodes in the outer radius of the sphere
r_inner : int, optional
Number of nodes in the inner radius of the shell. A value of 0 will
result in a solid sphere.
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the sphere-shell, and 0's
elsewhere.
"""
img = _template_sphere_disc(dim=3, outer_radius=r_outer,
inner_radius=r_inner)
return img
|
This method generates an image array of a sphere-shell.
It is useful for passing to Cubic networks as a ``template`` to make
spherical shaped networks.
Parameters
----------
r_outer : int
Number of nodes in the outer radius of the sphere
r_inner : int, optional
Number of nodes in the inner radius of the shell. A value of 0 will
result in a solid sphere.
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the sphere-shell, and 0's
elsewhere.
|
template_sphere_shell
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def template_cylinder_annulus(z, r_outer, r_inner=0):
r"""
This method generates an image array of a disc-ring.
It is useful for passing to Cubic networks as a ``template`` to make
circular-shaped 2D networks.
Parameters
----------
z : int
The height of the cylinder. A value of 0 will result in a circle
r_outer : int
Number of nodes in the outer radius of the cylinder
r_inner : int, optional
Number of the nodes in the inner radius of the annulus. A value of 0
will result in a solid cylinder.
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the disc-ring, and 0's
elsewhere.
"""
img = _template_sphere_disc(dim=2, outer_radius=r_outer,
inner_radius=r_inner)
if z > 0:
img = np.tile(np.atleast_3d(img), reps=z)
return img
|
This method generates an image array of a disc-ring.
It is useful for passing to Cubic networks as a ``template`` to make
circular-shaped 2D networks.
Parameters
----------
z : int
The height of the cylinder. A value of 0 will result in a circle
r_outer : int
Number of nodes in the outer radius of the cylinder
r_inner : int, optional
Number of the nodes in the inner radius of the annulus. A value of 0
will result in a solid cylinder.
Returns
-------
im : array_like
A Numpy array containing 1's to demarcate the disc-ring, and 0's
elsewhere.
|
template_cylinder_annulus
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def reflect_base_points(points, domain_size, f=1):
r"""
Relects a set of points about the faces of a given domain
Parameters
----------
points : ndarray
The coordinates of the points to be reflected. The points should be
in the coordinate system corresponding to the the domain.
domain_size : list or array
Controls the size and shape of the domain, as follows:
========== ============================================================
shape result
========== ============================================================
[x, y, z] Points will be reflected about all 6 faces
[x, y, 0] Points will be relfected about the x and y faces
[r, z] Points will be reflected above and below the end faces and
across the perimeter
[r, 0] Points will be reflected across the perimeter
[r] Points will be reflected across the outer surface
========== ============================================================
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Returns
-------
points : ndarray
The coordinates of the original points plus the new reflected points
"""
assert 0 <= f <= 1, 'f must be between 0 and 1'
domain_size = np.array(domain_size)
if len(domain_size) == 1:
r, theta, phi = points
new_r = 2*domain_size[0] - r
r = np.hstack([r, new_r])
theta = np.hstack([theta, theta])
phi = np.hstack([phi, phi])
points = np.vstack((r, theta, phi))
# Trim excess points outside radius
hi = domain_size[0]*(1+f)
keep = (points[0, :] <= hi)
points = points[:, keep]
if len(domain_size) == 2:
r, theta, z = points
new_r = 2*domain_size[0] - r
r = np.hstack([r, new_r])
theta = np.hstack([theta, theta])
z = np.hstack([z, z])
if domain_size[1] != 0: # If not a disk
r = np.hstack([r, r, r])
theta = np.hstack([theta, theta, theta])
z = np.hstack([z, -z, 2*domain_size[1]-z])
points = np.vstack((r, theta, z))
# Trim excess basepoints above and below cylinder
hi = domain_size[1]*(1+f)
lo = domain_size[1]*(-f)
keep = (points[2, :] <= hi)*(points[2, :] >= lo)
# Trim excess points outside radius
hi = domain_size[0]*(1+f)
keep *= (points[0, :] <= hi)
points = points[:, keep]
elif len(domain_size) == 3:
Nx, Ny, Nz = domain_size
# Reflect base points about all 6 faces
orig_pts = points
points = np.vstack((points,
[-1, 1, 1] * orig_pts + [2.0 * Nx, 0, 0]))
points = np.vstack((points, [-1, 1, 1] * orig_pts))
points = np.vstack((points,
[1, -1, 1] * orig_pts + [0, 2.0 * Ny, 0]))
points = np.vstack((points, [1, -1, 1] * orig_pts))
if domain_size[2] != 0:
points = np.vstack((points,
[1, 1, -1] * orig_pts + [0, 0, 2.0 * Nz]))
points = np.vstack((points, [1, 1, -1] * orig_pts))
# Trim excess basepoints
hi = domain_size*(1+f)
lo = domain_size*(-f)
keep = np.all(points <= hi, axis=1)
keep *= np.all(points >= lo, axis=1)
points = points[keep, :]
return points
|
Relects a set of points about the faces of a given domain
Parameters
----------
points : ndarray
The coordinates of the points to be reflected. The points should be
in the coordinate system corresponding to the the domain.
domain_size : list or array
Controls the size and shape of the domain, as follows:
========== ============================================================
shape result
========== ============================================================
[x, y, z] Points will be reflected about all 6 faces
[x, y, 0] Points will be relfected about the x and y faces
[r, z] Points will be reflected above and below the end faces and
across the perimeter
[r, 0] Points will be reflected across the perimeter
[r] Points will be reflected across the outer surface
========== ============================================================
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Returns
-------
points : ndarray
The coordinates of the original points plus the new reflected points
|
reflect_base_points
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def generate_base_points(num_points, domain_size, reflect=True, f=1):
r"""
Generates a set of randomly distributed points in rectilinear coordinates
for use in spatial tessellations
The points can be distributed in spherical, cylindrical, or rectilinear
domains, as well as 2D and 3D (disks and squares)
Parameters
----------
num_points : scalar
The number of base points that lie within the domain
domain_size : list or array
Controls the size and shape of the domain, as follows:
========== ============================================================
shape result
========== ============================================================
[x, y, z] A 3D cubic domain of dimension x, y and z, with points in
the range [0:x, 0:y, 0:z]
[x, y, 0] A 2D square domain of size x by y, with points in the range
[0:x, 0:y, 0:0]
[r, z] A 3D cylindrical domain of radius r and height z, with
points in the range [-r:r, -r:r, 0:z]
[r, 0] A 2D circular domain of radius r, with points in the range
[-r:r, -r:r, 0:0]
[r] A 3D spherical domain of radius r, with points in the range
[-r:r, -r:r, -r:r]
========== ============================================================
reflect : bool
If ``True``, the base points are generated as specified then reflected
about each face of the domain. This essentially tricks the
tessellation functions into creating smooth faces at the boundaries
once these excess points are trimmed. Note that the surface is not
perfectly smooth for the curved faces.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Notes
-----
To convert between coordinate systems see ``cart2sph`` and ``cart2cyl``
"""
if len(domain_size) == 1: # Spherical
shape = np.array([2*domain_size[0], 2*domain_size[0], 2*domain_size[0]])
base_pts = np.random.rand(num_points*9, 3) # Generate more than needed
# Convert to spherical coordinates
X, Y, Z = ((np.array(base_pts - [0.5, 0.5, 0.5]))*shape).T
R, Q, P = tools.cart2sph(X, Y, Z)
# Keep points outside the domain
inds = R <= domain_size[0]
R, Q, P = R[inds], Q[inds], P[inds]
# Trim internal points to give requested final number
R, Q, P = R[:num_points], Q[:num_points], P[:num_points]
# Reflect base points across perimeter
if reflect:
R, Q, P = reflect_base_points(np.vstack((R, Q, P)), domain_size, f=f)
# Convert to Cartesean coordinates
base_pts = np.vstack(tools.sph2cart(R, Q, P)).T
elif len(domain_size) == 2: # Cylindrical or Disk
shape = np.array([2*domain_size[0], 2*domain_size[0], domain_size[1]])
base_pts = np.random.rand(num_points*9, 3) # Generate more than needed
# Convert to cylindrical coordinates
X, Y, Z = ((np.array(base_pts - [0.5, 0.5, 0]))*shape).T
R, Q, Z = tools.cart2cyl(X, Y, Z)
# Trim points outside the domain
inds = R <= domain_size[0]
R, Q, Z = R[inds], Q[inds], Z[inds]
# Reduce to requested number of points
R, Q, Z = R[:num_points], Q[:num_points], Z[:num_points]
if reflect:
R, Q, Z = reflect_base_points(np.vstack((R, Q, Z)), domain_size, f=f)
# Convert to Cartesean coordinates
base_pts = np.vstack(tools.cyl2cart(R, Q, Z)).T
elif len(domain_size) == 3: # Cube or square
base_pts = np.random.rand(num_points, 3)*domain_size
if reflect:
base_pts = reflect_base_points(base_pts, domain_size, f=f)
return base_pts
|
Generates a set of randomly distributed points in rectilinear coordinates
for use in spatial tessellations
The points can be distributed in spherical, cylindrical, or rectilinear
domains, as well as 2D and 3D (disks and squares)
Parameters
----------
num_points : scalar
The number of base points that lie within the domain
domain_size : list or array
Controls the size and shape of the domain, as follows:
========== ============================================================
shape result
========== ============================================================
[x, y, z] A 3D cubic domain of dimension x, y and z, with points in
the range [0:x, 0:y, 0:z]
[x, y, 0] A 2D square domain of size x by y, with points in the range
[0:x, 0:y, 0:0]
[r, z] A 3D cylindrical domain of radius r and height z, with
points in the range [-r:r, -r:r, 0:z]
[r, 0] A 2D circular domain of radius r, with points in the range
[-r:r, -r:r, 0:0]
[r] A 3D spherical domain of radius r, with points in the range
[-r:r, -r:r, -r:r]
========== ============================================================
reflect : bool
If ``True``, the base points are generated as specified then reflected
about each face of the domain. This essentially tricks the
tessellation functions into creating smooth faces at the boundaries
once these excess points are trimmed. Note that the surface is not
perfectly smooth for the curved faces.
f : float
The fraction of points which should be reflected. The default is 1 which
reflects all the points in the domain, but this can lead to a lot of
unnecessary points, so setting to 0.1 or 0.2 helps speed, but risks that
the tessellation may not have smooth faces if not enough points are
reflected.
Notes
-----
To convert between coordinate systems see ``cart2sph`` and ``cart2cyl``
|
generate_base_points
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/generators/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/generators/tools/_funcs.py
|
MIT
|
def join(g1, g2, L_max=0.99):
r"""
Joins two networks together topologically including new connections
Parameters
----------
g1 : dictionary
A dictionary containing 'node.coords' and 'edge.conns'.
g2 : dictionary
A dictionary containing 'node.coords' and 'edge.conns'
L_max : float
The distance between nodes below which they are joined
Returns
-------
network : dict
A new dictionary containing coords and conns from both ``net1`` and
``net2``, plus new connections between the two input networks.
Notes
-----
The returned network will use the same node and edge prefixes as ``g1``
"""
node_prefix_1 = tools.get_node_prefix(g1)
node_prefix_2 = tools.get_node_prefix(g2)
if node_prefix_1 != node_prefix_2:
for item in g2.keys():
_, prop = item.split('.', 1)
g2[node_prefix_1 + '.' + item] = g2.pop(item)
node_prefix = node_prefix_1
edge_prefix_1 = tools.get_edge_prefix(g1)
edge_prefix_2 = tools.get_edge_prefix(g2)
if edge_prefix_1 != edge_prefix_2:
for item in g2.keys():
_, prop = item.split('.', 1)
g2[edge_prefix_1 + '.' + item] = g2.pop(item)
edge_prefix = edge_prefix_1
# Perform neighbor query
from scipy.spatial import KDTree
t1 = KDTree(g1[node_prefix+'.coords'])
t2 = KDTree(g2[node_prefix+'.coords'])
pairs = t1.query_ball_tree(t2, r=L_max)
# Combine existing network data
net3 = {}
Np1 = g1[node_prefix+'.coords'].shape[0]
Np2 = g2[node_prefix+'.coords'].shape[0]
Nt1 = g1[edge_prefix+'.conns'].shape[0]
Nt2 = g2[edge_prefix+'.conns'].shape[0]
net3[node_prefix+'.coords'] = \
np.vstack((g1.pop(node_prefix+'.coords'),
g2.pop(node_prefix+'.coords')))
net3[edge_prefix+'.conns'] = \
np.vstack((g1.pop(edge_prefix+'.conns'),
g2.pop(edge_prefix+'.conns') + Np1))
# Convert kdtree result into new connections
nnz = sum([len(row) for row in pairs])
conns = np.zeros((nnz, 2), dtype=int)
i = 0
for j, row in enumerate(pairs):
for col in row:
conns[i, :] = j, col + Np1
i += 1
# Add new connections to network
net3[edge_prefix+'.conns'] = \
np.vstack((net3.pop(edge_prefix+'.conns'), conns))
# Finally, expand any other data arrays on given networks
items = list(g1.keys()) + list(g2.keys())
N = {node_prefix: [Np1, Np2], edge_prefix: [Nt1, Nt2]}
for item in items:
prefix, attr = item.split('.', 1)
if prefix == node_prefix:
temp1 = g1.pop(item, None)
temp2 = g2.pop(item, None)
if prefix == edge_prefix:
temp1 = g1.pop(item, None)
temp2 = g2.pop(item, None)
if temp1 is None:
blank = False if temp2.dtype == bool else np.nan
temp1 = np.zeros(N[prefix][0], dtype=type(blank))*blank
elif temp2 is None:
blank = False if temp1.dtype == bool else np.nan
temp2 = np.zeros(N[prefix][1], dtype=type(blank))*blank
net3[item] = np.concatenate((temp1, temp2), axis=0)
return net3
|
Joins two networks together topologically including new connections
Parameters
----------
g1 : dictionary
A dictionary containing 'node.coords' and 'edge.conns'.
g2 : dictionary
A dictionary containing 'node.coords' and 'edge.conns'
L_max : float
The distance between nodes below which they are joined
Returns
-------
network : dict
A new dictionary containing coords and conns from both ``net1`` and
``net2``, plus new connections between the two input networks.
Notes
-----
The returned network will use the same node and edge prefixes as ``g1``
|
join
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_binary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_binary.py
|
MIT
|
def add_nodes(network, new_coords):
r"""
Given a list of node coordinates, add them to the network
Parameters
----------
network : dict
A dictionary containing the node and edge attributes as ndarrays
new_coords : ndarray
The N-by-3 array of coordinates of the new nodes
Returns
-------
network : dict
The network dictionary with the new nodes added to the end. Note that
any existing node attributes are also extended and filled with default
values specified in ``settings.default_values``
"""
# TODO: At present this does not work with empty networks. It's a bit
# challenging to determine what size each 'empty' array should become.
# It's fine for 1D arrays like ``np.array([])``, but for N-dimensional
# stuff it's trickier. For instance ``np.array([[], []])`` has a shape
# of (2, 0) so the empty dimension is the wrong one since all the array
# extending in this function occurs on the 1st axis.
g = network
node_prefix = tools.get_node_prefix(g)
coords = np.atleast_2d(new_coords)
Nnew = coords.shape[0]
for k, v in g.items():
if k.startswith(node_prefix):
dval = None
for t in settings.missing_values.keys():
if v.dtype == t:
dval = settings.missing_values[t]
blank = np.repeat(v[:1, ...], Nnew, axis=0)*dval
blank.fill(dval)
g[k] = np.concatenate((v, blank), axis=0).astype(v.dtype)
# Lastly, overwrite the -Nnew elements of coords with the given values
g[node_prefix+'.coords'][-Nnew:] = np.array(coords)
return g
|
Given a list of node coordinates, add them to the network
Parameters
----------
network : dict
A dictionary containing the node and edge attributes as ndarrays
new_coords : ndarray
The N-by-3 array of coordinates of the new nodes
Returns
-------
network : dict
The network dictionary with the new nodes added to the end. Note that
any existing node attributes are also extended and filled with default
values specified in ``settings.default_values``
|
add_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def add_edges(network, new_conns):
r"""
Given a list of edge connections, add them to the network
Parameters
----------
network : dict
A dictionary containing the node and edge attributes as ndarrays
new_conns : ndarray
The N-by-2 array of connections betwween existing nodes
Returns
-------
network : dict
The network dictionary with the new edges added to the end. Note that
any existing edge attributes are also extended and filled with default
values specified in ``settings.default_values``.
"""
# TODO: At present this does not work with empty networks. It's a bit
# challenging to determine what size each 'empty' array should become.
# It's fine for 1D arrays like ``np.array([])``, but for N-dimensional
# stuff it's trickier. For instance ``np.array([[], []])`` has a shape
# of (2, 0) so the empty dimension is the wrong one since all the array
# extending in this function occurs on the 1st axis.
g = network
edge_prefix = tools.get_edge_prefix(g)
conns = np.atleast_2d(new_conns)
Nnew = conns.shape[0]
for k, v in g.items():
if k.startswith(edge_prefix):
dval = None
for t in settings.missing_values.keys():
if v.dtype == t:
dval = settings.missing_values[t]
blank = np.repeat(v[:1, ...], Nnew, axis=0)*dval
blank.fill(dval)
g[k] = np.concatenate((v, blank), axis=0).astype(v.dtype)
# Lastly, overwrite the -Nnew elements of coords with the given values
g[edge_prefix+'.conns'][-Nnew:] = np.array(conns)
return g
|
Given a list of edge connections, add them to the network
Parameters
----------
network : dict
A dictionary containing the node and edge attributes as ndarrays
new_conns : ndarray
The N-by-2 array of connections betwween existing nodes
Returns
-------
network : dict
The network dictionary with the new edges added to the end. Note that
any existing edge attributes are also extended and filled with default
values specified in ``settings.default_values``.
|
add_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def trim_edges(network, inds):
r"""
Removes given edges from a graph or network
Parameters
----------
network : dictionary
A dictionary containing coords, conns and other attributes
inds : array_like
The edge indices to be trimmed in the form of a 1D list or boolean
mask with ``True`` values indicating indices to trim.
Returns
-------
network : dict
The dictionary with all edge arrays trimmed accordingly
"""
g = network
edge_prefix = tools.get_edge_prefix(g)
N_bonds = g[edge_prefix+'.conns'].shape[0]
inds = np.atleast_1d(inds)
keep = np.ones(N_bonds, dtype=bool)
keep[inds] = False
for k, v in g.items():
if k.startswith(edge_prefix):
g[k] = v[keep]
return g
|
Removes given edges from a graph or network
Parameters
----------
network : dictionary
A dictionary containing coords, conns and other attributes
inds : array_like
The edge indices to be trimmed in the form of a 1D list or boolean
mask with ``True`` values indicating indices to trim.
Returns
-------
network : dict
The dictionary with all edge arrays trimmed accordingly
|
trim_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def trim_nodes(network, inds):
r"""
Removes given nodes and any connected edges from a graph or network
Parameters
----------
network : dict
A dictionary containing coords, conns and other attributes
inds : array_like
The node indices to be trimmed in the form of a 1D list or boolean
mask with ``True`` values indicating indices to trim.
Returns
-------
network : dict
The dictionary with all nodes arrays trimmed accordingly, all edges
trimmed that were connected to the trimmed nodes, and the 'edge.conns'
array renumbered so edges point to the updated node indices.
"""
node_prefix = tools.get_node_prefix(network)
edge_prefix = tools.get_edge_prefix(network)
N_sites = network[node_prefix+'.coords'].shape[0]
inds = np.atleast_1d(inds)
if inds.dtype == bool:
inds = np.where(inds)[0]
keep = np.ones(N_sites, dtype=bool)
keep[inds] = False
for k, v in network.items():
if k.startswith(node_prefix):
network[k] = v[keep]
# Remove edges
edges = np.any(np.isin(network[edge_prefix+'.conns'], inds), axis=1)
network = trim_edges(network, inds=edges)
# Renumber conns
remapping = np.cumsum(keep) - 1
network[edge_prefix+'.conns'] = remapping[network[edge_prefix+'.conns']]
return network
|
Removes given nodes and any connected edges from a graph or network
Parameters
----------
network : dict
A dictionary containing coords, conns and other attributes
inds : array_like
The node indices to be trimmed in the form of a 1D list or boolean
mask with ``True`` values indicating indices to trim.
Returns
-------
network : dict
The dictionary with all nodes arrays trimmed accordingly, all edges
trimmed that were connected to the trimmed nodes, and the 'edge.conns'
array renumbered so edges point to the updated node indices.
|
trim_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def drop_nodes_from_am(am, inds):
r"""
Update adjacency matrix after dropping nodes
Parameters
----------
am : scipy.sparse matrix
The adjacency matrix of the network in COO format.
inds : array_like
A list of which nodes indices to drop. Can either be integer indices
or a boolean mask with ``True`` indicating which locations to drop
Returns
-------
am : ndarray
An updated adjacency matrix with nodes and headless edges removed,
and node indices updated accordingly
dropped_edges : ndarray
A boolean array with ``True`` values indicating which edges
were rendered headless. This can be used to drop invalid edges
from other arrays (i.e. array = array[~dropped_edges]).
"""
nodes = np.array(inds)
if nodes.dtype != bool:
inds = np.copy(nodes)
nodes = np.zeros(am.shape[0], dtype=bool)
nodes[inds] = True
node_mask = ~nodes
conns = np.vstack((am.row, am.col)).T
node_id = np.cumsum(node_mask) - 1
edge_mask = ~np.all(node_mask[conns], axis=1)
conns = node_id[conns[~edge_mask]]
am = sprs.coo_matrix((am.data[~edge_mask], (conns[:, 0], conns[:, 1])))
return am, edge_mask
|
Update adjacency matrix after dropping nodes
Parameters
----------
am : scipy.sparse matrix
The adjacency matrix of the network in COO format.
inds : array_like
A list of which nodes indices to drop. Can either be integer indices
or a boolean mask with ``True`` indicating which locations to drop
Returns
-------
am : ndarray
An updated adjacency matrix with nodes and headless edges removed,
and node indices updated accordingly
dropped_edges : ndarray
A boolean array with ``True`` values indicating which edges
were rendered headless. This can be used to drop invalid edges
from other arrays (i.e. array = array[~dropped_edges]).
|
drop_nodes_from_am
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def split_edges(network):
r"""
Inserts an new node between each existing node and joins with new edges
Parameters
----------
network : dict
The dictionary containing the network connections and coordinates
Returns
-------
result : tuple
A tuple containing ``new_conns`` and optionally ``new_coords`` if
``coords`` was provided.
============== ========================================================
Value Description
============== ========================================================
``new_conns`` A new adjacency matrix in COO format with new nodes
added between each original node. If edge 1 connected
nodes 1 and 2, then row 1 of the new sparse adjacency
matrix will be [1, Nt + 1], and row Nt + 1 will be
[Nt + 1, 2].
``new_coords`` A and updated list of node coordinates with the new
nodes appended to the end. The coordinates of the new
nodes are taken as the average of the two nodes between
which they were inserted.
============== ========================================================
"""
g = network
node_prefix = tools.get_node_prefix(g)
edge_prefix = tools.get_edge_prefix(g)
conns = g[edge_prefix + '.conns']
coords = g[node_prefix + '.coords']
Nt = conns.shape[0]
Np = conns.max() + 1
new_conns = np.zeros([2*Nt, 2], dtype=int)
new_conns[:Nt, :] = np.vstack((conns[:, 0], np.arange(Np, Np+Nt))).T
new_conns[Nt:, :] = np.vstack((np.arange(Np, Np+Nt), conns[:, 1])).T
result = (new_conns, )
if coords is not None:
Np = coords.shape[0]
new_coords = np.zeros([Np + Nt, 3], dtype=float)
new_coords[:Np, :] = coords
new_coords[Np:, :] = np.mean(coords[conns], axis=1)
result = (new_conns, new_coords)
return result
|
Inserts an new node between each existing node and joins with new edges
Parameters
----------
network : dict
The dictionary containing the network connections and coordinates
Returns
-------
result : tuple
A tuple containing ``new_conns`` and optionally ``new_coords`` if
``coords`` was provided.
============== ========================================================
Value Description
============== ========================================================
``new_conns`` A new adjacency matrix in COO format with new nodes
added between each original node. If edge 1 connected
nodes 1 and 2, then row 1 of the new sparse adjacency
matrix will be [1, Nt + 1], and row Nt + 1 will be
[Nt + 1, 2].
``new_coords`` A and updated list of node coordinates with the new
nodes appended to the end. The coordinates of the new
nodes are taken as the average of the two nodes between
which they were inserted.
============== ========================================================
|
split_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/operations/_unary.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/operations/_unary.py
|
MIT
|
def find_complementary_edges(network, inds, asmask=False):
r"""
Finds the complementary edges to a given set of inputs
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of edge indices for which the complement is sought
asmask : bool
If set to ``True`` the result is returned as a boolean mask of the
correct length with ``True`` values indicate the complements. The
default is ``False`` which returns a list of indices instead.
Returns
-------
An array containing indices of the edges that are not part of the input
list
"""
edge_prefix = get_edge_prefix(network)
inds = np.unique(inds)
N = network[edge_prefix+'.conns'].shape[0]
mask = np.ones(shape=N, dtype=bool)
mask[inds] = False
if asmask:
return mask
else:
return np.arange(N)[mask]
|
Finds the complementary edges to a given set of inputs
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of edge indices for which the complement is sought
asmask : bool
If set to ``True`` the result is returned as a boolean mask of the
correct length with ``True`` values indicate the complements. The
default is ``False`` which returns a list of indices instead.
Returns
-------
An array containing indices of the edges that are not part of the input
list
|
find_complementary_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_complementary_nodes(network, inds, asmask=False):
r"""
Finds the complementary nodes to a given set of inputs
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
A list of indices for which the complement is sought
asmask : bool
If set to ``True`` the result is returned as a boolean mask of the
correct length with ``True`` values indicate the complements. The
default is ``False`` which returns a list of indices instead.
Returns
-------
An array containing indices of the nodes that are not part of the input
list
"""
node_prefix = get_node_prefix(network)
inds = np.unique(inds)
N = network[node_prefix+'.coords'].shape[0]
mask = np.ones(shape=N, dtype=bool)
mask[inds] = False
if asmask:
return mask
else:
return np.arange(N)[mask]
|
Finds the complementary nodes to a given set of inputs
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
A list of indices for which the complement is sought
asmask : bool
If set to ``True`` the result is returned as a boolean mask of the
correct length with ``True`` values indicate the complements. The
default is ``False`` which returns a list of indices instead.
Returns
-------
An array containing indices of the nodes that are not part of the input
list
|
find_complementary_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_connected_nodes(network, inds, flatten=True, logic='or'):
r"""
Finds which nodes are connected to a given set of edges
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of edges indices whose connected nodes are sought
flatten : bool (default is ``True``)
Indicates whether the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input edge. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (sometimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
An array containing the connected sites, filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each given input edge. In this latter case, nodes that
have been removed by the given logic are indicated by ``nans``, thus the
array is of type ``float`` and is not suitable for indexing.
"""
if not isgtriu(network):
raise Exception("This function is not implemented for directed networks")
edges = np.array(inds, ndmin=1)
if len(edges) == 0: # Short-circuit this function if edges is empty
return []
am = dict_to_am(network)
neighbors = np.hstack((am.row[edges], am.col[edges]))
if neighbors.size > 0:
n_sites = np.amax(neighbors)
if logic in ['or', 'union', 'any']:
neighbors = np.unique(neighbors)
elif logic in ['xor', 'exclusive_or']:
neighbors = np.unique(np.where(np.bincount(neighbors) == 1)[0])
elif logic in ['xnor', 'nxor']:
neighbors = np.unique(np.where(np.bincount(neighbors) > 1)[0])
elif logic in ['and', 'all', 'intersection']:
temp = np.vstack((am.row[edges], am.col[edges])).T.tolist()
temp = [set(pair) for pair in temp]
neighbors = temp[0]
[neighbors.intersection_update(pair) for pair in temp[1:]]
neighbors = np.array(list(neighbors), dtype=np.int64, ndmin=1)
else:
raise Exception('Specified logic is not implemented')
if flatten is False:
if neighbors.size:
mask = np.zeros(shape=n_sites + 1, dtype=bool)
mask[neighbors] = True
temp = np.hstack((am.row[edges], am.col[edges])).astype(np.int64)
temp[~mask[temp]] = -1
inds = np.where(temp == -1)[0]
if len(inds):
temp = temp.astype(float)
temp[inds] = np.nan
temp = np.reshape(a=temp, newshape=[len(edges), 2], order='F')
neighbors = temp
else:
neighbors = [np.array([], dtype=np.int64) for i in range(len(edges))]
return neighbors
|
Finds which nodes are connected to a given set of edges
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of edges indices whose connected nodes are sought
flatten : bool (default is ``True``)
Indicates whether the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input edge. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (sometimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
An array containing the connected sites, filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each given input edge. In this latter case, nodes that
have been removed by the given logic are indicated by ``nans``, thus the
array is of type ``float`` and is not suitable for indexing.
|
find_connected_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_neighbor_edges(network, inds, flatten=True, logic='or'):
r"""
Finds all edges that are connected to the given input nodes
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
A list of node indices whose neighbor edges are sought
flatten : bool (default is ``True``)
Indicates whether the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input node. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (somtimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
An array containing the neighboring edges filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each given input node.
Notes
-----
The ``logic`` options are applied to neighboring edges only, thus it is not
possible to obtain edges that are part of the global set but not neighbors.
This is because (a) the list of global edges might be very large, and
(b) it is not possible to return a list of neighbors for each input site
if global sites are considered.
"""
if flatten == False:
im = dict_to_im(network)
am = None
else:
am = dict_to_am(network)
im = None
if im is not None:
if im.format != 'lil':
im = im.tolil(copy=False)
rows = [im.rows[i] for i in np.array(inds, ndmin=1, dtype=np.int64)]
if len(rows) == 0:
return []
neighbors = np.hstack(rows).astype(np.int64)
n_bonds = int(im.nnz / 2)
if logic in ['or', 'union', 'any']:
neighbors = np.unique(neighbors)
elif logic in ['xor', 'exclusive_or']:
neighbors = np.unique(np.where(np.bincount(neighbors) == 1)[0])
elif logic in ['xnor', 'shared']:
neighbors = np.unique(np.where(np.bincount(neighbors) > 1)[0])
elif logic in ['and', 'all', 'intersection']:
neighbors = set(neighbors)
[neighbors.intersection_update(i) for i in rows]
neighbors = np.array(list(neighbors), dtype=int, ndmin=1)
else:
raise Exception('Specified logic is not implemented')
if (flatten is False):
if (neighbors.size > 0):
mask = np.zeros(shape=n_bonds, dtype=bool)
mask[neighbors] = True
for i in range(len(rows)):
vals = np.array(rows[i], dtype=np.int64)
rows[i] = vals[mask[vals]]
neighbors = rows
else:
neighbors = [np.array([], dtype=np.int64) for i in range(len(inds))]
return neighbors
elif am is not None:
if am.format != 'coo':
am = am.tocoo(copy=False)
if flatten is False:
raise Exception('flatten cannot be used with an adjacency matrix')
if isgtriu(network):
am = sprs.triu(am, k=1)
Ps = np.zeros(am.shape[0], dtype=bool)
Ps[inds] = True
conns = np.vstack((am.row, am.col)).T
if logic in ['or', 'union', 'any']:
neighbors = np.any(Ps[conns], axis=1)
elif logic in ['xor', 'exclusive_or']:
neighbors = np.sum(Ps[conns], axis=1) == 1
elif logic in ['xnor', 'shared']:
neighbors = np.all(Ps[conns], axis=1)
elif logic in ['and', 'all', 'intersection']:
raise Exception('Specified logic is not implemented')
else:
raise Exception('Specified logic is not implemented')
neighbors = np.where(neighbors)[0]
return neighbors
else:
raise Exception('Either the incidence or the adjacency matrix must be specified')
|
Finds all edges that are connected to the given input nodes
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
A list of node indices whose neighbor edges are sought
flatten : bool (default is ``True``)
Indicates whether the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input node. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (somtimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
An array containing the neighboring edges filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each given input node.
Notes
-----
The ``logic`` options are applied to neighboring edges only, thus it is not
possible to obtain edges that are part of the global set but not neighbors.
This is because (a) the list of global edges might be very large, and
(b) it is not possible to return a list of neighbors for each input site
if global sites are considered.
|
find_neighbor_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_neighbor_nodes(network, inds, flatten=True, include_input=False,
logic='or'):
r"""
Finds all nodes that are directly connected to the input nodes
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of node indices whose neighbors are sought
flatten : bool
If ``True`` (default) the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input site. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
include_input : bool
If ``False`` (default) the input nodes will be removed from the result.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (somtimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
nodes : ndarray
An array containing the neighboring nodes filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each input site.
Notes
-----
The ``logic`` options are applied to neighboring nodes only, thus it is not
possible to obtain nodes that are part of the global set but not neighbors.
This is because the list of global nodes might be very large.
"""
g = network
nodes = np.array(inds, ndmin=1)
# Short-circuit the function if the input list is already empty
if len(nodes) == 0:
return []
am_coo = dict_to_am(g)
am = am_coo.tolil(copy=False)
rows = am.rows[nodes].tolist()
if len(rows) == 0:
return []
n_nodes = am.shape[0]
neighbors = am_coo.col[np.in1d(am_coo.row, nodes)]
if logic in ['or', 'union', 'any']:
neighbors = np.unique(neighbors)
elif logic in ['xor', 'exclusive_or']:
neighbors = np.unique(np.where(np.bincount(neighbors) == 1)[0])
elif logic in ['xnor', 'nxor']:
neighbors = np.unique(np.where(np.bincount(neighbors) > 1)[0])
elif logic in ['and', 'all', 'intersection']:
neighbors = set(neighbors)
[neighbors.intersection_update(i) for i in rows]
neighbors = np.array(list(neighbors), dtype=np.int64, ndmin=1)
else:
raise Exception('Specified logic is not implemented')
# Deal with removing inputs or not
mask = np.zeros(shape=n_nodes, dtype=bool)
mask[neighbors] = True
if not include_input:
mask[nodes] = False
# Finally flatten or not
if flatten:
neighbors = np.where(mask)[0]
else:
if neighbors.size > 0:
for i in range(len(rows)):
vals = np.array(rows[i], dtype=np.int64)
rows[i] = vals[mask[vals]]
neighbors = rows
else:
neighbors = [np.array([], dtype=int) for i in range(len(nodes))]
return neighbors
|
Finds all nodes that are directly connected to the input nodes
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list of node indices whose neighbors are sought
flatten : bool
If ``True`` (default) the returned result is a compressed array of all
neighbors, or a list of lists with each sub-list containing the
neighbors for each input site. Note that an *unflattened* list might
be slow to generate since it is a Python ``list`` rather than a Numpy
array.
include_input : bool
If ``False`` (default) the input nodes will be removed from the result.
logic : str
Specifies logic to filter the resulting list. Options are:
======= ===============================================================
logic Description
======= ===============================================================
'or' (default) All neighbors of the inputs. This is also known as
the 'union' in set theory or 'any' in boolean logic. Both
keywords are accepted and treated as 'or'.
'xor' Only neighbors of one and only one inputs. This is useful for
finding neighbors that are not *shared* by any of the input
nodes. 'exclusive_or' is also accepted.
'xnor' Neighbors that are shared by two or more inputs . This is
equivalent to finding all neighbors with 'or', minus those
found with 'xor', and is useful for finding neighbors that the
inputs have in common. 'nxor' is also accepted.
'and' Only neighbors shared by all inputs. This is also known as
'intersection' in set theory and (somtimes) as 'all' in
boolean logic. Both keywords are accepted and treated as
'and'.
======= ===============================================================
Returns
-------
nodes : ndarray
An array containing the neighboring nodes filtered by the given logic. If
``flatten`` is ``False`` then the result is a list of lists containing the
neighbors of each input site.
Notes
-----
The ``logic`` options are applied to neighboring nodes only, thus it is not
possible to obtain nodes that are part of the global set but not neighbors.
This is because the list of global nodes might be very large.
|
find_neighbor_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_connecting_edges(inds, network=None, am=None):
r"""
Finds the edge that connects each pair of given nodes
Parameters
----------
inds : array_like
A 2-column vector containing pairs of node indices
network : dict, optional
The network dictionary. Either this or ``am`` must be provided
am : scipy.sparse matrix, optional
The adjacency matrix of the network. Must be symmetrical such that if
nodes *i* and *j* are connected, the matrix contains non-zero values
at locations (i, j) and (j, i). Either this or ``g`` must be provided.
Returns
-------
edges : ndarray
An ndarry the same length as P1 (and P2) with each element
containing the edge number that connects the corresponding nodes,
or `nan`` if nodes are not connected.
Notes
-----
The adjacency matrix is converted to the ``DOK`` format internally if
needed, so if this format is already available it should be provided to
save time.
"""
nodes = np.array(inds, ndmin=2)
# Short-circuit function if nodes is an empty list
if nodes.size == 0:
return []
if network is not None:
edge_prefix = get_edge_prefix(network)
am = dict_to_am(
network,
weights=np.arange(network[edge_prefix+'.conns'].shape[0])
)
elif am is not None:
pass
else:
raise Exception('Either g or am must be provided')
if am.format != 'dok':
am = am.todok(copy=True)
z = tuple(zip(nodes[:, 0], nodes[:, 1]))
neighbors = np.array([am.get(item, np.nan) for item in z])
return neighbors
|
Finds the edge that connects each pair of given nodes
Parameters
----------
inds : array_like
A 2-column vector containing pairs of node indices
network : dict, optional
The network dictionary. Either this or ``am`` must be provided
am : scipy.sparse matrix, optional
The adjacency matrix of the network. Must be symmetrical such that if
nodes *i* and *j* are connected, the matrix contains non-zero values
at locations (i, j) and (j, i). Either this or ``g`` must be provided.
Returns
-------
edges : ndarray
An ndarry the same length as P1 (and P2) with each element
containing the edge number that connects the corresponding nodes,
or `nan`` if nodes are not connected.
Notes
-----
The adjacency matrix is converted to the ``DOK`` format internally if
needed, so if this format is already available it should be provided to
save time.
|
find_connecting_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_common_edges(network, inds_1, inds_2):
"""
Finds edges shared between two sets of nodes
Parameters
----------
network : dict
The network dictionary
inds_1 : array_like
A list of indices defining the first set of nodes
inds_2 : array_like
A list of indices defining the second set of nodes
Returns
-------
edges : ndarray
List of edge indices connecting the two given sets of nodes
"""
if np.intersect1d(inds_1, inds_2).size != 0:
raise Exception("inds_1 and inds_2 must not share any nodes")
if not isgtriu(network):
raise Exception("This function is not implemented for directed graphs")
edges_1 = find_neighbor_edges(inds=inds_1, network=network, logic="xor")
edges_2 = find_neighbor_edges(inds=inds_2, network=network, logic="xor")
return np.intersect1d(edges_1, edges_2)
|
Finds edges shared between two sets of nodes
Parameters
----------
network : dict
The network dictionary
inds_1 : array_like
A list of indices defining the first set of nodes
inds_2 : array_like
A list of indices defining the second set of nodes
Returns
-------
edges : ndarray
List of edge indices connecting the two given sets of nodes
|
find_common_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def filter_by_z(network, inds, z=1):
r"""
Filters a list of nodes to those with a given number of neighbors
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list containing the indices of the nodes to be filtered
z : int
The coordination number by which to filter
Returns
-------
inds : array_like
A list of node indices which satisfy the criteria
"""
inds = np.array(inds)
coordination = find_coordination(network)
hits = coordination == z
inds = inds[hits[inds]]
return inds
|
Filters a list of nodes to those with a given number of neighbors
Parameters
----------
network : dict
The network dictionary
inds : array_like
A list containing the indices of the nodes to be filtered
z : int
The coordination number by which to filter
Returns
-------
inds : array_like
A list of node indices which satisfy the criteria
|
filter_by_z
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_coordination(network, nodes=None):
r"""
Find the coordination number of nodes
Parameters
----------
network : dict
The network dictionary
nodes : array_like, optional
The nodes for which coordination is sought. If not provided then
coordination for *all* nodes is returned
Returns
-------
z : ndarray
An array containing the number of neighbors for each given node
Notes
-----
Supports directed and undirected graphs
"""
am = dict_to_am(network)
z = am.getnnz(axis=1)
if nodes is None:
return z
else:
return z[np.array(nodes)]
|
Find the coordination number of nodes
Parameters
----------
network : dict
The network dictionary
nodes : array_like, optional
The nodes for which coordination is sought. If not provided then
coordination for *all* nodes is returned
Returns
-------
z : ndarray
An array containing the number of neighbors for each given node
Notes
-----
Supports directed and undirected graphs
|
find_coordination
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def find_path(network, pairs, weights=None):
r"""
Find the shortest path between pairs of nodes
Parameters
----------
network : dict
The network dictionary
pairs : array_like
An N x 2 array containing N pairs of nodes between which the shortest
path is sought
weights : ndarray, optional
The edge weights to use when traversing the path. If not provided
then 1's will be used.
Returns
-------
paths : dict
A dictionary containing ``'node_paths'`` and ``'edge_paths'``, each
containing a list of lists indicating the path between each set of
nodes given in ``pairs``. An empty list indicates that no path was
found between a given set of pairs.
Notes
-----
The shortest path is found using Dijkstra's algorithm included in the
``scipy.sparse.csgraph`` module
"""
am = dict_to_am(network)
if weights is not None:
am.data = np.ones_like(am.row, dtype=int)
pairs = np.array(pairs, ndmin=2)
paths = csgraph.dijkstra(csgraph=am, indices=pairs[:, 0],
return_predecessors=True, min_only=False)[1]
if isgtriu(network):
am.data = np.hstack(2*[np.arange(am.data.size/2)]).astype(int)
else:
am.data = np.arange(am.data.size).astype(int)
dok = am.todok()
nodes = []
edges = []
for row in range(0, np.shape(pairs)[0]):
j = pairs[row][1]
ans = []
while paths[row][j] > -9999:
ans.append(j)
j = paths[row][j]
if len(ans) > 0:
ans.append(pairs[row][0])
ans.reverse()
nodes.append(np.array(ans, dtype=int))
keys = [tuple((ans[i], ans[i+1])) for i in range(len(ans)-1)]
temp = [dok[k] for k in keys]
edges.append(np.array(temp, dtype=int))
else:
nodes.append([])
edges.append([])
return {'node_paths': nodes, 'edge_paths': edges}
|
Find the shortest path between pairs of nodes
Parameters
----------
network : dict
The network dictionary
pairs : array_like
An N x 2 array containing N pairs of nodes between which the shortest
path is sought
weights : ndarray, optional
The edge weights to use when traversing the path. If not provided
then 1's will be used.
Returns
-------
paths : dict
A dictionary containing ``'node_paths'`` and ``'edge_paths'``, each
containing a list of lists indicating the path between each set of
nodes given in ``pairs``. An empty list indicates that no path was
found between a given set of pairs.
Notes
-----
The shortest path is found using Dijkstra's algorithm included in the
``scipy.sparse.csgraph`` module
|
find_path
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/queries/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/queries/_funcs.py
|
MIT
|
def bond_percolation(conns, occupied_bonds):
r"""
Assigns cluster numbers to sites and bonds acccording to a bond
percolation process, given a list of occupied bonds.
Parameters
----------
conns : array_like
An N x 2 array connections. Any sites connected to an occupied bond
will also be considered occupied and given the same cluster number
as the bond.
occupied_bonds : ndarray
A boolean array with one element for each bond, with ``True`` values
indicating that a bond is occupied
Returns
-------
A tuple containing a list of site and bond labels, indicating which
cluster each belongs to. A value of -1 indicates uninvaded.
Notes
-----
The ``connected_components`` function of ``scipy.sparse.csgraph`` will give
a cluster number to ALL bonds whether they are occupied or not, so this
function essentially adjusts the cluster numbers to represent a
percolation process.
"""
Np = np.amax(conns) + 1
# Find occupied sites based on status of shared bonds
occupied_sites = np.zeros([Np, ], dtype=bool)
occupied_sites[conns[occupied_bonds].flatten()] = True
# Perform cluster labeling of network
adj_mat = sprs.csr_matrix((occupied_bonds.astype(int),
(conns[:, 0], conns[:, 1])),
shape=(Np, Np))
adj_mat.eliminate_zeros()
clusters = csgraph.connected_components(csgraph=adj_mat, directed=False)[1]
# Set cluster number of unoccupied sites to -1
s_labels = (clusters + 1)*occupied_sites - 1
# Bonds inherit the cluster number of its connected sites
b_labels = np.amin(s_labels[conns], axis=1)
# Set cluster number of unoccupied bonds to -1
b_labels[~occupied_bonds] = -1
tup = namedtuple('cluster_labels', ('site_labels', 'bond_labels'))
return tup(s_labels, b_labels)
|
Assigns cluster numbers to sites and bonds acccording to a bond
percolation process, given a list of occupied bonds.
Parameters
----------
conns : array_like
An N x 2 array connections. Any sites connected to an occupied bond
will also be considered occupied and given the same cluster number
as the bond.
occupied_bonds : ndarray
A boolean array with one element for each bond, with ``True`` values
indicating that a bond is occupied
Returns
-------
A tuple containing a list of site and bond labels, indicating which
cluster each belongs to. A value of -1 indicates uninvaded.
Notes
-----
The ``connected_components`` function of ``scipy.sparse.csgraph`` will give
a cluster number to ALL bonds whether they are occupied or not, so this
function essentially adjusts the cluster numbers to represent a
percolation process.
|
bond_percolation
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/simulations/_percolation.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/simulations/_percolation.py
|
MIT
|
def site_percolation(conns, occupied_sites):
r"""
Assigns cluster numbers to sites and bonds acccording to a site
percolation process, given a list of occupied sites.
Parameters
----------
conns : array_like
An N x 2 array connections. If two connected sites are both occupied
they are part of the same cluster, as is the bond connecting them.
occupied_sites : ndarray
A boolean array with one element for each site, with ``True`` values
indicating that a site is occupied
Returns
-------
A tuple containing a list of site and bond labels, indicating which
cluster each belongs to. A value of -1 indicates unoccupied.
Notes
-----
The ``connected_components`` function of ``scipy.sparse.csgraph`` will
give ALL sites a cluster number whether they are occupied or not, so this
function essentially adjusts the cluster numbers to represent a
percolation process.
"""
Np = np.size(occupied_sites)
# Find bond occupancy based on status of its connected sites
occupied_bonds = np.all(occupied_sites[conns], axis=1)
# Perform cluster labeling of network
adj_mat = sprs.csr_matrix((occupied_bonds, (conns[:, 0], conns[:, 1])),
shape=(Np, Np))
adj_mat.eliminate_zeros()
clusters = csgraph.connected_components(csgraph=adj_mat, directed=False)[1]
# Set cluster number of unoccupied sites to -1
s_labels = (clusters + 1)*occupied_sites - 1
# Bonds inherit the cluster number of its connected sites
b_labels = np.amin(s_labels[conns], axis=1)
# Set cluster number of unoccupied bonds to -1
b_labels[~occupied_bonds] = -1
tup = namedtuple('cluster_labels', ('site_labels', 'bond_labels'))
return tup(s_labels, b_labels)
|
Assigns cluster numbers to sites and bonds acccording to a site
percolation process, given a list of occupied sites.
Parameters
----------
conns : array_like
An N x 2 array connections. If two connected sites are both occupied
they are part of the same cluster, as is the bond connecting them.
occupied_sites : ndarray
A boolean array with one element for each site, with ``True`` values
indicating that a site is occupied
Returns
-------
A tuple containing a list of site and bond labels, indicating which
cluster each belongs to. A value of -1 indicates unoccupied.
Notes
-----
The ``connected_components`` function of ``scipy.sparse.csgraph`` will
give ALL sites a cluster number whether they are occupied or not, so this
function essentially adjusts the cluster numbers to represent a
percolation process.
|
site_percolation
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/simulations/_percolation.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/simulations/_percolation.py
|
MIT
|
def trim_disconnected_clusters(b_labels, s_labels, inlets):
r"""
Computes actual node and edge occupancy based on connectivity to the given
inlets
Parameters
----------
b_labels : ndarray
An array of cluster labels assigned to each bond. -1 indicates
unoccupied
s_labels : ndarray
An array of cluster labels assigned to each site. -1 indicates
unoccupied. Site cluster numbers must correspond to the bond
clusters, such that if bond j has a cluster number N, then both
sites on each end of j are also labeled N.
inlets : ndarray
An array containing node indices that are to be treated as inlets.
Any clusters labels not found in these nodes will be considered
disconnected and set to -1.
Returns
-------
occupancy : tuple of ndarrays
The returned tuple containing arrays of cluster numbers of
``occupied_sites`` and ``occupied_bonds``, after accounting for
connection to the ``inlets``.
Notes
-----
The ``b_labels`` and ``s_labels`` arrays are returned from the
``bond_percolation`` or ``site_percolation`` function.
"""
hits = np.unique(s_labels[inlets])
hits = hits[hits >= 0]
occupied_bonds = np.isin(b_labels, hits)*(b_labels + 1) - 1
occupied_sites = np.isin(s_labels, hits)*(s_labels + 1) - 1
r = namedtuple('cluster_labels', ('site_labels', 'bond_labels'))
return r(occupied_sites, occupied_bonds)
|
Computes actual node and edge occupancy based on connectivity to the given
inlets
Parameters
----------
b_labels : ndarray
An array of cluster labels assigned to each bond. -1 indicates
unoccupied
s_labels : ndarray
An array of cluster labels assigned to each site. -1 indicates
unoccupied. Site cluster numbers must correspond to the bond
clusters, such that if bond j has a cluster number N, then both
sites on each end of j are also labeled N.
inlets : ndarray
An array containing node indices that are to be treated as inlets.
Any clusters labels not found in these nodes will be considered
disconnected and set to -1.
Returns
-------
occupancy : tuple of ndarrays
The returned tuple containing arrays of cluster numbers of
``occupied_sites`` and ``occupied_bonds``, after accounting for
connection to the ``inlets``.
Notes
-----
The ``b_labels`` and ``s_labels`` arrays are returned from the
``bond_percolation`` or ``site_percolation`` function.
|
trim_disconnected_clusters
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/simulations/_percolation.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/simulations/_percolation.py
|
MIT
|
def remove_isolated_clusters(labels, inlets):
r"""
Finds cluster labels not attached to the inlets, and sets them to
unoccupied (-1)
Parameters
----------
labels : tuple of node and edge labels
This information is provided by the ``site_percolation`` or
``bond_percolation`` functions
inlets : array_like
A list of which nodes are inlets. Can be a boolean mask or an
array of indices.
Returns
-------
A tuple containing a list of node and edge labels, with all clusters
not connected to the inlets set to not occupied (-1).
"""
# Identify clusters of invasion sites
inv_clusters = np.unique(labels.site_labels[inlets])
# Remove cluster numbers == -1, if any
inv_clusters = inv_clusters[inv_clusters >= 0]
# Find all pores in invading clusters
p_invading = np.in1d(labels.site_labels, inv_clusters)
labels.site_labels[~p_invading] = -1
t_invading = np.in1d(labels.bond_labels, inv_clusters)
labels.bond_labels[~t_invading] = -1
return labels
|
Finds cluster labels not attached to the inlets, and sets them to
unoccupied (-1)
Parameters
----------
labels : tuple of node and edge labels
This information is provided by the ``site_percolation`` or
``bond_percolation`` functions
inlets : array_like
A list of which nodes are inlets. Can be a boolean mask or an
array of indices.
Returns
-------
A tuple containing a list of node and edge labels, with all clusters
not connected to the inlets set to not occupied (-1).
|
remove_isolated_clusters
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/simulations/_percolation.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/simulations/_percolation.py
|
MIT
|
def ispercolating(conns, occupied, inlets, outlets):
r"""
Determines if a percolating cluster exists in the network spanning
the given inlet and outlet nodes
Parameters
----------
conns : array_like
An N x 2 array connections. If two connected sites are both occupied
they are part of the same cluster, as is the bond connecting them.
occupied : array_like
A boolean array with ``True`` values indicating if a bond or site
is occupied. If the length of this array is equal to the number
of bonds (i.e. ``conns.shape[0]``) then bond percolation is assumed,
otherwise site percolation is assumed.
inlets : array_like
An array of indices indicating which nodes are part of the inlets
outlets : array_like
An array of indices indicating which nodes are part of the outlets
"""
if occupied.size == conns.shape[0]:
mode = 'bond'
else:
mode = 'site'
if mode.startswith('site'):
clusters = site_percolation(conns, occupied)
elif mode.startswith('bond'):
clusters = bond_percolation(conns, occupied)
ins = np.unique(clusters.site_labels[inlets])
if ins[0] == -1:
ins = ins[1:]
outs = np.unique(clusters.site_labels[outlets])
if outs[0] == -1:
outs = outs[1:]
hits = np.in1d(ins, outs)
return np.any(hits)
|
Determines if a percolating cluster exists in the network spanning
the given inlet and outlet nodes
Parameters
----------
conns : array_like
An N x 2 array connections. If two connected sites are both occupied
they are part of the same cluster, as is the bond connecting them.
occupied : array_like
A boolean array with ``True`` values indicating if a bond or site
is occupied. If the length of this array is equal to the number
of bonds (i.e. ``conns.shape[0]``) then bond percolation is assumed,
otherwise site percolation is assumed.
inlets : array_like
An array of indices indicating which nodes are part of the inlets
outlets : array_like
An array of indices indicating which nodes are part of the outlets
|
ispercolating
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/simulations/_percolation.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/simulations/_percolation.py
|
MIT
|
def rotate_coords(coords, a=0, b=0, c=0, R=None):
r"""
Rotates coordinates a given amount about each axis
Parameters
----------
coords : ndarray
The site coordinates to be transformed. ``coords`` must be in 3D,
but a 2D network can be represented by putting 0's in the missing
dimension.
a, b, c : scalar, optional
The amount in degrees to rotate about the x, y, and z-axis,
respectively.
R : array_like, optional
Rotation matrix. Must be a 3-by-3 matrix since coordinates are
always in 3D. If this is given then `a`, `b`, and `c` are ignored.
Returns
-------
coords : ndarray
A copy of the given ``coords`` is made and returned to the rotation
does not occur *in place*.
See Also
--------
shear_coords
"""
coords = np.copy(coords)
if R is None:
if a:
R = np.array([[1, 0, 0],
[0, np.cos(np.deg2rad(a)), -np.sin(np.deg2rad(a))],
[0, np.sin(np.deg2rad(a)), np.cos(np.deg2rad(a))]])
coords = np.tensordot(coords, R, axes=(1, 1))
if b:
R = np.array([[np.cos(np.deg2rad(b)), 0, -np.sin(np.deg2rad(b))],
[0, 1, 0],
[np.sin(np.deg2rad(b)), 0, np.cos(np.deg2rad(b))]])
coords = np.tensordot(coords, R, axes=(1, 1))
if c:
R = np.array([[np.cos(np.deg2rad(c)), -np.sin(np.deg2rad(c)), 0],
[np.sin(np.deg2rad(c)), np.cos(np.deg2rad(c)), 0],
[0, 0, 1]])
coords = np.tensordot(coords, R, axes=(1, 1))
else:
coords = np.tensordot(coords, R, axes=(1, 1))
return coords
|
Rotates coordinates a given amount about each axis
Parameters
----------
coords : ndarray
The site coordinates to be transformed. ``coords`` must be in 3D,
but a 2D network can be represented by putting 0's in the missing
dimension.
a, b, c : scalar, optional
The amount in degrees to rotate about the x, y, and z-axis,
respectively.
R : array_like, optional
Rotation matrix. Must be a 3-by-3 matrix since coordinates are
always in 3D. If this is given then `a`, `b`, and `c` are ignored.
Returns
-------
coords : ndarray
A copy of the given ``coords`` is made and returned to the rotation
does not occur *in place*.
See Also
--------
shear_coords
|
rotate_coords
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def shear_coords(coords, ay=0, az=0, bx=0, bz=0, cx=0, cy=0, S=None):
r"""
Shears the coordinates a given amount about along axis
Parameters
----------
coords : ndarray
The coordinates to be transformed
ay : scalar
The factor by which to shear along the x-axis as a function of y
az : scalar
The factor by which to shear along the x-axis as a function of z
bx : scalar
The factor by which to shear along the y-axis as a function of x
bz : scalar
The factor by which to shear along the y-axis as a function of z
cx : scalar
The factor by which to shear along the z-axis as a function of x
cy : scalar
The factor by which to shear along the z-axis as a function of y
S : array_like
The shear matrix. Must be a 3-by-3 matrix since pore coordinates are
always in 3D. If this is given then the other individual arguments
are ignored.
Returns
-------
coords : ndarray
The sheared coordinates. A copy of the supplied coordinates is made
so that the operation is not performed *in place*.
See Also
--------
rotate_coords
Notes
-----
The shear along the i *th*-axis is given as i\* = i + aj. This means
the new i coordinate is the old one plus some linear factor *a* in the
j *th* direction.
The values of ``a``, ``b``, and ``c`` are essentially the inverse of the
slope to be formed by the neighboring layers of sheared pores. A value of
0 means no shear, and neighboring points are stacked directly on top of
each other; a value of 1 means they form a 45 degree diagonal, and so on.
If ``S`` is given, then is should be of the form:
::
S = [[1 , ay, az],
[bx, 1 , bz],
[cx, cy, 1 ]]
where any of the off-diagonal components can be 0 meaning no shear
"""
coords = np.copy(coords)
if S is None:
S = np.array([[1, ay, az],
[bx, 1, bz],
[cx, cy, 1]])
coords = ([email protected]).T
return coords
|
Shears the coordinates a given amount about along axis
Parameters
----------
coords : ndarray
The coordinates to be transformed
ay : scalar
The factor by which to shear along the x-axis as a function of y
az : scalar
The factor by which to shear along the x-axis as a function of z
bx : scalar
The factor by which to shear along the y-axis as a function of x
bz : scalar
The factor by which to shear along the y-axis as a function of z
cx : scalar
The factor by which to shear along the z-axis as a function of x
cy : scalar
The factor by which to shear along the z-axis as a function of y
S : array_like
The shear matrix. Must be a 3-by-3 matrix since pore coordinates are
always in 3D. If this is given then the other individual arguments
are ignored.
Returns
-------
coords : ndarray
The sheared coordinates. A copy of the supplied coordinates is made
so that the operation is not performed *in place*.
See Also
--------
rotate_coords
Notes
-----
The shear along the i *th*-axis is given as i\* = i + aj. This means
the new i coordinate is the old one plus some linear factor *a* in the
j *th* direction.
The values of ``a``, ``b``, and ``c`` are essentially the inverse of the
slope to be formed by the neighboring layers of sheared pores. A value of
0 means no shear, and neighboring points are stacked directly on top of
each other; a value of 1 means they form a 45 degree diagonal, and so on.
If ``S`` is given, then is should be of the form:
::
S = [[1 , ay, az],
[bx, 1 , bz],
[cx, cy, 1 ]]
where any of the off-diagonal components can be 0 meaning no shear
|
shear_coords
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def generate_points_on_sphere(n=100, r=1):
r"""
Generates approximately equispaced points on the surface of a sphere
Parameters
----------
n : int or [int, int]
If a single ``int`` is provided then this number of points will be
generated using the Fibonacci method to make them approximately
equally spaced. If a list of 2 ``int``s is given, they are interpreted
as the number of meridians and parallels to divide the sphere with.
r : scalar
The radius of the sphere on which the points should lie
Returns
-------
coords : ndarray
An array of x, y, z coordinates for the sphere which will be centered
on [0, 0, 0]
"""
if isinstance(n, int):
i = np.arange(n)
phi = np.pi * (3 - np.sqrt(5)) # golden angle in radians
y = 1 - (i / float(n - 1))*2 # y goes from 1 to -1
radius = np.sqrt(1 - y*y) # radius at y
theta = phi * i # golden angle increment
x = np.cos(theta) * radius
z = np.sin(theta) * radius
# Convert to spherical coords
r_, q, p = cart2sph(x, y, z)
# Scale the radius then convert back to cartesian
X, Y, Z = sph2cart(r=r*r_, theta=q, phi=p)
coords = np.vstack((X, Y, Z)).T
else:
nlat = n[0]
nlon = n[1]
lat = []
lon = []
for i in range(0, 360, max(1, int(360/nlon))):
for j in range(max(1, int(180/nlat)), 180, max(1, int(180/nlat))):
lon.append(i)
lat.append(j)
lat.extend([0, 180])
lon.extend([0, 0])
theta = np.deg2rad(lon) - np.pi
phi = np.deg2rad(lat) - np.pi/2
X, Y, Z = sph2cart(phi=phi, theta=theta, r=r)
coords = np.vstack((X, Y, Z)).T
return coords
|
Generates approximately equispaced points on the surface of a sphere
Parameters
----------
n : int or [int, int]
If a single ``int`` is provided then this number of points will be
generated using the Fibonacci method to make them approximately
equally spaced. If a list of 2 ``int``s is given, they are interpreted
as the number of meridians and parallels to divide the sphere with.
r : scalar
The radius of the sphere on which the points should lie
Returns
-------
coords : ndarray
An array of x, y, z coordinates for the sphere which will be centered
on [0, 0, 0]
|
generate_points_on_sphere
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def generate_points_in_disk(n=100, r=1):
r"""
Generates approximately equally spaced points inside a disk
Parameters
----------
n : int
The number of points to generate
r : scalar
The radius of the disk
Returns
-------
coords : ndarray
An ``n by 2`` array of x, y points (in cartesian coordinates)
"""
indices = np.arange(0, n, dtype=float) + 0.5
r = np.sqrt(indices/n)
theta = np.pi*(1 + 5**0.5)*indices
x = r*np.cos(theta)
y = r*np.sin(theta)
return np.vstack((x, y)).T
|
Generates approximately equally spaced points inside a disk
Parameters
----------
n : int
The number of points to generate
r : scalar
The radius of the disk
Returns
-------
coords : ndarray
An ``n by 2`` array of x, y points (in cartesian coordinates)
|
generate_points_in_disk
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def generate_points_on_circle(n=100, r=1):
r"""
Generates equally spaced points on a circle
Parameters
----------
n : int
The number of points to generate
r : scalar
The radius of the disk
Returns
-------
coords : ndarray
An ``n by 2`` array of x, y points (in cartesian coordinates)
"""
theta = np.linspace(0, 2*np.pi, n, endpoint=False)
r = np.ones_like(theta)*r
z = np.zeros_like(theta)
x, y, z = cyl2cart(r=r, theta=theta, z=z)
return np.vstack((x, y)).T
|
Generates equally spaced points on a circle
Parameters
----------
n : int
The number of points to generate
r : scalar
The radius of the disk
Returns
-------
coords : ndarray
An ``n by 2`` array of x, y points (in cartesian coordinates)
|
generate_points_on_circle
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def cart2sph(x, y, z):
r"""
Converts cartesian to spherical coordinates
Parameters
----------
x, y, z : array_like
Arrays containing the x, y and z coordinates to be converted
Returns
-------
r, theta, phi : ndarrays
Three arrays containing the spherical coordinate of each given point
Notes
-----
Surprizingly (and annoyingly) this is not built into numpy, for reasons
discussed `here <https://github.com/numpy/numpy/issues/5228>`_.
"""
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
phi = np.arctan2(z, hxy)
theta = np.arctan2(y, x)
return r, theta, phi
|
Converts cartesian to spherical coordinates
Parameters
----------
x, y, z : array_like
Arrays containing the x, y and z coordinates to be converted
Returns
-------
r, theta, phi : ndarrays
Three arrays containing the spherical coordinate of each given point
Notes
-----
Surprizingly (and annoyingly) this is not built into numpy, for reasons
discussed `here <https://github.com/numpy/numpy/issues/5228>`_.
|
cart2sph
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def sph2cart(r, theta, phi):
r"""
Converts spherical to cartesian coordinates
Parameters
----------
r, theta, phi : array_like
Arrays containing the r, theta and phi coordinates to be transformed
Returns
-------
x, y, z : ndarrays
Three arrays containing the cartesian coordinates of the given points
Notes
-----
Surprizingly (and annoyingly) this is not built into numpy, for reasons
discussed `here <https://github.com/numpy/numpy/issues/5228>`_.
"""
rcos_theta = r * np.cos(phi)
x = rcos_theta * np.cos(theta)
y = rcos_theta * np.sin(theta)
z = r * np.sin(phi)
return x, y, z
|
Converts spherical to cartesian coordinates
Parameters
----------
r, theta, phi : array_like
Arrays containing the r, theta and phi coordinates to be transformed
Returns
-------
x, y, z : ndarrays
Three arrays containing the cartesian coordinates of the given points
Notes
-----
Surprizingly (and annoyingly) this is not built into numpy, for reasons
discussed `here <https://github.com/numpy/numpy/issues/5228>`_.
|
sph2cart
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_coords_transforms.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_coords_transforms.py
|
MIT
|
def get_edge_prefix(network):
r"""
Determines the prefix used for edge arrays from ``<edge_prefix>.conns``
Parameters
----------
network : dict
The network dictionary
Returns
-------
edge_prefix : str
The value of ``<edge_prefix>`` used in ``g``. This is found by
scanning ``g.keys()`` until an array ending in ``'.conns'`` is found,
then returning the prefix.
Notes
-----
This process is surprizingly fast, on the order of nano seconds, so this
overhead is worth it for the flexibility it provides in array naming.
However, since all ``dict`` are now sorted in Python, it may be helpful
to ensure the ``'conns'`` array is near the beginning of the list.
"""
for item in network.keys():
if item.endswith('.conns'):
return item.split('.')[0]
|
Determines the prefix used for edge arrays from ``<edge_prefix>.conns``
Parameters
----------
network : dict
The network dictionary
Returns
-------
edge_prefix : str
The value of ``<edge_prefix>`` used in ``g``. This is found by
scanning ``g.keys()`` until an array ending in ``'.conns'`` is found,
then returning the prefix.
Notes
-----
This process is surprizingly fast, on the order of nano seconds, so this
overhead is worth it for the flexibility it provides in array naming.
However, since all ``dict`` are now sorted in Python, it may be helpful
to ensure the ``'conns'`` array is near the beginning of the list.
|
get_edge_prefix
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def get_node_prefix(network):
r"""
Determines the prefix used for node arrays from ``<edge_prefix>.coords``
Parameters
----------
network : dict
The network dictionary
Returns
-------
node_prefix : str
The value of ``<node_prefix>`` used in ``g``. This is found by
scanning ``g.keys()`` until an array ending in ``'.coords'`` is found,
then returning the prefix.
Notes
-----
This process is surprizingly fast, on the order of nano seconds, so this
overhead is worth it for the flexibility it provides in array naming.
However, since all ``dict`` are now sorted in Python, it may be helpful
to ensure the ``'conns'`` array is near the beginning of the list.
"""
for item in network.keys():
if item.endswith('.coords'):
return item.split('.')[0]
|
Determines the prefix used for node arrays from ``<edge_prefix>.coords``
Parameters
----------
network : dict
The network dictionary
Returns
-------
node_prefix : str
The value of ``<node_prefix>`` used in ``g``. This is found by
scanning ``g.keys()`` until an array ending in ``'.coords'`` is found,
then returning the prefix.
Notes
-----
This process is surprizingly fast, on the order of nano seconds, so this
overhead is worth it for the flexibility it provides in array naming.
However, since all ``dict`` are now sorted in Python, it may be helpful
to ensure the ``'conns'`` array is near the beginning of the list.
|
get_node_prefix
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def change_prefix(network, old_prefix, new_prefix):
r"""
Changes the prefix used when generating the graph
Parameters
----------
network : dict
The network graph
old_prefix : str
The current prefix to change, can either be a node or an edge prefix
new_prefix : str
The prefix to use instead
Returns
-------
network : dict
The graph dictionary will arrays assigned to new keys
"""
for key in list(network.keys()):
if key.startswith(old_prefix):
temp = key.split('.', 1)[1]
network[new_prefix + '.' + temp] = network.pop(key)
return network
|
Changes the prefix used when generating the graph
Parameters
----------
network : dict
The network graph
old_prefix : str
The current prefix to change, can either be a node or an edge prefix
new_prefix : str
The prefix to use instead
Returns
-------
network : dict
The graph dictionary will arrays assigned to new keys
|
change_prefix
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def isoutside(network, shape, rtol=0.0):
r"""
Identifies sites that lie outside the specified shape
Parameters
----------
network : dict
The network dictionary. For convenience it is also permissible to just
supply an N-by-D array of coordinates.
shape : array_like
The shape of the domain beyond which points are considered "outside".
The argument is treated as follows:
========== ============================================================
shape Interpretation
========== ============================================================
[x, y, z] A 3D cubic domain of dimension x, y and z with the origin at
[0, 0, 0].
[x, y, 0] A 2D square domain of size x by y with the origin at
[0, 0]
[r, z] A 3D cylindrical domain of radius r and height z whose
central axis starts at [0, 0, 0]
[r, 0] A 2D circular domain of radius r centered on [0, 0] and
extending upwards
[r] A 3D spherical domain of radius r centered on [0, 0, 0]
========== ============================================================
rtol : scalar or array_like, optional
Controls how far a node must be from the domain boundary to be
considered outside. It is applied as a fraction of the domain size as
``x[i] > (shape[0] + shape[0]*threshold)`` or
``y[i] < (0 - shape[1]*threshold)``. Discrete threshold values
can be given for each axis by supplying a list the same size as
``shape``.
Returns
-------
mask : boolean ndarray
A boolean array with ``True`` values indicating nodes that lie outside
the domain.
Notes
-----
If the domain is 2D, either a circle or a square, then the z-dimension
of ``shape`` should be set to 0.
"""
try:
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
except AttributeError:
coords = network
shape = np.array(shape, dtype=float)
if np.isscalar(rtol):
tolerance = np.array([rtol]*len(shape))
else:
tolerance = np.array(rtol)
# Label external pores for trimming below
if len(shape) == 1: # Spherical
# Find external points
R, Q, P = cart2sph(*coords.T)
thresh = tolerance[0]*shape[0]
Ps = R > (shape[0] + thresh)
elif len(shape) == 2: # Cylindrical
# Find external pores outside radius
R, Q, Z = cart2cyl(*coords.T)
thresh = tolerance[0]*shape[0]
Ps = R > shape[0]*(1 + thresh)
# Find external pores above and below cylinder
if shape[1] > 0:
thresh = tolerance[1]*shape[1]
Ps = Ps + (coords[:, 2] > (shape[1] + thresh))
Ps = Ps + (coords[:, 2] < (0 - thresh))
else:
pass
elif len(shape) == 3: # Rectilinear
thresh = tolerance*shape
Ps1 = np.any(coords > (shape + thresh), axis=1)
Ps2 = np.any(coords < (0 - thresh), axis=1)
Ps = Ps1 + Ps2
return Ps
|
Identifies sites that lie outside the specified shape
Parameters
----------
network : dict
The network dictionary. For convenience it is also permissible to just
supply an N-by-D array of coordinates.
shape : array_like
The shape of the domain beyond which points are considered "outside".
The argument is treated as follows:
========== ============================================================
shape Interpretation
========== ============================================================
[x, y, z] A 3D cubic domain of dimension x, y and z with the origin at
[0, 0, 0].
[x, y, 0] A 2D square domain of size x by y with the origin at
[0, 0]
[r, z] A 3D cylindrical domain of radius r and height z whose
central axis starts at [0, 0, 0]
[r, 0] A 2D circular domain of radius r centered on [0, 0] and
extending upwards
[r] A 3D spherical domain of radius r centered on [0, 0, 0]
========== ============================================================
rtol : scalar or array_like, optional
Controls how far a node must be from the domain boundary to be
considered outside. It is applied as a fraction of the domain size as
``x[i] > (shape[0] + shape[0]*threshold)`` or
``y[i] < (0 - shape[1]*threshold)``. Discrete threshold values
can be given for each axis by supplying a list the same size as
``shape``.
Returns
-------
mask : boolean ndarray
A boolean array with ``True`` values indicating nodes that lie outside
the domain.
Notes
-----
If the domain is 2D, either a circle or a square, then the z-dimension
of ``shape`` should be set to 0.
|
isoutside
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def dimensionality(network, cache=True):
r"""
Checks the dimensionality of the network
Parameters
----------
network : dict
The network dictionary
cache : boolean, optional (default is True)
If ``False`` then the dimensionality is recalculated even if it has
already been calculated and stored in the graph dictionary.
Returns
-------
dims : list
A 3-by-1 array containing ``True`` for each axis that contains
multiple values, indicating that the pores are spatially distributed
in that dimension.
"""
if cache:
try:
return network.params["dimensionality"]
# union of KeyErroa and AttributeError
except (KeyError, AttributeError):
pass
n = get_node_prefix(network)
coords = network[n+'.coords']
eps = np.finfo(float).resolution
dims_unique = \
[not np.allclose(xk, xk.mean(), atol=0, rtol=eps) for xk in coords.T]
if cache:
network["params.dimensionality"] = np.array(dims_unique)
return np.array(dims_unique)
|
Checks the dimensionality of the network
Parameters
----------
network : dict
The network dictionary
cache : boolean, optional (default is True)
If ``False`` then the dimensionality is recalculated even if it has
already been calculated and stored in the graph dictionary.
Returns
-------
dims : list
A 3-by-1 array containing ``True`` for each axis that contains
multiple values, indicating that the pores are spatially distributed
in that dimension.
|
dimensionality
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def find_surface_nodes_cubic(network):
r"""
Identifies nodes on the outer surface of the domain assuming a cubic domain
to save time
Parameters
----------
network : dict
The graph dictionary
Returns
-------
mask : ndarray
A boolean array of ``True`` values indicating which nodes were found
on the surfaces.
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
hits = np.zeros(coords.shape[0], dtype=bool)
dims = dimensionality(network)
for d in range(3):
if dims[d]:
hi = np.where(coords[:, d] == coords[:, d].max())[0]
lo = np.where(coords[:, d] == coords[:, d].min())[0]
hits[hi] = True
hits[lo] = True
return hits
|
Identifies nodes on the outer surface of the domain assuming a cubic domain
to save time
Parameters
----------
network : dict
The graph dictionary
Returns
-------
mask : ndarray
A boolean array of ``True`` values indicating which nodes were found
on the surfaces.
|
find_surface_nodes_cubic
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def find_coincident_nodes(network):
r"""
Finds nodes with identical coordinates
Parameters
----------
network : dict
The network dictionary
Returns
-------
duplicates : list of ndarrays
A list with each sublist indicating the indices of nodes that share
a common set of coordinates
Notes
-----
This function works by computing a ``hash`` of the coordinates then finding
all nodes with equivalent hash values. Hashes are supposed to be unique
but they occassionally "collide", meaning nodes may be identified as
coincident that are not.
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
hashed = [hash(row.tobytes()) for row in coords]
uniq, counts = np.unique(hashed, return_counts=True)
hits = np.where(counts > 1)[0]
dupes = []
for item in hits:
dupes.append(np.where(hashed == uniq[item])[0])
return dupes
|
Finds nodes with identical coordinates
Parameters
----------
network : dict
The network dictionary
Returns
-------
duplicates : list of ndarrays
A list with each sublist indicating the indices of nodes that share
a common set of coordinates
Notes
-----
This function works by computing a ``hash`` of the coordinates then finding
all nodes with equivalent hash values. Hashes are supposed to be unique
but they occassionally "collide", meaning nodes may be identified as
coincident that are not.
|
find_coincident_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def find_surface_nodes(network):
r"""
Identifies nodes on the outer surface of the domain using a Delaunay
tessellation
Parameters
----------
network : dict
The network dictionary
Returns
-------
mask : ndarray
A boolean array of ``True`` values indicating which nodes were found
on the surfaces.
Notes
-----
This function generates points around the domain the performs a Delaunay
tesselation between these points and the network nodes. Any network
nodes which are connected to a generated points is considered a surface
node.
"""
node_prefix = get_node_prefix(network)
coords = np.copy(network[node_prefix+'.coords'])
shift = np.mean(coords, axis=0)
coords = coords - shift
tmp = cart2sph(*coords.T)
hits = np.zeros(coords.shape[0], dtype=bool)
r = 2*tmp[0].max()
dims = dimensionality(network)
if sum(dims) == 1:
hi = np.where(coords[:, dims] == coords[:, dims].max())[0]
lo = np.where(coords[:, dims] == coords[:, dims].min())[0]
hits[hi] = True
hits[lo] = True
return hits
if sum(dims) == 2:
markers = generate_points_on_circle(n=max(10, int(coords.shape[0]/10)), r=r)
pts = np.vstack((coords[:, dims], markers))
else:
markers = generate_points_on_sphere(n=max(10, int(coords.shape[0]/10)), r=r)
pts = np.vstack((coords, markers))
tri = Delaunay(pts, incremental=False)
(indices, indptr) = tri.vertex_neighbor_vertices
for k in range(coords.shape[0], tri.npoints):
neighbors = indptr[indices[k]:indices[k+1]]
inds = np.where(neighbors < coords.shape[0])
hits[neighbors[inds]] = True
return hits
|
Identifies nodes on the outer surface of the domain using a Delaunay
tessellation
Parameters
----------
network : dict
The network dictionary
Returns
-------
mask : ndarray
A boolean array of ``True`` values indicating which nodes were found
on the surfaces.
Notes
-----
This function generates points around the domain the performs a Delaunay
tesselation between these points and the network nodes. Any network
nodes which are connected to a generated points is considered a surface
node.
|
find_surface_nodes
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def internode_distance(network, inds_1=None, inds_2=None):
r"""
Find the distance between all nodes on set 1 to each node in set 2
Parameters
----------
network : dict
The network dictionary
inds_1 : array_like
A list containing the indices of the first set of nodes
inds_2 : array_Like
A list containing the indices of the first set of nodes. It's OK if
these indices are partially or completely duplicating ``nodes1``.
Returns
-------
dist : array_like
A distance matrix with ``len(site1)`` rows and ``len(sites2)`` columns.
The distance between site *i* in ``site1`` and *j* in ``sites2`` is
located at *(i, j)* and *(j, i)* in the distance matrix.
Notes
-----
This function computes and returns a distance matrix, so can get large.
For distances between larger sets a KD-tree approach would be better,
which is available in ``scipy.spatial``.
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
p1 = np.array(inds_1, ndmin=1)
p2 = np.array(inds_2, ndmin=1)
return distance_matrix(coords[p1], coords[p2])
|
Find the distance between all nodes on set 1 to each node in set 2
Parameters
----------
network : dict
The network dictionary
inds_1 : array_like
A list containing the indices of the first set of nodes
inds_2 : array_Like
A list containing the indices of the first set of nodes. It's OK if
these indices are partially or completely duplicating ``nodes1``.
Returns
-------
dist : array_like
A distance matrix with ``len(site1)`` rows and ``len(sites2)`` columns.
The distance between site *i* in ``site1`` and *j* in ``sites2`` is
located at *(i, j)* and *(j, i)* in the distance matrix.
Notes
-----
This function computes and returns a distance matrix, so can get large.
For distances between larger sets a KD-tree approach would be better,
which is available in ``scipy.spatial``.
|
internode_distance
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def iscoplanar(network):
r"""
Determines if specified nodes are coplanar with each other
Parameters
----------
network : dict
The graph dictionary
Returns
-------
flag : bool
A boolean value of whether given nodes are coplanar (``True``) or
not (``False``)
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix + '.coords']
if np.shape(coords)[0] < 3:
raise Exception('At least 3 input pores are required')
Px = coords[:, 0]
Py = coords[:, 1]
Pz = coords[:, 2]
# Do easy check first, for common coordinate
if np.shape(np.unique(Px))[0] == 1:
return True
if np.shape(np.unique(Py))[0] == 1:
return True
if np.shape(np.unique(Pz))[0] == 1:
return True
# Perform rigorous check using vector algebra
# Grab first basis vector from list of coords
n1 = np.array((Px[1] - Px[0], Py[1] - Py[0], Pz[1] - Pz[0])).T
n = np.array([0.0, 0.0, 0.0])
i = 1
while n.sum() == 0:
if i >= (np.size(Px) - 1):
return False
# Chose a secon basis vector
n2 = np.array((Px[i+1] - Px[i], Py[i+1] - Py[i], Pz[i+1] - Pz[i])).T
# Find their cross product
n = np.cross(n1, n2)
i += 1
# Create vectors between all other pairs of points
r = np.array((Px[1:-1] - Px[0], Py[1:-1] - Py[0], Pz[1:-1] - Pz[0]))
# Ensure they all lie on the same plane
n_dot = np.dot(n, r)
return bool(np.sum(np.absolute(n_dot)) == 0)
|
Determines if specified nodes are coplanar with each other
Parameters
----------
network : dict
The graph dictionary
Returns
-------
flag : bool
A boolean value of whether given nodes are coplanar (``True``) or
not (``False``)
|
iscoplanar
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def is_fully_connected(network, inds=None):
r"""
Checks whether graph is fully connected, i.e. not clustered
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
The indices of boundary nodes (i.e. inlets/outlets). If this is given
the multiple sample spanning clusters will count as fully connected.
Returns
-------
flag : bool
If ``inds`` is not specified, then returns ``True`` only if
the entire network is connected to the same cluster. If
``inds`` is given, then returns ``True`` only if all clusters
are connected to the given boundary nodes.
"""
am = dict_to_am(network)
am = am.tolil()
inds = np.array(inds)
temp = csgraph.connected_components(am, directed=False)[1]
is_connected = np.unique(temp).size == 1
Np = am.shape[0]
Nt = int(am.nnz/2)
# Ensure all clusters are part of inds, if given
if not is_connected and inds is not None:
am.resize(Np + 1, Np + 1)
am.rows[-1] = inds.tolist()
am.data[-1] = np.arange(Nt, Nt + len(inds)).tolist()
temp = csgraph.connected_components(am, directed=False)[1]
is_connected = np.unique(temp).size == 1
return is_connected
|
Checks whether graph is fully connected, i.e. not clustered
Parameters
----------
network : dict
The network dictionary
inds : array_like (optional)
The indices of boundary nodes (i.e. inlets/outlets). If this is given
the multiple sample spanning clusters will count as fully connected.
Returns
-------
flag : bool
If ``inds`` is not specified, then returns ``True`` only if
the entire network is connected to the same cluster. If
``inds`` is given, then returns ``True`` only if all clusters
are connected to the given boundary nodes.
|
is_fully_connected
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def get_cubic_spacing(network):
r"""
Determine spacing of a cubic network
Parameters
----------
network : dict
The network dictionary
Returns
-------
spacing : ndarray
An array containing the spacing between nodes in each direction
"""
node_prefix = get_node_prefix(network)
edge_prefix = get_edge_prefix(network)
coords = network[node_prefix+'.coords']
conns = network[edge_prefix+'.conns']
# Find Network spacing
C12 = coords[conns]
mag = np.linalg.norm(np.diff(C12, axis=1), axis=2)
unit_vec = np.around(np.squeeze(np.diff(C12, axis=1)) / mag, decimals=14)
spacing = [0, 0, 0]
dims = dimensionality(network)
# Ensure vectors point in n-dims unique directions
c = {tuple(row): 1 for row in unit_vec}
mag = np.atleast_1d(mag.squeeze()).astype(float)
if len(c.keys()) > sum(dims):
raise Exception(
"Spacing is undefined when throats point in more directions"
" than network has dimensions."
)
for ax in [0, 1, 2]:
if dims[ax]:
inds = np.where(unit_vec[:, ax] == unit_vec[:, ax].max())[0]
temp = np.unique(mag[inds])
if not np.allclose(temp, temp[0]):
raise Exception("A unique value of spacing could not be found.")
spacing[ax] = temp[0]
return np.array(spacing)
|
Determine spacing of a cubic network
Parameters
----------
network : dict
The network dictionary
Returns
-------
spacing : ndarray
An array containing the spacing between nodes in each direction
|
get_cubic_spacing
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def get_cubic_shape(network):
r"""
Determine shape of a cubic network
Parameters
----------
network : dict
The network dictionary
Returns
-------
shape : ndarray
An array containing the shape of the network each direction
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
L = np.ptp(coords, axis=0)
mask = L.astype(bool)
S = get_cubic_spacing(network)
shape = np.array([1, 1, 1], int)
shape[mask] = L[mask] / S[mask] + 1
return shape
|
Determine shape of a cubic network
Parameters
----------
network : dict
The network dictionary
Returns
-------
shape : ndarray
An array containing the shape of the network each direction
|
get_cubic_shape
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def get_domain_area(network, inlets=None, outlets=None):
r"""
Determine the cross sectional area relative to the inlets/outlets.
Parameters
----------
network : dict
The network dictionary
inlets : array_like
The indices of the inlets
outlets : array_Like
The indices of the outlets
Returns
-------
area : scalar
The cross sectional area relative to the inlets/outlets.
"""
if dimensionality(network).sum() != 3:
raise Exception('The network is not 3D, specify area manually')
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
inlets = coords[inlets]
outlets = coords[outlets]
if not iscoplanar(inlets):
print('Detected inlet pores are not coplanar')
if not iscoplanar(outlets):
print('Detected outlet pores are not coplanar')
Nin = np.ptp(inlets, axis=0) > 0
if Nin.all():
print('Detected inlets are not oriented along a principle axis')
Nout = np.ptp(outlets, axis=0) > 0
if Nout.all():
print('Detected outlets are not oriented along a principle axis')
hull_in = ConvexHull(points=inlets[:, Nin])
hull_out = ConvexHull(points=outlets[:, Nout])
if hull_in.volume != hull_out.volume:
print('Inlet and outlet faces are different area')
area = hull_in.volume # In 2D: volume=area, area=perimeter
return area
|
Determine the cross sectional area relative to the inlets/outlets.
Parameters
----------
network : dict
The network dictionary
inlets : array_like
The indices of the inlets
outlets : array_Like
The indices of the outlets
Returns
-------
area : scalar
The cross sectional area relative to the inlets/outlets.
|
get_domain_area
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def get_domain_length(network, inlets=None, outlets=None):
r"""
Determine the domain length relative to the inlets/outlets.
Parameters
----------
network : dict
The network dictionary
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The domain length relative to the inlets/outlets.
"""
node_prefix = get_node_prefix(network)
coords = network[node_prefix+'.coords']
inlets = coords[inlets]
outlets = coords[outlets]
if not iscoplanar(inlets):
print('Detected inlet pores are not coplanar')
if not iscoplanar(outlets):
print('Detected inlet pores are not coplanar')
tree = KDTree(data=inlets)
Ls = np.unique(np.float64(tree.query(x=outlets)[0]))
if not np.allclose(Ls, Ls[0]):
print('A unique value of length could not be found')
length = Ls[0]
return length
|
Determine the domain length relative to the inlets/outlets.
Parameters
----------
network : dict
The network dictionary
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The domain length relative to the inlets/outlets.
|
get_domain_length
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def tri_to_am(tri):
r"""
Given a Delaunay triangulation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation.
Parameters
----------
tri : Delaunay Triangulation Object
This object is produced by ``scipy.spatial.Delaunay``
Returns
-------
A sparse adjacency matrix in COO format. The network is undirected
and unweighted, so the adjacency matrix is upper-triangular and all the
weights are set to 1.
"""
# Create an empty list-of-list matrix
lil = sprs.lil_matrix((tri.npoints, tri.npoints))
# Scan through Delaunay triangulation object to retrieve pairs
indices, indptr = tri.vertex_neighbor_vertices
if 1: # Original way
for k in range(tri.npoints):
lil.rows[k] = indptr[indices[k]:indices[k + 1]].tolist()
# Convert to coo format
lil.data = lil.rows # Just a dummy array to make things work properly
coo = lil.tocoo()
else: # Alternative way, about 10x SLOWER
coo = [[], []]
for k in range(tri.npoints):
# lil.rows[k] = indptr[indices[k]:indices[k + 1]].tolist()
col = indptr[indices[k]:indices[k+1]]
coo[0].extend(np.ones_like(col)*k)
coo[1].extend(col)
coo = sprs.coo_matrix((np.ones_like(coo[0]), (coo[0], coo[1])))
# Set weights to 1's
coo.data = np.ones_like(coo.data)
# Remove diagonal, and convert to csr remove duplicates
am = sprs.triu(A=coo, k=1, format='csr')
# The convert back to COO and return
am = am.tocoo()
return am
|
Given a Delaunay triangulation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation.
Parameters
----------
tri : Delaunay Triangulation Object
This object is produced by ``scipy.spatial.Delaunay``
Returns
-------
A sparse adjacency matrix in COO format. The network is undirected
and unweighted, so the adjacency matrix is upper-triangular and all the
weights are set to 1.
|
tri_to_am
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def vor_to_am(vor):
r"""
Given a Voronoi tessellation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation in COO format.
Parameters
----------
vor : Voronoi Tessellation object
This object is produced by ``scipy.spatial.Voronoi``
Returns
-------
A sparse adjacency matrix in COO format. The network is undirected
and unweighted, so the adjacency matrix is upper-triangular and all the
weights are set to 1.
"""
if 0: # Original way, 2X slower
rc = [[], []]
for ij in vor.ridge_dict.keys():
row = vor.ridge_dict[ij].copy()
# Make sure voronoi cell closes upon itself
row.append(row[0])
# Add connections to rc list
rc[0].extend(row[:-1])
rc[1].extend(row[1:])
rc = np.vstack(rc).T
else:
v = vor.ridge_vertices.copy()
# Add row [0] to close the facet on itself, add -1 to break connection to
# next facet in list as connections with -1 get deleted
_ = [row.extend([row[0], -1]) for row in v]
v = np.hstack(v)
rc = np.vstack((v[:-1], v[1:])).T
mask = np.any(rc < 0, axis=1)
rc = rc[~mask]
rc = np.sort(rc, axis=1)
am = conns_to_am(rc)
return am
|
Given a Voronoi tessellation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation in COO format.
Parameters
----------
vor : Voronoi Tessellation object
This object is produced by ``scipy.spatial.Voronoi``
Returns
-------
A sparse adjacency matrix in COO format. The network is undirected
and unweighted, so the adjacency matrix is upper-triangular and all the
weights are set to 1.
|
vor_to_am
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def dict_to_am(network, weights=None):
r"""
Convert a graph dictionary into a ``scipy.sparse`` adjacency matrix in
COO format
Parameters
----------
network : dict
A network dictionary
weights : ndarray, optional
The weight values to use for the connections. If not provided
then 1's are assumed.
Returns
-------
am : sparse matrix
The sparse adjacency matrix in COO format
Notes
-----
If the edge connections in ``g`` are in upper-triangular form, then the
graph is assumed to be undirected and the returned adjacency matrix is
symmetrical (i.e. the triu entries are reflected in tril). If any edges
are found in the lower triangle, then the returned adjacency matrix is
unsymmetrical.
Multigraphs (i.e. duplicate connections between nodes) are not suported,
but this is not checked for here to avoid overhead since this function is
called frequently.
"""
edge_prefix = get_edge_prefix(network)
node_prefix = get_node_prefix(network)
conns = np.copy(network[edge_prefix+'.conns'])
shape = [network[node_prefix+'.coords'].shape[0]]*2
if weights is None:
weights = np.ones_like(conns[:, 0], dtype=int)
if isgtriu(network): # If graph is triu, then it is assumed to be undirected
conns = np.vstack((conns, np.fliplr(conns))) # Reflect to tril
data = np.ones_like(conns[:, 0], dtype=int) # Generate fake data
am = sprs.coo_matrix((data, (conns[:, 0], conns[:, 1])), shape=shape)
am.data = np.hstack((weights, weights))
else:
am = sprs.coo_matrix((weights, (conns[:, 0], conns[:, 1])), shape=shape)
return am
|
Convert a graph dictionary into a ``scipy.sparse`` adjacency matrix in
COO format
Parameters
----------
network : dict
A network dictionary
weights : ndarray, optional
The weight values to use for the connections. If not provided
then 1's are assumed.
Returns
-------
am : sparse matrix
The sparse adjacency matrix in COO format
Notes
-----
If the edge connections in ``g`` are in upper-triangular form, then the
graph is assumed to be undirected and the returned adjacency matrix is
symmetrical (i.e. the triu entries are reflected in tril). If any edges
are found in the lower triangle, then the returned adjacency matrix is
unsymmetrical.
Multigraphs (i.e. duplicate connections between nodes) are not suported,
but this is not checked for here to avoid overhead since this function is
called frequently.
|
dict_to_am
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def dict_to_im(network):
r"""
Convert a graph dictionary into a ``scipy.sparse`` incidence matrix in COO
format
Parameters
----------
network : dict
The network dictionary
Returns
-------
im : sparse matrix
The sparse incidence matrix in COO format
Notes
-----
Rows correspond to nodes and columns correspond to edges. Each column
has 2 nonzero values indicating which 2 nodes are connected by the
corresponding edge. Each row contains an arbitrary number of nonzeros
whose locations indicate which edges are directly connected to the
corresponding node.
"""
edge_prefix = get_edge_prefix(network)
node_prefix = get_node_prefix(network)
conns = network[edge_prefix+'.conns']
coords = network[node_prefix+'.coords']
if isgtriu(network):
data = np.ones(2*conns.shape[0], dtype=int)
shape = (coords.shape[0], conns.shape[0])
temp = np.arange(conns.shape[0])
cols = np.vstack((temp, temp)).T.flatten()
rows = conns.flatten()
im = sprs.coo_matrix((data, (rows, cols)), shape=shape)
else:
raise Exception('This function is not implemented for directed graphs')
return im
|
Convert a graph dictionary into a ``scipy.sparse`` incidence matrix in COO
format
Parameters
----------
network : dict
The network dictionary
Returns
-------
im : sparse matrix
The sparse incidence matrix in COO format
Notes
-----
Rows correspond to nodes and columns correspond to edges. Each column
has 2 nonzero values indicating which 2 nodes are connected by the
corresponding edge. Each row contains an arbitrary number of nonzeros
whose locations indicate which edges are directly connected to the
corresponding node.
|
dict_to_im
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def ismultigraph(network):
r"""
Checks if graph contains multiple connections between any pair of nodes
Parameters
----------
network : dict
The network dictionary
Returns
-------
flag : bool
Returns ``True`` if any pair of nodes is connected by more than one
edge.
"""
edge_prefix = get_edge_prefix(network)
node_prefix = get_node_prefix(network)
conns = network[edge_prefix+'.conns']
coords = network[node_prefix+'.coords']
data = np.ones_like(conns[:, 0], dtype=int)
shape = 2*[coords.shape[0]]
am = sprs.coo_matrix((data, (conns[:, 0], conns[:, 1])), shape=shape)
am.sum_duplicates()
return np.any(am.data > 1)
|
Checks if graph contains multiple connections between any pair of nodes
Parameters
----------
network : dict
The network dictionary
Returns
-------
flag : bool
Returns ``True`` if any pair of nodes is connected by more than one
edge.
|
ismultigraph
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def isgtriu(network):
r"""
Determines if graph connections are in upper triangular format
Parameters
----------
network : dict
The network dictionary
Returns
-------
flag : bool
Returns ``True`` if *all* rows in "conns" are ordered as [lo, hi]
"""
edge_prefix = get_edge_prefix(network)
conns = network[edge_prefix+'.conns']
return np.all(conns[:, 0] < conns[:, 1])
|
Determines if graph connections are in upper triangular format
Parameters
----------
network : dict
The network dictionary
Returns
-------
flag : bool
Returns ``True`` if *all* rows in "conns" are ordered as [lo, hi]
|
isgtriu
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def to_triu(network):
r"""
Adjusts conns array to force into upper triangular form
Parameters
----------
network : dict
The network dictionary
Returns
-------
network : dict
The graph dictionary with edge connections updated
Notes
-----
This does not check for the creation of duplicate connections
"""
edge_prefix = get_edge_prefix(network)
conns = network[edge_prefix+'.conns']
network[edge_prefix+'.conns'] = np.sort(conns, axis=1)
return network
|
Adjusts conns array to force into upper triangular form
Parameters
----------
network : dict
The network dictionary
Returns
-------
network : dict
The graph dictionary with edge connections updated
Notes
-----
This does not check for the creation of duplicate connections
|
to_triu
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def conns_to_am(conns, shape=None, force_triu=True, drop_diag=True,
drop_dupes=True, drop_negs=True):
r"""
Converts a list of connections into a Scipy sparse adjacency matrix
Parameters
----------
conns : array_like, N x 2
The list of site-to-site connections
shape : list, optional
The shape of the array. If none is given then it is taken as 1 + the
maximum value in ``conns``.
force_triu : bool
If True (default), then all connections are assumed undirected, and
moved to the upper triangular portion of the array
drop_diag : bool
If True (default), then connections from a site and itself are removed.
drop_dupes : bool
If True (default), then all pairs of sites sharing multiple connections
are reduced to a single connection.
drop_negs : bool
If True (default), then all connections with one or both ends pointing
to a negative number are removed.
Returns
-------
am : ndarray
A sparse adjacency matrix in COO format
"""
if drop_negs: # Remove connections to -1
keep = ~np.any(conns < 0, axis=1)
conns = conns[keep]
if drop_diag: # Remove connections of [self, self]
keep = np.where(conns[:, 0] != conns[:, 1])[0]
conns = conns[keep]
if force_triu: # Sort connections to [low, high]
conns = np.sort(conns, axis=1)
# Now convert to actual sparse array in COO format
data = np.ones_like(conns[:, 0], dtype=int)
if shape is None:
N = conns.max() + 1
shape = (N, N)
am = sprs.coo_matrix((data, (conns[:, 0], conns[:, 1])), shape=shape)
if drop_dupes: # Convert to csr and back too coo
am = am.tocsr()
am = am.tocoo()
# Perform one last check on adjacency matrix
missing = np.where(np.bincount(conns.flatten()) == 0)[0]
if np.size(missing) or np.any(am.col.max() < (shape[0] - 1)):
print('Some nodes are not connected to any bonds')
return am
|
Converts a list of connections into a Scipy sparse adjacency matrix
Parameters
----------
conns : array_like, N x 2
The list of site-to-site connections
shape : list, optional
The shape of the array. If none is given then it is taken as 1 + the
maximum value in ``conns``.
force_triu : bool
If True (default), then all connections are assumed undirected, and
moved to the upper triangular portion of the array
drop_diag : bool
If True (default), then connections from a site and itself are removed.
drop_dupes : bool
If True (default), then all pairs of sites sharing multiple connections
are reduced to a single connection.
drop_negs : bool
If True (default), then all connections with one or both ends pointing
to a negative number are removed.
Returns
-------
am : ndarray
A sparse adjacency matrix in COO format
|
conns_to_am
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def istriu(am):
r"""
Returns ``True`` if the sparse adjacency matrix is upper triangular
"""
if am.shape[0] != am.shape[1]:
print('Matrix is not square, triangularity is irrelevant')
return False
if am.format != 'coo':
am = am.tocoo(copy=False)
return np.all(am.row <= am.col)
|
Returns ``True`` if the sparse adjacency matrix is upper triangular
|
istriu
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def istril(am):
r"""
Returns ``True`` if the sparse adjacency matrix is lower triangular
"""
if am.shape[0] != am.shape[1]:
print('Matrix is not square, triangularity is irrelevant')
return False
if am.format != 'coo':
am = am.tocoo(copy=False)
return np.all(am.row >= am.col)
|
Returns ``True`` if the sparse adjacency matrix is lower triangular
|
istril
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def istriangular(am):
r"""
Returns ``True`` if the sparse adjacency matrix is either upper or lower
triangular
"""
if am.format != 'coo':
am = am.tocoo(copy=False)
return istril(am) or istriu(am)
|
Returns ``True`` if the sparse adjacency matrix is either upper or lower
triangular
|
istriangular
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def issymmetric(am):
r"""
A method to check if a square matrix is symmetric
Returns ``True`` if the sparse adjacency matrix is symmetric
"""
if am.shape[0] != am.shape[1]:
print('Matrix is not square, symmetrical is irrelevant')
return False
if am.format != 'coo':
am = am.tocoo(copy=False)
if istril(am) or istriu(am):
return False
# Compare am with its transpose, element wise
sym = ((am != am.T).size) == 0
return sym
|
A method to check if a square matrix is symmetric
Returns ``True`` if the sparse adjacency matrix is symmetric
|
issymmetric
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/tools/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/tools/_funcs.py
|
MIT
|
def plot_edges(network,
edges=None,
ax=None,
size_by=None,
color_by=None,
cmap='jet',
color='b',
alpha=1.0,
linestyle='solid',
linewidth=1,
**kwargs): # pragma: no cover
r"""
Produce a 3D plot of the network topology
This shows how edges connect for quick visualization without having
to export data to veiw in Paraview.
Parameters
----------
network : dict
The network dictionary
edges : array_like (optional)
The list of edges to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no edges are
specified then all are shown.
fig : Matplotlib figure handle and line property arguments (optional)
If a ``fig`` is supplied, then the topology will be overlaid on this
plot. This makes it possible to combine coordinates and connections,
and to color edges differently for instance.
size_by : array_like (optional)
An ndarray of edge values (e.g. alg['throat.rate']). These
values are used to scale the ``linewidth``, so if the lines are too
thin, then increase ``linewidth``.
color_by : str or array_like (optional)
An ndarray of edge values (e.g. alg['edge.rate']).
cmap : str or cmap object (optional)
The matplotlib colormap to use if specfying an edge property
for ``color_by``
color : str, optional (optional)
A matplotlib named color (e.g. 'r' for red).
alpha : float (optional)
The transparency of the lines, with 1 being solid and 0 being invisible
linestyle : str (optional)
Can be one of {'solid', 'dashed', 'dashdot', 'dotted'}. Default is
'solid'.
linewidth : float (optional)
Controls the thickness of drawn lines. Is used to scale the thickness
if ``size_by`` is given. Default is 1. If a value is provided for
``size_by`` then they are used to scale the ``linewidth``.
**kwargs : dict
All other keyword arguments are passed on to the ``Line3DCollection``
class of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
lc : LineCollection or Line3DCollection
Matplotlib object containing the lines representing the throats.
Notes
-----
To create a single plot containing both coordinates and connections,
consider creating an empty figure and then passing the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_coordinates
"""
node_prefix = get_node_prefix(network)
edge_prefix = get_edge_prefix(network)
conns = network[edge_prefix+'.conns']
coords = network[node_prefix+'.coords']
Ts = np.arange(conns.shape[0]) if edges is None else edges
dim = dimensionality(network)
ThreeD = True if dim.sum() == 3 else False
# Add a dummy axis for 1D networks
if dim.sum() == 1:
dim[np.argwhere(~dim)[0]] = True
if "fig" in kwargs.keys():
raise Exception("'fig' argument is deprecated, use 'ax' instead.")
if ax is None:
fig, ax = plt.subplots()
else:
# The next line is necessary if ax was created using plt.subplots()
fig, ax = ax.get_figure(), ax.get_figure().gca()
if ThreeD and ax.name != '3d':
fig.delaxes(ax)
ax = fig.add_subplot(111, projection='3d')
# Collect coordinates
Ps = np.unique(conns[Ts])
X, Y, Z = coords[Ps].T
xyz = coords[:, dim]
P1, P2 = conns[Ts].T
throat_pos = np.column_stack((xyz[P1], xyz[P2])).reshape((Ts.size, 2, dim.sum()))
# Deal with optional style related arguments
if 'c' in kwargs.keys():
color = kwargs.pop('c')
color = mcolors.to_rgb(color) + tuple([alpha])
# Override colors with color_by if given
if color_by is not None:
color = cm.get_cmap(name=cmap)(color_by / color_by.max())
color[:, 3] = alpha
if size_by is not None:
linewidth = size_by / size_by.max() * linewidth
if ThreeD:
lc = Line3DCollection(throat_pos, colors=color, cmap=cmap,
linestyles=linestyle, linewidths=linewidth,
antialiaseds=np.ones_like(Ts), **kwargs)
else:
lc = LineCollection(throat_pos, colors=color, cmap=cmap,
linestyles=linestyle, linewidths=linewidth,
antialiaseds=np.ones_like(Ts), **kwargs)
ax.add_collection(lc)
_scale_axes(ax=ax, X=X, Y=Y, Z=Z)
_label_axes(ax=ax, X=X, Y=Y, Z=Z)
fig.tight_layout()
return lc
|
Produce a 3D plot of the network topology
This shows how edges connect for quick visualization without having
to export data to veiw in Paraview.
Parameters
----------
network : dict
The network dictionary
edges : array_like (optional)
The list of edges to plot if only a sub-sample is desired. This is
useful for inspecting a small region of the network. If no edges are
specified then all are shown.
fig : Matplotlib figure handle and line property arguments (optional)
If a ``fig`` is supplied, then the topology will be overlaid on this
plot. This makes it possible to combine coordinates and connections,
and to color edges differently for instance.
size_by : array_like (optional)
An ndarray of edge values (e.g. alg['throat.rate']). These
values are used to scale the ``linewidth``, so if the lines are too
thin, then increase ``linewidth``.
color_by : str or array_like (optional)
An ndarray of edge values (e.g. alg['edge.rate']).
cmap : str or cmap object (optional)
The matplotlib colormap to use if specfying an edge property
for ``color_by``
color : str, optional (optional)
A matplotlib named color (e.g. 'r' for red).
alpha : float (optional)
The transparency of the lines, with 1 being solid and 0 being invisible
linestyle : str (optional)
Can be one of {'solid', 'dashed', 'dashdot', 'dotted'}. Default is
'solid'.
linewidth : float (optional)
Controls the thickness of drawn lines. Is used to scale the thickness
if ``size_by`` is given. Default is 1. If a value is provided for
``size_by`` then they are used to scale the ``linewidth``.
**kwargs : dict
All other keyword arguments are passed on to the ``Line3DCollection``
class of matplotlib, so check their documentation for additional
formatting options.
Returns
-------
lc : LineCollection or Line3DCollection
Matplotlib object containing the lines representing the throats.
Notes
-----
To create a single plot containing both coordinates and connections,
consider creating an empty figure and then passing the ``ax`` object as
an argument to ``plot_connections`` and ``plot_coordinates``.
Otherwise, each call to either of these methods creates a new figure.
See Also
--------
plot_coordinates
|
plot_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/_skgraph/visualization/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/_skgraph/visualization/_funcs.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.