code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
byte-like -> bytes
'''
b2 = hashlib.blake2b(**kwargs)
b2.update(data)
return b2.digest() | def blake2b(data=b'', **kwargs) | byte-like -> bytes | 4.403479 | 2.954104 | 1.490631 |
'''
bytes, bool, bool -> str
cashaddrs are preferred where possible
but cashaddr is ignored in most cases
is there a better way to structure this?
'''
addr_bytes = bytearray()
if riemann.network.CASHADDR_P2SH is not None and cashaddr:
addr_bytes.extend(riemann.network.CASHADDR_P2... | def _hash_to_sh_address(script_hash, witness=False, cashaddr=True) | bytes, bool, bool -> str
cashaddrs are preferred where possible
but cashaddr is ignored in most cases
is there a better way to structure this? | 2.845916 | 1.983373 | 1.434887 |
'''
makes an p2sh address from a serialized script
'''
if witness:
script_hash = utils.sha256(script_bytes)
else:
script_hash = utils.hash160(script_bytes)
return _hash_to_sh_address(
script_hash=script_hash,
witness=witness,
cashaddr=cashaddr) | def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True) | makes an p2sh address from a serialized script | 3.218331 | 2.806647 | 1.146682 |
'''
str, bool, bool -> str
'''
script_bytes = script_ser.serialize(script_string)
return _ser_script_to_sh_address(
script_bytes=script_bytes,
witness=witness,
cashaddr=cashaddr) | def make_sh_address(script_string, witness=False, cashaddr=True) | str, bool, bool -> str | 4.693208 | 3.851299 | 1.218604 |
'''
bytes, bool -> str
'''
addr_bytes = bytearray()
if riemann.network.CASHADDR_P2PKH is not None and cashaddr:
addr_bytes.extend(riemann.network.CASHADDR_P2PKH)
addr_bytes.extend(pubkey_hash)
return riemann.network.CASHADDR_ENCODER.encode(addr_bytes)
if witness:
... | def _make_pkh_address(pubkey_hash, witness=False, cashaddr=True) | bytes, bool -> str | 2.157604 | 1.991014 | 1.083671 |
'''
bytes, bool -> str
'''
pubkey_hash = utils.hash160(pubkey)
return _make_pkh_address(pubkey_hash=pubkey_hash,
witness=witness,
cashaddr=cashaddr) | def make_pkh_address(pubkey, witness=False, cashaddr=True) | bytes, bool -> str | 3.904132 | 2.958241 | 1.319748 |
'''
str -> bytes
There's probably a better way to do this
'''
parsed = parse(address)
parsed_hash = b''
try:
if (parsed.find(riemann.network.P2WPKH_PREFIX) == 0
and len(parsed) == 22):
return parsed
except TypeError:
pass
try:
if ... | def to_output_script(address) | str -> bytes
There's probably a better way to do this | 1.732574 | 1.69067 | 1.024785 |
'''
bytes -> str
Convert output script (the on-chain format) to an address
There's probably a better way to do this
'''
try:
if (len(output_script) == len(riemann.network.P2WSH_PREFIX) + 32
and output_script.find(riemann.network.P2WSH_PREFIX) == 0):
# Script h... | def from_output_script(output_script, cashaddr=True) | bytes -> str
Convert output script (the on-chain format) to an address
There's probably a better way to do this | 2.345321 | 2.087776 | 1.123358 |
'''
str -> bytes
There's probably a better way to do this.
'''
raw = parse(address)
# Cash addresses
try:
if address.find(riemann.network.CASHADDR_PREFIX) == 0:
if raw.find(riemann.network.CASHADDR_P2SH) == 0:
return raw[len(riemann.network.CASHADDR_P2SH... | def parse_hash(address) | str -> bytes
There's probably a better way to do this. | 1.875236 | 1.774303 | 1.056886 |
'''
str -> int
Bitcoin uses tx version 2 for nSequence signaling.
Zcash uses tx version 2 for joinsplits.
We want to signal nSequence if we're using OP_CSV.
Unless we're in zcash.
'''
n = riemann.get_current_network_name()
if 'sprout' in n:
return 1
if 'overwinter' in n:... | def guess_version(redeem_script) | str -> int
Bitcoin uses tx version 2 for nSequence signaling.
Zcash uses tx version 2 for joinsplits.
We want to signal nSequence if we're using OP_CSV.
Unless we're in zcash. | 8.712403 | 3.062074 | 2.845262 |
'''
str -> int
If OP_CSV is used, guess an appropriate sequence
Otherwise, disable RBF, but leave lock_time on.
Fails if there's not a constant before OP_CSV
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKSEQUENCEVERIFY')
return int(sc... | def guess_sequence(redeem_script) | str -> int
If OP_CSV is used, guess an appropriate sequence
Otherwise, disable RBF, but leave lock_time on.
Fails if there's not a constant before OP_CSV | 9.714251 | 2.600513 | 3.735513 |
'''
str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKLOCKTIMEVERIFY')
return int(script_array[... | def guess_locktime(redeem_script) | str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV | 6.412394 | 2.430151 | 2.638681 |
'''
int, str -> TxOut
accepts base58 or bech32 addresses
'''
script = addr.to_output_script(address)
value = utils.i2le_padded(value, 8)
return tb._make_output(value, script) | def output(value, address) | int, str -> TxOut
accepts base58 or bech32 addresses | 11.88005 | 6.129171 | 1.93828 |
'''
hex_str, int, int -> Outpoint
accepts block explorer txid string
'''
tx_id_le = bytes.fromhex(tx_id)[::-1]
return tb.make_outpoint(tx_id_le, index, tree) | def outpoint(tx_id, index, tree=None) | hex_str, int, int -> Outpoint
accepts block explorer txid string | 10.776366 | 5.169725 | 2.084514 |
'''
Outpoint, byte-like, int -> TxIn
'''
if redeem_script is not None and sequence is None:
sequence = guess_sequence(redeem_script)
if sequence is None:
sequence = 0xFFFFFFFE
return tb.make_legacy_input(
outpoint=outpoint,
stack_script=b'',
redeem_script=... | def unsigned_input(outpoint, redeem_script=None, sequence=None) | Outpoint, byte-like, int -> TxIn | 5.256197 | 3.695839 | 1.422193 |
'''
OutPoint, hex_string, hex_string, int -> TxIn
Create a signed legacy TxIn from a p2pkh prevout
'''
stack_script = '{sig} {pk}'.format(sig=sig, pk=pubkey)
stack_script = script_ser.serialize(stack_script)
return tb.make_legacy_input(outpoint, stack_script, b'', sequence) | def p2pkh_input(outpoint, sig, pubkey, sequence=0xFFFFFFFE) | OutPoint, hex_string, hex_string, int -> TxIn
Create a signed legacy TxIn from a p2pkh prevout | 9.821783 | 5.010481 | 1.960248 |
'''
OutPoint, hex_string, hex_string, int -> (TxIn, InputWitness)
Create a signed legacy TxIn from a p2pkh prevout
Create an empty InputWitness for it
Useful for transactions spending some witness and some legacy prevouts
'''
stack_script = '{sig} {pk}'.format(sig=sig, pk=pubkey)
return ... | def p2pkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE) | OutPoint, hex_string, hex_string, int -> (TxIn, InputWitness)
Create a signed legacy TxIn from a p2pkh prevout
Create an empty InputWitness for it
Useful for transactions spending some witness and some legacy prevouts | 9.620491 | 3.28641 | 2.927356 |
'''
OutPoint, str, str, int -> TxIn
Create a signed legacy TxIn from a p2pkh prevout
'''
if sequence is None:
sequence = guess_sequence(redeem_script)
stack_script = script_ser.serialize(stack_script)
redeem_script = script_ser.hex_serialize(redeem_script)
redeem_script = script... | def p2sh_input(outpoint, stack_script, redeem_script, sequence=None) | OutPoint, str, str, int -> TxIn
Create a signed legacy TxIn from a p2pkh prevout | 4.093661 | 2.886264 | 1.418325 |
'''
OutPoint, str, str, int -> (TxIn, InputWitness)
Create a signed legacy TxIn from a p2pkh prevout
Create an empty InputWitness for it
Useful for transactions spending some witness and some legacy prevouts
'''
if sequence is None:
sequence = guess_sequence(redeem_script)
stack... | def p2sh_input_and_witness(outpoint, stack_script,
redeem_script, sequence=None) | OutPoint, str, str, int -> (TxIn, InputWitness)
Create a signed legacy TxIn from a p2pkh prevout
Create an empty InputWitness for it
Useful for transactions spending some witness and some legacy prevouts | 5.393066 | 2.392793 | 2.253879 |
'''
Outpoint, hex_string, hex_string, int -> (TxIn, InputWitness)
Create a signed witness TxIn and InputWitness from a p2wpkh prevout
'''
return tb.make_witness_input_and_witness(
outpoint=outpoint,
sequence=sequence,
stack=[bytes.fromhex(sig), bytes.fromhex(pubkey)]) | def p2wpkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE) | Outpoint, hex_string, hex_string, int -> (TxIn, InputWitness)
Create a signed witness TxIn and InputWitness from a p2wpkh prevout | 6.667355 | 3.038169 | 2.194531 |
'''
Outpoint, str, str, int -> (TxIn, InputWitness)
Create a signed witness TxIn and InputWitness from a p2wsh prevout
'''
if sequence is None:
sequence = guess_sequence(witness_script)
stack = list(map(
lambda x: b'' if x == 'NONE' else bytes.fromhex(x), stack.split()))
stac... | def p2wsh_input_and_witness(outpoint, stack, witness_script, sequence=None) | Outpoint, str, str, int -> (TxIn, InputWitness)
Create a signed witness TxIn and InputWitness from a p2wsh prevout | 5.841707 | 3.785647 | 1.54312 |
'''Create an unsigned transaction
Use this to generate sighashes for unsigned TxIns
Gotcha: it requires you to know the timelock and version
it will _not_ guess them
becuase it may not have acess to all scripts
Hint: set version to 2 if using sequence number relative time locks
... | def unsigned_legacy_tx(tx_ins, tx_outs, **kwargs) | Create an unsigned transaction
Use this to generate sighashes for unsigned TxIns
Gotcha: it requires you to know the timelock and version
it will _not_ guess them
becuase it may not have acess to all scripts
Hint: set version to 2 if using sequence number relative time locks
Arg... | 4.384819 | 1.360342 | 3.223322 |
'''Create an unsigned segwit transaction
Create an unsigned segwit transaction
Use this to generate sighashes for unsigned TxIns
Gotcha: it requires you to know the timelock and version
it will _not_ guess them
becuase it may not have acess to all scripts
Hint: set version to... | def unsigned_witness_tx(tx_ins, tx_outs, **kwargs) | Create an unsigned segwit transaction
Create an unsigned segwit transaction
Use this to generate sighashes for unsigned TxIns
Gotcha: it requires you to know the timelock and version
it will _not_ guess them
becuase it may not have acess to all scripts
Hint: set version to 2 if u... | 6.795793 | 1.579196 | 4.303323 |
'''
Construct a fully-signed legacy transaction
Args:
tx_ins list(TxIn instances): list of transaction inputs
tx_outs list(TxOut instances): list of transaction outputs
**kwargs:
version (int): transaction version number
locktime (hex): transaction lo... | def legacy_tx(tx_ins, tx_outs, **kwargs) | Construct a fully-signed legacy transaction
Args:
tx_ins list(TxIn instances): list of transaction inputs
tx_outs list(TxOut instances): list of transaction outputs
**kwargs:
version (int): transaction version number
locktime (hex): transaction locktime
... | 3.214211 | 1.943351 | 1.653952 |
'''
Construct a fully-signed segwit transaction
Args:
tx_ins list(TxIn instances): list of transaction inputs
tx_outs list(TxOut instances): list of transaction outputs
tx_witnesses list(TxWitness instances): list of transaction witnsses
**kwargs:
version ... | def witness_tx(tx_ins, tx_outs, tx_witnesses, **kwargs) | Construct a fully-signed segwit transaction
Args:
tx_ins list(TxIn instances): list of transaction inputs
tx_outs list(TxOut instances): list of transaction outputs
tx_witnesses list(TxWitness instances): list of transaction witnsses
**kwargs:
version (int): tr... | 3.779319 | 2.549104 | 1.482607 |
'''
OverwinterTx, ... -> OverwinterTx
Makes a copy. Allows over-writing specific pieces.
'''
return OverwinterTx(
tx_ins=tx_ins if tx_ins is not None else self.tx_ins,
tx_outs=tx_outs if tx_outs is not None else self.tx_outs,
lock_time=(lock_t... | def copy(self, tx_ins=None, tx_outs=None, lock_time=None,
expiry_height=None, tx_joinsplits=None, joinsplit_pubkey=None,
joinsplit_sig=None) | OverwinterTx, ... -> OverwinterTx
Makes a copy. Allows over-writing specific pieces. | 1.984322 | 1.466172 | 1.353403 |
'''
byte-like -> OverwinterTx
'''
header = byte_string[0:4]
group_id = byte_string[4:8]
if header != b'\x03\x00\x00\x80' or group_id != b'\x70\x82\xc4\x03':
raise ValueError(
'Bad header or group ID. Expected {} and {}. Got: {} and {}'
... | def from_bytes(OverwinterTx, byte_string) | byte-like -> OverwinterTx | 1.815448 | 1.791582 | 1.013321 |
dir_path = os.path.join(os.path.expanduser('~'), '.keep')
if os.path.exists(dir_path):
if click.confirm('[CRITICAL] Remove everything inside ~/.keep ?', abort=True):
shutil.rmtree(dir_path)
utils.first_time_use(ctx) | def cli(ctx) | Initializes the CLI environment. | 5.110957 | 4.814704 | 1.061531 |
matches = utils.grep_commands(pattern)
if matches:
selected = utils.select_command(matches)
if selected >= 0:
cmd, desc = matches[selected]
pcmd = utils.create_pcmd(cmd)
raw_params, params, defaults = utils.get_params_in_pcmd(pcmd)
arguments... | def cli(ctx, pattern, arguments, safe) | Executes a saved command. | 4.179084 | 3.984142 | 1.048929 |
cmd = click.prompt('Command')
desc = click.prompt('Description ')
alias = click.prompt('Alias (optional)', default='')
utils.save_command(cmd, desc, alias)
utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc)) | def cli(ctx) | Saves a new command | 6.198548 | 4.752772 | 1.304196 |
if args:
msg %= args
click.echo(msg, file=sys.stderr) | def log(self, msg, *args) | Logs a message to stderr. | 4.626146 | 3.65086 | 1.267139 |
if self.verbose:
self.log(msg, *args) | def vlog(self, msg, *args) | Logs a message to stderr only if verbose is enabled. | 4.102341 | 3.854191 | 1.064385 |
utils.check_update(ctx, forced=True)
click.secho("Keep is at its latest version v{}".format(about.__version__), fg='green') | def cli(ctx) | Check for an update of Keep. | 19.043541 | 11.152538 | 1.707552 |
matches = utils.grep_commands(pattern)
if matches:
for cmd, desc in matches:
click.secho("$ {} :: {}".format(cmd, desc), fg='green')
elif matches == []:
click.echo('No saved commands matches the pattern {}'.format(pattern))
else:
click.echo('No commands to show. ... | def cli(ctx, pattern) | Searches for a saved command. | 6.428598 | 5.342097 | 1.203385 |
json_path = os.path.join(os.path.expanduser('~'), '.keep', 'commands.json')
if not os.path.exists(json_path):
click.echo('No commands to show. Add one by `keep new`.')
else:
utils.list_commands(ctx) | def cli(ctx) | Shows the saved commands. | 4.666041 | 3.972244 | 1.174661 |
credentials_path = os.path.join(os.path.expanduser('~'), '.keep', '.credentials')
if not os.path.exists(credentials_path):
click.echo('You are not registered.')
utils.register()
else:
utils.pull(ctx, overwrite) | def cli(ctx, overwrite) | Updates the local database with remote. | 4.541011 | 4.392464 | 1.033819 |
dir_path = os.path.join(os.path.expanduser('~'), '.keep', '.credentials')
if os.path.exists(dir_path):
if click.confirm('[CRITICAL] Reset credentials saved in ~/.keep/.credentials ?', abort=True):
os.remove(dir_path)
utils.register() | def cli(ctx) | Register user over server. | 5.866469 | 5.256611 | 1.116017 |
try:
if ctx.update_checked and not forced:
return
except AttributeError:
update_check_file = os.path.join(dir_path, 'update_check.txt')
today = datetime.date.today().strftime("%m/%d/%Y")
if os.path.exists(update_check_file):
date = open(update_check_f... | def check_update(ctx, forced=False) | Check for update on pypi. Limit to 1 check per day if not forced | 3.194234 | 3.054002 | 1.045917 |
commands = utils.read_commands()
if commands is []:
click.echo("No commands to edit, Add one by 'keep new'. ")
else:
edit_header = "# Unchanged file will abort the operation\n"
new_commands = utils.edit_commands(commands, editor, edit_header)
if new_commands and new_com... | def cli(ctx, editor) | Edit saved commands. | 4.22801 | 3.906273 | 1.082364 |
matches = utils.grep_commands(pattern)
if matches:
selected = utils.select_command(matches)
if selected >= 0:
cmd, desc = matches[selected]
command = "$ {} :: {}".format(cmd, desc)
if click.confirm("Remove\n\t{}\n\n?".format(command), default=True):
... | def cli(ctx, pattern) | Deletes a saved command. | 5.650498 | 5.076806 | 1.113003 |
r
lim_max = sp.amax(mesh.verts, axis=0)
lim_min = sp.amin(mesh.verts, axis=0)
# Display resulting triangular mesh using Matplotlib.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Fancy indexing: `verts[faces]` to generate a collection of triangles
mesh = Poly3DCollecti... | def show_mesh(mesh) | r"""
Visualizes the mesh of a region as obtained by ``get_mesh`` function in
the ``metrics`` submodule.
Parameters
----------
mesh : tuple
A mesh returned by ``skimage.measure.marching_cubes``
Returns
-------
fig : Matplotlib figure
A handle to a matplotlib 3D axis | 1.993032 | 2.112861 | 0.943286 |
r
im_temp = sp.zeros_like(im)
crds = sp.array(sp.rand(npoints, im.ndim)*im.shape, dtype=int)
pads = sp.array(sp.rand(npoints)*sp.amin(im.shape)/2+10, dtype=int)
im_temp[tuple(crds.T)] = True
labels, N = spim.label(input=im_temp)
slices = spim.find_objects(input=labels)
porosity = sp.zero... | def representative_elementary_volume(im, npoints=1000) | r"""
Calculates the porosity of the image as a function subdomain size. This
function extracts a specified number of subdomains of random size, then
finds their porosity.
Parameters
----------
im : ND-array
The image of the porous material
npoints : int
The number of random... | 3.424069 | 3.344758 | 1.023712 |
r
if axis >= im.ndim:
raise Exception('axis out of range')
im = np.atleast_3d(im)
a = set(range(im.ndim)).difference(set([axis]))
a1, a2 = a
prof = np.sum(np.sum(im, axis=a2), axis=a1)/(im.shape[a2]*im.shape[a1])
return prof*100 | def porosity_profile(im, axis) | r"""
Returns a porosity profile along the specified axis
Parameters
----------
im : ND-array
The volumetric image for which to calculate the porosity profile
axis : int
The axis (0, 1, or 2) along which to calculate the profile. For
instance, if `axis` is 0, then the porosi... | 3.471178 | 3.96981 | 0.874394 |
r
if im.dtype == bool:
im = spim.distance_transform_edt(im)
mask = find_dt_artifacts(im) == 0
im[mask] = 0
x = im[im > 0].flatten()
h = sp.histogram(x, bins=bins, density=True)
h = _parse_histogram(h=h, voxel_size=voxel_size)
rdf = namedtuple('radial_density_function',
... | def radial_density(im, bins=10, voxel_size=1) | r"""
Computes radial density function by analyzing the histogram of voxel
values in the distance transform. This function is defined by
Torquato [1] as:
.. math::
\int_0^\infty P(r)dr = 1.0
where *P(r)dr* is the probability of finding a voxel at a lying at a radial
distance b... | 3.919281 | 3.584329 | 1.093449 |
r
im = sp.array(im, dtype=int)
Vp = sp.sum(im == 1)
Vs = sp.sum(im == 0)
e = Vp/(Vs + Vp)
return e | def porosity(im) | r"""
Calculates the porosity of an image assuming 1's are void space and 0's are
solid phase.
All other values are ignored, so this can also return the relative
fraction of a phase of interest.
Parameters
----------
im : ND-array
Image of the void space with 1's indicating void spa... | 4.933902 | 5.579087 | 0.884356 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if im.ndim == 2:
pts = sp.meshgrid(range(0, im.shape[0], spa... | def two_point_correlation_bf(im, spacing=10) | r"""
Calculates the two-point correlation function using brute-force (see Notes)
Parameters
----------
im : ND-array
The image of the void space on which the 2-point correlation is desired
spacing : int
The space between points on the regular grid that is used to generate
th... | 2.985049 | 2.610238 | 1.143593 |
r
if len(autocorr.shape) == 2:
adj = sp.reshape(autocorr.shape, [2, 1, 1])
inds = sp.indices(autocorr.shape) - adj/2
dt = sp.sqrt(inds[0]**2 + inds[1]**2)
elif len(autocorr.shape) == 3:
adj = sp.reshape(autocorr.shape, [3, 1, 1, 1])
inds = sp.indices(autocorr.shape) -... | def _radial_profile(autocorr, r_max, nbins=100) | r"""
Helper functions to calculate the radial profile of the autocorrelation
Masks the image in radial segments from the center and averages the values
The distance values are normalized and 100 bins are used as default.
Parameters
----------
autocorr : ND-array
The image of autocorrela... | 3.032122 | 2.878514 | 1.053364 |
r
# Calculate half lengths of the image
hls = (np.ceil(np.shape(im))/2).astype(int)
# Fourier Transform and shift image
F = sp_ft.ifftshift(sp_ft.fftn(sp_ft.fftshift(im)))
# Compute Power Spectrum
P = sp.absolute(F**2)
# Auto-correlation is inverse of Power Spectrum
autoc = sp.absolu... | def two_point_correlation_fft(im) | r"""
Calculates the two-point correlation function using fourier transforms
Parameters
----------
im : ND-array
The image of the void space on which the 2-point correlation is desired
Returns
-------
result : named_tuple
A tuple containing the x and y data for plotting the ... | 5.769037 | 5.535493 | 1.04219 |
r
im = im.flatten()
vals = im[im > 0]*voxel_size
if log:
vals = sp.log10(vals)
h = _parse_histogram(sp.histogram(vals, bins=bins, density=True))
psd = namedtuple('pore_size_distribution',
(log*'log' + 'R', 'pdf', 'cdf', 'satn',
'bin_centers', 'b... | def pore_size_distribution(im, bins=10, log=True, voxel_size=1) | r"""
Calculate a pore-size distribution based on the image produced by the
``porosimetry`` or ``local_thickness`` functions.
Parameters
----------
im : ND-array
The array of containing the sizes of the largest sphere that overlaps
each voxel. Obtained from either ``porosimetry`` or... | 4.698265 | 3.374897 | 1.392121 |
r
labels, N = spim.label(im > 0)
props = regionprops(labels, coordinates='xy')
chord_lens = sp.array([i.filled_area for i in props])
return chord_lens | def chord_counts(im) | r"""
Finds the length of each chord in the supplied image and returns a list
of their individual sizes
Parameters
----------
im : ND-array
An image containing chords drawn in the void space.
Returns
-------
result : 1D-array
A 1D array with one element for each chord, c... | 6.130771 | 9.632071 | 0.636496 |
r
x = im[im > 0]
h = list(sp.histogram(x, bins=bins, density=True))
h = _parse_histogram(h=h, voxel_size=voxel_size)
cld = namedtuple('linear_density_function',
('L', 'pdf', 'cdf', 'relfreq',
'bin_centers', 'bin_edges', 'bin_widths'))
return cld(h.bin_c... | def linear_density(im, bins=25, voxel_size=1, log=False) | r"""
Determines the probability that a point lies within a certain distance
of the opposite phase *along a specified direction*
This relates directly the radial density function defined by Torquato [1],
but instead of reporting the probability of lying within a stated distance
to the nearest solid ... | 4.077096 | 4.41737 | 0.922969 |
r
x = chord_counts(im)
if bins is None:
bins = sp.array(range(0, x.max()+2))*voxel_size
x = x*voxel_size
if log:
x = sp.log10(x)
if normalization == 'length':
h = list(sp.histogram(x, bins=bins, density=False))
h[0] = h[0]*(h[1][1:]+h[1][:-1])/2 # Scale bin heigt... | def chord_length_distribution(im, bins=None, log=False, voxel_size=1,
normalization='count') | r"""
Determines the distribution of chord lengths in an image containing chords.
Parameters
----------
im : ND-image
An image with chords drawn in the pore space, as produced by
``apply_chords`` or ``apply_chords_3d``.
``im`` can be either boolean, in which case each chord will... | 3.477675 | 3.119134 | 1.114949 |
r
print('_'*60)
print('Finding interfacial areas between each region')
from skimage.morphology import disk, square, ball, cube
im = regions.copy()
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimen... | def region_interface_areas(regions, areas, voxel_size=1, strel=None) | r"""
Calculates the interfacial area between all pairs of adjecent regions
Parameters
----------
regions : ND-array
An image of the pore space partitioned into individual pore regions.
Note that zeros in the image will not be considered for area
calculation.
areas : array_li... | 4.201116 | 3.83711 | 1.094865 |
r
print('_'*60)
print('Finding surface area of each region')
im = regions.copy()
# Get 'slices' into im for each pore region
slices = spim.find_objects(im)
# Initialize arrays
Ps = sp.arange(1, sp.amax(im)+1)
sa = sp.zeros_like(Ps, dtype=float)
# Start extracting marching cube ar... | def region_surface_areas(regions, voxel_size=1, strel=None) | r"""
Extracts the surface area of each region in a labeled image.
Optionally, it can also find the the interfacial area between all
adjoining regions.
Parameters
----------
regions : ND-array
An image of the pore space partitioned into individual pore regions.
Note that zeros i... | 6.078142 | 5.577309 | 1.089798 |
r
if mesh:
verts = mesh.verts
faces = mesh.faces
else:
if (verts is None) or (faces is None):
raise Exception('Either mesh or verts and faces must be given')
surface_area = measure.mesh_surface_area(verts, faces)
return surface_area | def mesh_surface_area(mesh=None, verts=None, faces=None) | r"""
Calculates the surface area of a meshed region
Parameters
----------
mesh : tuple
The tuple returned from the ``mesh_region`` function
verts : array
An N-by-ND array containing the coordinates of each mesh vertex
faces : array
An N-by-ND array indicating which eleme... | 3.151628 | 3.63508 | 0.867004 |
r
if im.dtype == bool:
im = im.astype(int)
elif im.dtype != int:
raise Exception('Image must contain integer values for each phase')
labels = sp.arange(0, sp.amax(im)+1)
results = sp.zeros_like(labels)
for i in labels:
results[i] = sp.sum(im == i)
if normed:
r... | def phase_fraction(im, normed=True) | r"""
Calculates the number (or fraction) of each phase in an image
Parameters
----------
im : ND-array
An ND-array containing integer values
normed : Boolean
If ``True`` (default) the returned values are normalized by the total
number of voxels in image, otherwise the voxel ... | 3.857807 | 4.162828 | 0.926727 |
r
if sp.squeeze(im.ndim) < 3:
raise Exception('This view is only necessary for 3D images')
x, y, z = (sp.array(im.shape)/2).astype(int)
im_xy = im[:, :, z]
im_xz = im[:, y, :]
im_yz = sp.rot90(im[x, :, :])
new_x = im_xy.shape[0] + im_yz.shape[0] + 10
new_y = im_xy.shape[1] + im... | def show_planes(im) | r"""
Create a quick montage showing a 3D image in all three directions
Parameters
----------
im : ND-array
A 3D image of the porous material
Returns
-------
image : ND-array
A 2D array containing the views. This single image can be viewed using
``matplotlib.pyplot.... | 2.412392 | 2.382642 | 1.012486 |
r
im = sp.array(~im, dtype=int)
if direction in ['Y', 'y']:
im = sp.transpose(im, axes=[1, 0, 2])
if direction in ['Z', 'z']:
im = sp.transpose(im, axes=[2, 1, 0])
t = im.shape[0]
depth = sp.reshape(sp.arange(0, t), [t, 1, 1])
im = im*depth
im = sp.amax(im, axis=0)
re... | def sem(im, direction='X') | r"""
Simulates an SEM photograph looking into the porous material in the
specified direction. Features are colored according to their depth into
the image, so darker features are further away.
Parameters
----------
im : array_like
ND-image of the porous material with the solid phase ma... | 2.928183 | 3.260145 | 0.898176 |
r
im = sp.array(~im, dtype=int)
if direction in ['Y', 'y']:
im = sp.transpose(im, axes=[1, 0, 2])
if direction in ['Z', 'z']:
im = sp.transpose(im, axes=[2, 1, 0])
im = sp.sum(im, axis=0)
return im | def xray(im, direction='X') | r"""
Simulates an X-ray radiograph looking through the porouls material in the
specfied direction. The resulting image is colored according to the amount
of attenuation an X-ray would experience, so regions with more solid will
appear darker.
Parameters
----------
im : array_like
N... | 2.684821 | 3.250916 | 0.825866 |
r
# Parse the regionprops list and pull out all props with scalar values
metrics = []
reg = regionprops[0]
for item in reg.__dir__():
if not item.startswith('_'):
try:
if sp.shape(getattr(reg, item)) == ():
metrics.append(item)
exce... | def props_to_DataFrame(regionprops) | r"""
Returns a Pandas DataFrame containing all the scalar metrics for each
region, such as volume, sphericity, and so on, calculated by
``regionprops_3D``.
Parameters
----------
regionprops : list
This is a list of properties for each region that is computed
by ``regionprops_3D`... | 5.896379 | 5.966064 | 0.98832 |
r
im = sp.zeros(shape=shape)
for r in regionprops:
if prop == 'convex':
mask = r.convex_image
else:
mask = r.image
temp = mask * r[prop]
s = bbox_to_slices(r.bbox)
im[s] += temp
return im | def props_to_image(regionprops, shape, prop) | r"""
Creates an image with each region colored according the specified ``prop``,
as obtained by ``regionprops_3d``.
Parameters
----------
regionprops : list
This is a list of properties for each region that is computed
by PoreSpy's ``regionprops_3D`` or Skimage's ``regionsprops``.
... | 4.602747 | 5.643798 | 0.815541 |
r
vs = voxel_size
for entry in data:
if data[entry].dtype == bool:
data[entry] = data[entry].astype(np.int8)
if data[entry].flags['C_CONTIGUOUS']:
data[entry] = np.ascontiguousarray(data[entry])
imageToVTK(path, cellData=data, spacing=(vs, vs, vs), origin=origin) | def dict_to_vtk(data, path='./dictvtk', voxel_size=1, origin=(0, 0, 0)) | r"""
Accepts multiple images as a dictionary and compiles them into a vtk file
Parameters
----------
data : dict
A dictionary of *key: value* pairs, where the *key* is the name of the
scalar property stored in each voxel of the array stored in the
corresponding *value*.
path... | 3.57763 | 4.128487 | 0.866572 |
r
from openpnm.network import GenericNetwork
# Convert net dict to an openpnm Network
pn = GenericNetwork()
pn.update(net)
pn.project.save_project(filename)
ws = pn.project.workspace
ws.close_project(pn.project) | def to_openpnm(net, filename) | r"""
Save the result of the `snow` network extraction function in a format
suitable for opening in OpenPNM.
Parameters
----------
net : dict
The dictionary object produced by the network extraction functions
filename : string or path object
The name and location to save the fil... | 5.876146 | 7.205894 | 0.815464 |
r
if len(im.shape) == 2:
im = im[:, :, np.newaxis]
if im.dtype == bool:
vox = True
if vox:
im = im.astype(np.int8)
vs = voxel_size
if divide:
split = np.round(im.shape[2]/2).astype(np.int)
im1 = im[:, :, 0:split]
im2 = im[:, :, split:]
imag... | def to_vtk(im, path='./voxvtk', divide=False, downsample=False, voxel_size=1,
vox=False) | r"""
Converts an array to a vtk file.
Parameters
----------
im : 3D image
The image of the porous material
path : string
Path to output file
divide : bool
vtk files can get very large, this option allows you for two output
files, divided at z = half. This allows ... | 2.203917 | 2.206624 | 0.998773 |
r
# Create binary image for fluid and solid phases
bin_im = im == solid
# Transform to integer for distance transform
bin_im = bin_im.astype(int)
# Distance Transform computes Euclidean distance in lattice units to
# Nearest fluid for every solid voxel
dt = nd.distance_transform_edt(bin_... | def to_palabos(im, filename, solid=0) | r"""
Converts an ND-array image to a text file that Palabos can read in as a
geometry for Lattice Boltzmann simulations. Uses a Euclidean distance
transform to identify solid voxels neighboring fluid voxels and labels
them as the interface.
Parameters
----------
im : ND-array
The im... | 5.66145 | 4.71982 | 1.199505 |
r
return generate_voxel_image(network, pore_shape=pore_shape,
throat_shape=throat_shape, max_dim=max_dim,
verbose=verbose, rtol=rtol) | def openpnm_to_im(network, pore_shape="sphere", throat_shape="cylinder",
max_dim=None, verbose=1, rtol=0.1) | r"""
Generates voxel image from an OpenPNM network object.
Parameters
----------
network : OpenPNM GenericNetwork
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
Sha... | 2.723652 | 3.016832 | 0.902819 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if mode in ['backward', 'reverse']:
im = sp.flip(im, axis)
... | def distance_transform_lin(im, axis=0, mode='both') | r"""
Replaces each void voxel with the linear distance to the nearest solid
voxel along the specified axis.
Parameters
----------
im : ND-array
The image of the porous material with ``True`` values indicating the
void phase (or phase of interest)
axis : int
The directio... | 2.223412 | 2.179204 | 1.020286 |
r
im = dt > 0
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if footprint is None:
if im.ndim == 2:
... | def find_peaks(dt, r_max=4, footprint=None) | r"""
Returns all local maxima in the distance transform
Parameters
----------
dt : ND-array
The distance transform of the pore space. This may be calculated and
filtered using any means desired.
r_max : scalar
The size of the structuring element used in the maximum filter.... | 4.666939 | 5.447739 | 0.856675 |
r
if peaks.ndim == 2:
strel = square
else:
strel = cube
markers, N = spim.label(input=peaks, structure=strel(3))
inds = spim.measurements.center_of_mass(input=peaks,
labels=markers,
index=sp.arang... | def reduce_peaks(peaks) | r"""
Any peaks that are broad or elongated are replaced with a single voxel
that is located at the center of mass of the original voxels.
Parameters
----------
peaks : ND-image
An image containing True values indicating peaks in the distance
transform
Returns
-------
im... | 4.172719 | 3.945646 | 1.05755 |
r
peaks = sp.copy(peaks)
if dt.ndim == 2:
from skimage.morphology import square as cube
else:
from skimage.morphology import cube
labels, N = spim.label(peaks)
slices = spim.find_objects(labels)
for i in range(N):
s = extend_slice(s=slices[i], shape=peaks.shape, pad=1... | def trim_saddle_points(peaks, dt, max_iters=10) | r"""
Removes peaks that were mistakenly identified because they lied on a
saddle or ridge in the distance transform that was not actually a true
local peak.
Parameters
----------
peaks : ND-array
A boolean image containing True values to mark peaks in the distance
transform (``d... | 3.45021 | 3.518896 | 0.980481 |
r
peaks = sp.copy(peaks)
if dt.ndim == 2:
from skimage.morphology import square as cube
else:
from skimage.morphology import cube
peaks, N = spim.label(peaks, structure=cube(3))
crds = spim.measurements.center_of_mass(peaks, labels=peaks,
... | def trim_nearby_peaks(peaks, dt) | r"""
Finds pairs of peaks that are nearer to each other than to the solid phase,
and removes the peak that is closer to the solid.
Parameters
----------
peaks : ND-array
A boolean image containing True values to mark peaks in the distance
transform (``dt``)
dt : ND-array
... | 3.48268 | 3.508142 | 0.992742 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if im.ndim == 2:
if conn == 4:
strel = disk(1)
... | def find_disconnected_voxels(im, conn=None) | r"""
This identifies all pore (or solid) voxels that are not connected to the
edge of the image. This can be used to find blind pores, or remove
artifacts such as solid phase voxels that are floating in space.
Parameters
----------
im : ND-image
A Boolean image, with True values indica... | 4.145908 | 3.873052 | 1.07045 |
r
im = sp.copy(im)
holes = find_disconnected_voxels(im)
im[holes] = False
return im | def fill_blind_pores(im) | r"""
Fills all pores that are not connected to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected pores removed.
See Also
--------
find_... | 10.683798 | 9.751775 | 1.095575 |
r
im = sp.copy(im)
holes = find_disconnected_voxels(~im)
im[holes] = True
return im | def trim_floating_solid(im) | r"""
Removes all solid that that is not attached to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected solid removed.
See Also
--------
... | 14.497808 | 12.600683 | 1.150557 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
im = trim_floating_solid(~im)
labels = spim.label(~im)[0]
in... | def trim_nonpercolating_paths(im, inlet_axis=0, outlet_axis=0) | r"""
Removes all nonpercolating paths between specified edges
This function is essential when performing transport simulations on an
image, since image regions that do not span between the desired inlet and
outlet do not contribute to the transport.
Parameters
----------
im : ND-array
... | 2.286455 | 2.21765 | 1.031026 |
r
result = im
if mode in ['maxima', 'extrema']:
result = reconstruction(seed=im - h, mask=im, method='dilation')
elif mode in ['minima', 'extrema']:
result = reconstruction(seed=im + h, mask=im, method='erosion')
return result | def trim_extrema(im, h, mode='maxima') | r"""
Trims local extrema in greyscale values by a specified amount.
This essentially decapitates peaks and/or floods valleys.
Parameters
----------
im : ND-array
The image whose extrema are to be removed
h : float
The height to remove from each peak or fill in each valley
... | 4.234086 | 4.72434 | 0.896228 |
r
mask = im > 0
if regions is None:
labels, N = spim.label(mask)
else:
labels = sp.copy(regions)
N = labels.max()
I = im.flatten()
L = labels.flatten()
if mode.startswith('max'):
V = sp.zeros(shape=N+1, dtype=float)
for i in range(len(L)):
... | def flood(im, regions=None, mode='max') | r"""
Floods/fills each region in an image with a single value based on the
specific values in that region. The ``mode`` argument is used to
determine how the value is calculated.
Parameters
----------
im : array_like
An ND image with isolated regions containing 0's elsewhere.
regi... | 2.178948 | 2.413377 | 0.902863 |
r
temp = sp.ones(shape=dt.shape)*sp.inf
for ax in range(dt.ndim):
dt_lin = distance_transform_lin(sp.ones_like(temp, dtype=bool),
axis=ax, mode='both')
temp = sp.minimum(temp, dt_lin)
result = sp.clip(dt - temp, a_min=0, a_max=sp.inf)
return re... | def find_dt_artifacts(dt) | r"""
Finds points in a distance transform that are closer to wall than solid.
These points could *potentially* be erroneously high since their distance
values do not reflect the possibility that solid may have been present
beyond the border of the image but lost by trimming.
Parameters
-------... | 5.371768 | 5.442273 | 0.987045 |
r
if im.dtype == bool:
im = spim.label(im)[0]
counts = sp.bincount(im.flatten())
counts[0] = 0
chords = counts[im]
return chords | def region_size(im) | r"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
find regions, or a greyscale image with integer ... | 7.792514 | 6.65112 | 1.171609 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if spacing < 0:
raise Exception('Spacing cannot be less than... | def apply_chords(im, spacing=1, axis=0, trim_edges=True, label=False) | r"""
Adds chords to the void space in the specified direction. The chords are
separated by 1 voxel plus the provided spacing.
Parameters
----------
im : ND-array
An image of the porous material with void marked as ``True``.
spacing : int
Separation between chords. The default... | 4.297064 | 4.388328 | 0.979203 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if im.ndim < 3:
raise Exception('Must be a 3D image to use t... | def apply_chords_3D(im, spacing=0, trim_edges=True) | r"""
Adds chords to the void space in all three principle directions. The
chords are seprated by 1 voxel plus the provided spacing. Chords in the X,
Y and Z directions are labelled 1, 2 and 3 resepctively.
Parameters
----------
im : ND-array
A 3D image of the porous material with void... | 3.976173 | 3.977237 | 0.999733 |
r
im_new = porosimetry(im=im, sizes=sizes, access_limited=False, mode=mode)
return im_new | def local_thickness(im, sizes=25, mode='hybrid') | r"""
For each voxel, this functions calculates the radius of the largest sphere
that both engulfs the voxel and fits entirely within the foreground. This
is not the same as a simple distance transform, which finds the largest
sphere that could be *centered* on each voxel.
Parameters
----------
... | 12.109858 | 6.906686 | 1.753353 |
r
temp = sp.zeros_like(im)
temp[inlets] = True
labels, N = spim.label(im + temp)
im = im ^ (clear_border(labels=labels) > 0)
return im | def trim_disconnected_blobs(im, inlets) | r"""
Removes foreground voxels not connected to specified inlets
Parameters
----------
im : ND-array
The array to be trimmed
inlets : ND-array of tuple of indices
The locations of the inlets. Any voxels *not* connected directly to
the inlets will be trimmed
Returns
... | 9.965244 | 10.481935 | 0.950707 |
r'''
Helper function to generate the axial shifts that will be performed on
the image to identify bordering pixels/voxels
'''
if ndim == 2:
if include_diagonals:
neighbors = square(3)
else:
neighbors = diamond(1)
neighbors[1, 1] = 0
x, y = np.w... | def _get_axial_shifts(ndim=2, include_diagonals=False) | r'''
Helper function to generate the axial shifts that will be performed on
the image to identify bordering pixels/voxels | 2.467544 | 1.909195 | 1.292452 |
r'''
Creates a stack of images with one extra dimension to the input image
with length equal to the number of borders to search + 1.
Image is rolled along the axial shifts so that the border pixel is
overlapping the original pixel. First image in stack is the original.
Stacking makes direct vect... | def _make_stack(im, include_diagonals=False) | r'''
Creates a stack of images with one extra dimension to the input image
with length equal to the number of borders to search + 1.
Image is rolled along the axial shifts so that the border pixel is
overlapping the original pixel. First image in stack is the original.
Stacking makes direct vectoriz... | 2.496206 | 1.427046 | 1.749212 |
r'''
Identifies the voxels in regions that border *N* other regions.
Useful for finding triple-phase boundaries.
Parameters
----------
im : ND-array
An ND image of the porous material containing discrete values in the
pore space identifying different regions. e.g. the result of... | def nphase_border(im, include_diagonals=False) | r'''
Identifies the voxels in regions that border *N* other regions.
Useful for finding triple-phase boundaries.
Parameters
----------
im : ND-array
An ND image of the porous material containing discrete values in the
pore space identifying different regions. e.g. the result of a
... | 5.408484 | 2.642735 | 2.046548 |
r
values = sp.array(values).flatten()
if sp.size(values) != regions.max() + 1:
raise Exception('Number of values does not match number of regions')
im = sp.zeros_like(regions)
im = values[regions]
return im | def map_to_regions(regions, values) | r"""
Maps pore values from a network onto the image from which it was extracted
This function assumes that the pore numbering in the network has remained
unchanged from the region labels in the partitioned image.
Parameters
----------
regions : ND-array
An image of the pore space parti... | 4.827604 | 5.660773 | 0.852817 |
r
print("\n" + "-" * 44, flush=True)
print("| Generating voxel image from pore network |", flush=True)
print("-" * 44, flush=True)
# 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,
... | def generate_voxel_image(network, pore_shape="sphere", throat_shape="cylinder",
max_dim=None, verbose=1, rtol=0.1) | r"""
Generates voxel image from an OpenPNM network object.
Parameters
----------
network : OpenPNM GenericNetwork
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
Sha... | 3.19212 | 2.989171 | 1.067895 |
r
f = boundary_faces
if f is not None:
coords = network['pore.coords']
condition = coords[~network['pore.boundary']]
dic = {'left': 0, 'right': 0, 'front': 1, 'back': 1,
'top': 2, 'bottom': 2}
if all(coords[:, 2] == 0):
dic['top'] = 1
di... | def label_boundary_cells(network=None, boundary_faces=None) | r"""
Takes 2D or 3D network and assign labels to boundary pores
Parameters
----------
network : dictionary
A dictionary as produced by the SNOW network extraction algorithms
containing edge/vertex, site/bond, node/link information.
boundary_faces : list of strings
The user ... | 2.851108 | 2.887429 | 0.987421 |
r
im = im.copy()
if im.ndim != element.ndim:
raise Exception('Image shape ' + str(im.shape)
+ ' and element shape ' + str(element.shape)
+ ' do not match')
s_im = []
s_el = []
if (center is not None) and (corner is None):
for dim in... | def insert_shape(im, element, center=None, corner=None, value=1,
mode='overwrite') | r"""
Inserts sub-image into a larger image at the specified location.
If the inserted image extends beyond the boundaries of the image it will
be cropped accordingly.
Parameters
----------
im : ND-array
The image into which the sub-image will be inserted
element : ND-array
... | 1.903284 | 1.911039 | 0.995942 |
r
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
if sp.size(shape) == 2:
shape = sp.hstack((shape, [1]))
temp = sp.zeros(shape=shape[:2])
Xi = sp.ceil(sp.linspace(spacing/2,
shape[0]-(spacing/2)-1,
... | def bundle_of_tubes(shape: List[int], spacing: int) | r"""
Create a 3D image of a bundle of tubes, in the form of a rectangular
plate with randomly sized holes through it.
Parameters
----------
shape : list
The size the image, with the 3rd dimension indicating the plate
thickness. If the 3rd dimension is not given then a thickness of
... | 2.515056 | 2.537033 | 0.991337 |
r
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
Rs = dist.interval(sp.linspace(0.05, 0.95, nbins))
Rs = sp.vstack(Rs).T
Rs = (Rs[:-1] + Rs[1:])/2
Rs = sp.clip(Rs.flatten(), a_min=r_min, a_max=None)
phi_desired = 1 - (1 - porosity)/(len(Rs))
... | def polydisperse_spheres(shape: List[int], porosity: float, dist,
nbins: int = 5, r_min: int = 5) | r"""
Create an image of randomly place, overlapping spheres with a distribution
of radii.
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where Ni is the
number of voxels in each direction. If shape is only 2D, then an
image of polydispe... | 4.044414 | 4.074635 | 0.992583 |
r
print(78*'―')
print('voronoi_edges: Generating', ncells, 'cells')
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
im = sp.zeros(shape, dtype=bool)
base_pts = sp.rand(ncells, 3)*shape
if flat_faces:
# Reflect base points
Nx, Ny,... | def voronoi_edges(shape: List[int], radius: int, ncells: int,
flat_faces: bool = True) | r"""
Create an image of the edges in a Voronoi tessellation
Parameters
----------
shape : array_like
The size of the image to generate in [Nx, Ny, Nz] where Ni is the
number of voxels in each direction.
radius : scalar
The radius to which Voronoi edges should be dilated in ... | 2.614955 | 2.552265 | 1.024562 |
r
edges = [[], []]
for facet in vor.ridge_vertices:
# Create a closed cycle of vertices that define the facet
edges[0].extend(facet[:-1]+[facet[-1]])
edges[1].extend(facet[1:]+[facet[0]])
edges = sp.vstack(edges).T # Convert to scipy-friendly format
mask = sp.any(edges == -1... | def _get_Voronoi_edges(vor) | r"""
Given a Voronoi object as produced by the scipy.spatial.Voronoi class,
this function calculates the start and end points of eeach edge in the
Voronoi diagram, in terms of the vertex indices used by the received
Voronoi object.
Parameters
----------
vor : scipy.spatial.Voronoi object
... | 3.54039 | 3.951932 | 0.895863 |
r
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
ndim = (shape != 1).sum()
s_vol = ps_disk(radius).sum() if ndim == 2 else ps_ball(radius).sum()
bulk_vol = sp.prod(shape)
N = int(sp.ceil((1 - porosity)*bulk_vol/s_vol))
im = sp.random.random(si... | def overlapping_spheres(shape: List[int], radius: int, porosity: float,
iter_max: int = 10, tol: float = 0.01) | r"""
Generate a packing of overlapping mono-disperse spheres
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where Ni is the
number of voxels in the i-th direction.
radius : scalar
The radius of spheres in the packing.
porosity : sc... | 4.355009 | 4.320169 | 1.008065 |
r
try:
import noise
except ModuleNotFoundError:
raise Exception("The noise package must be installed")
shape = sp.array(shape)
if sp.size(shape) == 1:
Lx, Ly, Lz = sp.full((3, ), int(shape))
elif len(shape) == 2:
Lx, Ly = shape
Lz = 1
elif len(shape) =... | def generate_noise(shape: List[int], porosity=None, octaves: int = 3,
frequency: int = 32, mode: str = 'simplex') | r"""
Generate a field of spatially correlated random noise using the Perlin
noise algorithm, or the updated Simplex noise algorithm.
Parameters
----------
shape : array_like
The size of the image to generate in [Nx, Ny, Nz] where N is the
number of voxels.
porosity : float
... | 2.511693 | 2.270801 | 1.106083 |
blobiness = sp.array(blobiness)
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
sigma = sp.mean(shape)/(40*blobiness)
im = sp.random.random(shape)
im = spim.gaussian_filter(im, sigma=sigma)
im = norm_to_uniform(im, scale=[0, 1])
if porosity... | def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1) | Generates an image containing amorphous blobs
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where N is the
number of voxels
porosity : float
If specified, this will threshold the image to the specified value
prior to returning. If... | 4.909578 | 4.765621 | 1.030208 |
r
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
elif sp.size(shape) == 2:
raise Exception("2D cylinders don't make sense")
R = sp.sqrt(sp.sum(sp.square(shape))).astype(int)
im = sp.zeros(shape)
# Adjust max angles to be between 0 and 90
... | def cylinders(shape: List[int], radius: int, ncylinders: int,
phi_max: float = 0, theta_max: float = 90) | r"""
Generates a binary image of overlapping cylinders. This is a good
approximation of a fibrous mat.
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where N is the
number of voxels. 2D images are not permitted.
radius : scalar
The ... | 2.685014 | 2.739018 | 0.980284 |
r
X0 = sp.around(X0).astype(int)
X1 = sp.around(X1).astype(int)
if len(X0) == 3:
L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]], [X1[2]-X0[2]]])) + 1
x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)
y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)
z = sp.... | def line_segment(X0, X1) | r"""
Calculate the voxel coordinates of a straight line between the two given
end points
Parameters
----------
X0 and X1 : array_like
The [x, y] or [x, y, z] coordinates of the start and end points of
the line.
Returns
-------
coords : list of lists
A list of li... | 1.606739 | 1.629899 | 0.985791 |
r
elem = strel.copy()
x_dim, y_dim = im.shape
x_min = x-r
x_max = x+r+1
y_min = y-r
y_max = y+r+1
if x_min < 0:
x_adj = -x_min
elem = elem[x_adj:, :]
x_min = 0
elif x_max > x_dim:
x_adj = x_max - x_dim
elem = elem[:-x_adj, :]
if y_min < 0:
... | def _fit_strel_to_im_2d(im, strel, r, x, y) | r"""
Helper function to add a structuring element to a 2D image.
Used by RSA. Makes sure if center is less than r pixels from edge of image
that the strel is sliced to fit. | 1.756916 | 1.650097 | 1.064735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.