text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_immutable(self):
'''
Prevents any future changes to the object
'''
self._bytes = bytes(self._bytes)
self.__immutable = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find(self, substring):
'''
byte-like -> int
Finds the index of substring
'''
if isinstance(substring, ByteData):
substring = substring.to_bytes()
return self._bytes.find(substring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_bytes(VarInt, byte_string):
'''
byte-like -> VarInt
accepts arbitrary length input, gets a VarInt off the front
'''
num = byte_string
if num[0] <= 0xfc:
num = num[0:1]
non_compact = False
elif num[0] == 0xfd:
num = num[1:3]
non_compact = (num[-1:] == b'\x00')
elif num[0] == 0xfe:
num = num[1:5]
non_compact = (num[-2:] == b'\x00\x00')
elif num[0] == 0xff:
num = num[1:9]
non_compact = (num[-4:] == b'\x00\x00\x00\x00')
if len(num) not in [1, 2, 4, 8]:
raise ValueError('Malformed VarInt. Got: {}'
.format(byte_string.hex()))
if (non_compact
and ('overwinter' in riemann.get_current_network_name()
or 'sapling' in riemann.get_current_network_name())):
raise ValueError('VarInt must be compact. Got: {}'
.format(byte_string.hex()))
ret = VarInt(
utils.le2i(num),
length=len(num) + 1 if non_compact else 0)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def copy(self, tx_ins=None, tx_outs=None, lock_time=None,
expiry_height=None, value_balance=None, tx_shielded_spends=None,
tx_shielded_outputs=None, tx_joinsplits=None,
joinsplit_pubkey=None, joinsplit_sig=None, binding_sig=None):
'''
SaplingTx, ... -> SaplingTx
Makes a copy. Allows over-writing specific pieces.
'''
return SaplingTx(
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_time if lock_time is not None
else self.lock_time),
expiry_height=(expiry_height if expiry_height is not None
else self.expiry_height),
value_balance=(value_balance if value_balance is not None
else self.value_balance),
tx_shielded_spends=(
tx_shielded_spends if tx_shielded_spends is not None
else self.tx_shielded_spends),
tx_shielded_outputs=(
tx_shielded_outputs if tx_shielded_outputs is not None
else self.tx_shielded_outputs),
tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None
else self.tx_joinsplits),
joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None
else self.joinsplit_pubkey),
joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None
else self.joinsplit_sig),
binding_sig=(binding_sig if binding_sig is not None
else self.binding_sig)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(data, checksum=True):
"""Convert binary to base58 using BASE58_ALPHABET.""" |
if checksum:
data = data + utils.hash256(data)[:4]
v, prefix = to_long(256, lambda x: x, iter(data))
data = from_long(v, prefix, BASE58_BASE, lambda v: BASE58_ALPHABET[v])
return data.decode("utf8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_pkh_output_script(pubkey, witness=False):
'''
bytearray -> bytearray
'''
if witness and not riemann.network.SEGWIT:
raise ValueError(
'Network {} does not support witness scripts.'
.format(riemann.get_current_network_name()))
output_script = bytearray()
if type(pubkey) is not bytearray and type(pubkey) is not bytes:
raise ValueError('Unknown pubkey format. '
'Expected bytes. Got: {}'.format(type(pubkey)))
pubkey_hash = utils.hash160(pubkey)
if witness:
output_script.extend(riemann.network.P2WPKH_PREFIX)
output_script.extend(pubkey_hash)
else:
output_script.extend(b'\x76\xa9\x14') # OP_DUP OP_HASH160 PUSH14
output_script.extend(pubkey_hash)
output_script.extend(b'\x88\xac') # OP_EQUALVERIFY OP_CHECKSIG
return output_script |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_output(value, output_script, version=None):
'''
byte-like, byte-like -> TxOut
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredTxOut(
value=value,
version=version,
output_script=output_script)
return tx.TxOut(value=value, output_script=output_script) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_sh_output(value, output_script, witness=False):
'''
int, str -> TxOut
'''
return _make_output(
value=utils.i2le_padded(value, 8),
output_script=make_sh_output_script(output_script, witness)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_pkh_output(value, pubkey, witness=False):
'''
int, bytearray -> TxOut
'''
return _make_output(
value=utils.i2le_padded(value, 8),
output_script=make_pkh_output_script(pubkey, witness)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_outpoint(tx_id_le, index, tree=None):
'''
byte-like, int, int -> Outpoint
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredOutpoint(tx_id=tx_id_le,
index=utils.i2le_padded(index, 4),
tree=utils.i2le_padded(tree, 1))
return tx.Outpoint(tx_id=tx_id_le,
index=utils.i2le_padded(index, 4)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_script_sig(stack_script, redeem_script):
'''
str, str -> bytearray
'''
stack_script += ' {}'.format(
serialization.hex_serialize(redeem_script))
return serialization.serialize(stack_script) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_legacy_input(outpoint, stack_script, redeem_script, sequence):
'''
Outpoint, byte-like, byte-like, int -> TxIn
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredTxIn(
outpoint=outpoint,
sequence=utils.i2le_padded(sequence, 4))
return tx.TxIn(outpoint=outpoint,
stack_script=stack_script,
redeem_script=redeem_script,
sequence=utils.i2le_padded(sequence, 4)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_witness_input(outpoint, sequence):
'''
Outpoint, int -> TxIn
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredTxIn(
outpoint=outpoint,
sequence=utils.i2le_padded(sequence, 4))
return tx.TxIn(outpoint=outpoint,
stack_script=b'',
redeem_script=b'',
sequence=utils.i2le_padded(sequence, 4)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def length_prepend(byte_string):
'''
bytes -> bytes
'''
length = tx.VarInt(len(byte_string))
return length.to_bytes() + byte_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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?
'''
addr_bytes = bytearray()
if riemann.network.CASHADDR_P2SH is not None and cashaddr:
addr_bytes.extend(riemann.network.CASHADDR_P2SH)
addr_bytes.extend(script_hash)
return riemann.network.CASHADDR_ENCODER.encode(addr_bytes)
if witness:
addr_bytes.extend(riemann.network.P2WSH_PREFIX)
addr_bytes.extend(script_hash)
return riemann.network.SEGWIT_ENCODER.encode(addr_bytes)
else:
addr_bytes.extend(riemann.network.P2SH_PREFIX)
addr_bytes.extend(script_hash)
return riemann.network.LEGACY_ENCODER.encode(addr_bytes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True):
'''
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_sh_address(script_string, witness=False, cashaddr=True):
'''
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def to_output_script(address):
'''
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 (parsed.find(riemann.network.P2WSH_PREFIX) == 0
and len(parsed) == 34):
return parsed
except TypeError:
pass
try:
if (parsed.find(riemann.network.CASHADDR_P2SH) == 0
and len(parsed) == len(riemann.network.CASHADDR_P2SH) + 20):
prefix = b'\xa9\x14' # OP_HASH160 PUSH14
parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
suffix = b'\x87' # OP_EQUAL
except TypeError:
pass
try:
if (parsed.find(riemann.network.CASHADDR_P2PKH) == 0
and len(parsed) == len(riemann.network.CASHADDR_P2PKH) + 20):
prefix = b'\x76\xa9\x14' # OP_DUP OP_HASH160 PUSH14
parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
suffix = b'\x88\xac' # OP_EQUALVERIFY OP_CHECKSIG
except TypeError:
pass
if (parsed.find(riemann.network.P2PKH_PREFIX) == 0
and len(parsed) == len(riemann.network.P2PKH_PREFIX) + 20):
prefix = b'\x76\xa9\x14' # OP_DUP OP_HASH160 PUSH14
parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
suffix = b'\x88\xac' # OP_EQUALVERIFY OP_CHECKSIG
if (parsed.find(riemann.network.P2SH_PREFIX) == 0
and len(parsed) == len(riemann.network.P2SH_PREFIX) + 20):
prefix = b'\xa9\x14' # OP_HASH160 PUSH14
parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
suffix = b'\x87' # OP_EQUAL
if parsed_hash == b'':
raise ValueError('Cannot parse output script from address.')
output_script = prefix + parsed_hash + suffix
return output_script |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parse_hash(address):
'''
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):]
if raw.find(riemann.network.CASHADDR_P2PKH) == 0:
return raw[len(riemann.network.CASHADDR_P2PKH):]
except TypeError:
pass
# Segwit addresses
try:
if address.find(riemann.network.BECH32_HRP) == 0:
if raw.find(riemann.network.P2WSH_PREFIX) == 0:
return raw[len(riemann.network.P2WSH_PREFIX):]
if raw.find(riemann.network.P2WPKH_PREFIX) == 0:
return raw[len(riemann.network.P2WPKH_PREFIX):]
except TypeError:
pass
# Legacy Addresses
if raw.find(riemann.network.P2SH_PREFIX) == 0:
return raw[len(riemann.network.P2SH_PREFIX):]
if raw.find(riemann.network.P2PKH_PREFIX) == 0:
return raw[len(riemann.network.P2PKH_PREFIX):] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
n = riemann.get_current_network_name()
if 'sprout' in n:
return 1
if 'overwinter' in n:
return 3
if 'sapling' in n:
return 4
try:
script_array = redeem_script.split()
script_array.index('OP_CHECKSEQUENCEVERIFY')
return 2
except ValueError:
return 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKSEQUENCEVERIFY')
return int(script_array[loc - 1], 16)
except ValueError:
return 0xFFFFFFFE |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def output(value, address):
'''
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def outpoint(tx_id, index, tree=None):
'''
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unsigned_input(outpoint, redeem_script=None, sequence=None):
'''
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=b'',
sequence=sequence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def p2pkh_input(outpoint, sig, pubkey, sequence=0xFFFFFFFE):
'''
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def p2sh_input(outpoint, stack_script, redeem_script, sequence=None):
'''
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_ser.serialize(redeem_script)
return tb.make_legacy_input(
outpoint=outpoint,
stack_script=stack_script,
redeem_script=redeem_script,
sequence=sequence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
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_time if lock_time is not None
else self.lock_time),
expiry_height=(expiry_height if expiry_height is not None
else self.expiry_height),
tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None
else self.tx_joinsplits),
joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None
else self.joinsplit_pubkey),
joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None
else self.joinsplit_sig)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_bytes(OverwinterTx, byte_string):
'''
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 {}'
.format(b'\x03\x00\x00\x80'.hex(),
b'\x70\x82\xc4\x03'.hex(),
header.hex(),
group_id.hex()))
tx_ins = []
tx_ins_num = shared.VarInt.from_bytes(byte_string[8:])
current = 8 + len(tx_ins_num)
for _ in range(tx_ins_num.number):
tx_in = TxIn.from_bytes(byte_string[current:])
current += len(tx_in)
tx_ins.append(tx_in)
tx_outs = []
tx_outs_num = shared.VarInt.from_bytes(byte_string[current:])
current += len(tx_outs_num)
for _ in range(tx_outs_num.number):
tx_out = TxOut.from_bytes(byte_string[current:])
current += len(tx_out)
tx_outs.append(tx_out)
lock_time = byte_string[current:current + 4]
current += 4
expiry_height = byte_string[current:current + 4]
current += 4
if current == len(byte_string):
# No joinsplits
tx_joinsplits = tuple()
joinsplit_pubkey = None
joinsplit_sig = None
else:
tx_joinsplits = []
tx_joinsplits_num = shared.VarInt.from_bytes(byte_string[current:])
current += len(tx_outs_num)
for _ in range(tx_joinsplits_num.number):
tx_joinsplit = z.SproutJoinsplit.from_bytes(
byte_string[current:])
current += len(tx_joinsplit)
tx_joinsplits.append(tx_joinsplit)
joinsplit_pubkey = byte_string[current:current + 32]
current += 32
joinsplit_sig = byte_string[current:current + 64]
return OverwinterTx(
tx_ins=tx_ins,
tx_outs=tx_outs,
lock_time=lock_time,
expiry_height=expiry_height,
tx_joinsplits=tx_joinsplits,
joinsplit_pubkey=joinsplit_pubkey,
joinsplit_sig=joinsplit_sig) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx):
"""Initializes the CLI environment.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, pattern, arguments, safe):
"""Executes a saved command.""" |
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 = list(arguments)
kargs = {}
for r, p, d in zip(raw_params, params, defaults):
if arguments:
val = arguments.pop(0)
click.echo("{}: {}".format(p, val))
kargs[r] = val
elif safe:
if d:
kargs[r] = d
else:
p_default = d if d else None
val = click.prompt("Enter value for '{}'".format(p), default=p_default)
kargs[r] = val
click.echo("\n")
final_cmd = utils.substitute_pcmd(pcmd, kargs, safe)
command = "$ {} :: {}".format(final_cmd, desc)
if click.confirm("Execute\n\t{}\n\n?".format(command), default=True):
os.system(final_cmd)
elif matches == []:
click.echo('No saved commands matches the pattern {}'.format(pattern))
else:
click.echo("No commands to run, Add one by 'keep new'. ") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx):
"""Saves a new command""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, msg, *args):
"""Logs a message to stderr.""" |
if args:
msg %= args
click.echo(msg, file=sys.stderr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled.""" |
if self.verbose:
self.log(msg, *args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx):
"""Check for an update of Keep.""" |
utils.check_update(ctx, forced=True)
click.secho("Keep is at its latest version v{}".format(about.__version__), fg='green') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, pattern):
"""Searches for a saved command.""" |
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. Add one by `keep new`.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx):
"""Shows the saved commands.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, overwrite):
"""Updates the local database with remote.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx):
"""Register user over server.""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_update(ctx, forced=False):
""" Check for update on pypi. Limit to 1 check per day if not forced """ |
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_file, 'r').read()
else:
date = []
if forced or today != date:
ctx.update_checked = True
date = today
with open(update_check_file, 'w') as f:
f.write(date)
r = requests.get("https://pypi.org/pypi/keep/json").json()
version = r['info']['version']
curr_version = about.__version__
if version > curr_version:
click.secho("Keep seems to be outdated. Current version = "
"{}, Latest version = {}".format(curr_version, version) +
"\n\nPlease update with ", bold=True, fg='red')
click.secho("\tpip3 --no-cache-dir install -U keep==" + str(version), fg='green')
click.secho("\n\n") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, editor):
"""Edit saved commands.""" |
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_commands != commands:
click.echo("Replace:\n")
click.secho("\t{}".format('\n\t'.join(utils.format_commands(commands))),
fg="green")
click.echo("With:\n\t")
click.secho("\t{}".format('\n\t'.join(utils.format_commands(new_commands))),
fg="green")
if click.confirm("", default=False):
utils.write_commands(new_commands) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, pattern):
"""Deletes a saved command.""" |
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):
utils.remove_command(cmd)
click.echo('Command successfully removed!')
elif matches == []:
click.echo('No saved commands matches the pattern {}'.format(pattern))
else:
click.echo("No commands to remove, Add one by 'keep new'. ") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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 = Poly3DCollection(mesh.verts[mesh.faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)
ax.set_xlabel("x-axis")
ax.set_ylabel("y-axis")
ax.set_zlabel("z-axis")
ax.set_xlim(lim_min[0], lim_max[0])
ax.set_ylim(lim_min[1], lim_max[1])
ax.set_zlim(lim_min[2], lim_max[2])
return fig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 randomly located and sized boxes to sample. The default is 1000. Returns ------- result : named_tuple A tuple containing the *volume* and *porosity* of each subdomain tested in arrays ``npoints`` long. They can be accessed as attributes of the tuple. They can be conveniently plotted by passing the tuple to matplotlib's ``plot`` function using the \* notation: ``plt.plot(*result, 'b.')``. The resulting plot is similar to the sketch given by Bachmat and Bear [1] Notes ----- This function is frustratingly slow. Profiling indicates that all the time is spent on scipy's ``sum`` function which is needed to sum the number of void voxels (1's) in each subdomain. Also, this function is a prime target for parallelization since the ``npoints`` are calculated independenlty. References [1] Bachmat and Bear. On the Concept and Size of a Representative Elementary Volume (Rev), Advances in Transport Phenomena in Porous Media (1987) """ |
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.zeros(shape=(N,), dtype=float)
volume = sp.zeros(shape=(N,), dtype=int)
for i in tqdm(sp.arange(0, N)):
s = slices[i]
p = pads[i]
new_s = extend_slice(s, shape=im.shape, pad=p)
temp = im[new_s]
Vp = sp.sum(temp)
Vt = sp.size(temp)
porosity[i] = Vp/Vt
volume[i] = Vt
profile = namedtuple('profile', ('volume', 'porosity'))
profile.volume = volume
profile.porosity = porosity
return profile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 porosity in each YZ plane is calculated and returned as 1D array with 1 value for each X position. Returns ------- result : 1D-array A 1D-array of porosity along the specified axis """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 space (or True) and 0's indicating the solid phase (or False). Returns ------- porosity : float Calculated as the sum of all 1's divided by the sum of all 1's and 0's. See Also -------- phase_fraction Notes ----- This function assumes void is represented by 1 and solid by 0, and all other values are ignored. This is useful, for example, for images of cylindrical cores, where all voxels outside the core are labelled with 2. Alternatively, images can be processed with ``find_disconnected_voxels`` to get an image of only blind pores. This can then be added to the orignal image such that blind pores have a value of 2, thus allowing the calculation of accessible porosity, rather than overall porosity. """ |
im = sp.array(im, dtype=int)
Vp = sp.sum(im == 1)
Vs = sp.sum(im == 0)
e = Vp/(Vs + Vp)
return e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 autocorrelation produced by FFT r_max : int or float The maximum radius in pixels to sum the image over Returns ------- result : named_tuple A named tupling containing an array of ``bins`` of radial position and an array of ``counts`` in each bin. """ |
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) - adj/2
dt = sp.sqrt(inds[0]**2 + inds[1]**2 + inds[2]**2)
else:
raise Exception('Image dimensions must be 2 or 3')
bin_size = np.int(np.ceil(r_max/nbins))
bins = np.arange(bin_size, r_max, step=bin_size)
radial_sum = np.zeros_like(bins)
for i, r in enumerate(bins):
# Generate Radial Mask from dt using bins
mask = (dt <= r) * (dt > (r-bin_size))
radial_sum[i] = np.sum(autocorr[mask])/np.sum(mask)
# Return normalized bin and radially summed autoc
norm_autoc_radial = radial_sum/np.max(autocorr)
tpcf = namedtuple('two_point_correlation_function',
('distance', 'probability'))
return tpcf(bins, norm_autoc_radial) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 two-point correlation function, using the *args feature of matplotlib's plot function. The x array is the distances between points and the y array is corresponding probabilities that points of a given distance both lie in the void space. Notes ----- The fourier transform approach utilizes the fact that the autocorrelation function is the inverse FT of the power spectrum density. For background read the Scipy fftpack docs and for a good explanation see: http://www.ucl.ac.uk/~ucapikr/projects/KamilaSuankulova_BSc_Project.pdf """ |
# 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.absolute(sp_ft.ifftshift(sp_ft.ifftn(sp_ft.fftshift(P))))
tpcf = _radial_profile(autoc, r_max=np.min(hls))
return tpcf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ``local_thickness``. bins : scalar or array_like Either an array of bin sizes to use, or the number of bins that should be automatically generated that span the data range. log : boolean If ``True`` (default) the size data is converted to log (base-10) values before processing. This can help voxel_size : scalar The size of a voxel side in preferred units. The default is 1, so the user can apply the scaling to the returned results after the fact. Returns ------- result : named_tuple A named-tuple containing several values: *R* or *logR* - radius, equivalent to ``bin_centers`` *pdf* - probability density function *cdf* - cumulative density function *satn* - phase saturation in differential form. For the cumulative saturation, just use *cfd* which is already normalized to 1. *bin_centers* - the center point of each bin *bin_edges* - locations of bin divisions, including 1 more value than the number of bins *bin_widths* - useful for passing to the ``width`` argument of ``matplotlib.pyplot.bar`` Notes ----- (1) To ensure the returned values represent actual sizes be sure to scale the distance transform by the voxel size first (``dt *= voxel_size``) plt.bar(psd.R, psd.satn, width=psd.bin_widths, edgecolor='k') """ |
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', 'bin_edges', 'bin_widths'))
return psd(h.bin_centers, h.pdf, h.cdf, h.relfreq,
h.bin_centers, h.bin_edges, h.bin_widths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, containing its length. Notes ---- The returned array can be passed to ``plt.hist`` to plot the histogram, or to ``sp.histogram`` to get the histogram data directly. Another useful function is ``sp.bincount`` which gives the number of chords of each length in a format suitable for ``plt.plot``. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 be identified using ``scipy.ndimage.label``, or numerical values in which case it is assumed that chords have already been identifed and labeled. In both cases, the size of each chord will be computed as the number of voxels belonging to each labelled region. bins : scalar or array_like If a scalar is given it is interpreted as the number of bins to use, and if an array is given they are used as the bins directly. log : Boolean If true, the logarithm of the chord lengths will be used, which can make the data more clear. normalization : string Indicates how to normalize the bin heights. Options are: *'count' or 'number'* - (default) This simply counts the number of chords in each bin in the normal sense of a histogram. This is the rigorous definition according to Torquato [1]. *'length'* - This multiplies the number of chords in each bin by the chord length (i.e. bin size). The normalization scheme accounts for the fact that long chords are less frequent than shorert chords, thus giving a more balanced distribution. voxel_size : scalar The size of a voxel side in preferred units. The default is 1, so the user can apply the scaling to the returned results after the fact. Returns ------- result : named_tuple A tuple containing the following elements, which can be retrieved by attribute name: *L* or *logL* - chord length, equivalent to ``bin_centers`` *pdf* - probability density function *cdf* - cumulative density function *relfreq* - relative frequency chords in each bin. The sum of all bin heights is 1.0. For the cumulative relativce, use *cdf* which is already normalized to 1. *bin_centers* - the center point of each bin *bin_edges* - locations of bin divisions, including 1 more value than the number of bins *bin_widths* - useful for passing to the ``width`` argument of ``matplotlib.pyplot.bar`` References [1] Torquato, S. Random Heterogeneous Materials: Mircostructure and Macroscopic Properties. Springer, New York (2002) - See page 45 & 292 """ |
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 heigths by length
h[0] = h[0]/h[0].sum()/(h[1][1:]-h[1][:-1]) # Normalize h[0] manually
elif normalization in ['number', 'count']:
h = sp.histogram(x, bins=bins, density=True)
else:
raise Exception('Unsupported normalization:', normalization)
h = _parse_histogram(h)
cld = namedtuple('chord_length_distribution',
(log*'log' + 'L', 'pdf', 'cdf', 'relfreq',
'bin_centers', 'bin_edges', 'bin_widths'))
return cld(h.bin_centers, h.pdf, h.cdf, h.relfreq,
h.bin_centers, h.bin_edges, h.bin_widths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_like A list containing the areas of each regions, as determined by ``region_surface_area``. Note that the region number and list index are offset by 1, such that the area for region 1 is stored in ``areas[0]``. voxel_size : scalar The resolution of the image, expressed as the length of one side of a voxel, so the volume of a voxel would be **voxel_size**-cubed. The default is 1. strel : array_like The structuring element used to blur the region. If not provided, then a spherical element (or disk) with radius 1 is used. See the docstring for ``mesh_region`` for more details, as this argument is passed to there. Returns ------- result : named_tuple A named-tuple containing 2 arrays. ``conns`` holds the connectivity information and ``area`` holds the result for each pair. ``conns`` is a N-regions by 2 array with each row containing the region number of an adjacent pair of regions. For instance, if ``conns[0, 0]`` is 0 and ``conns[0, 1]`` is 5, then row 0 of ``area`` contains the interfacial area shared by regions 0 and 5. """ |
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 dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if im.ndim == 2:
cube = square
ball = disk
# Get 'slices' into im for each region
slices = spim.find_objects(im)
# Initialize arrays
Ps = sp.arange(1, sp.amax(im)+1)
sa = sp.zeros_like(Ps, dtype=float)
sa_combined = [] # Difficult to preallocate since number of conns unknown
cn = []
# Start extracting area from im
for i in tqdm(Ps):
reg = i - 1
if slices[reg] is not None:
s = extend_slice(slices[reg], im.shape)
sub_im = im[s]
mask_im = sub_im == i
sa[reg] = areas[reg]
im_w_throats = spim.binary_dilation(input=mask_im,
structure=ball(1))
im_w_throats = im_w_throats*sub_im
Pn = sp.unique(im_w_throats)[1:] - 1
for j in Pn:
if j > reg:
cn.append([reg, j])
merged_region = im[(min(slices[reg][0].start,
slices[j][0].start)):
max(slices[reg][0].stop,
slices[j][0].stop),
(min(slices[reg][1].start,
slices[j][1].start)):
max(slices[reg][1].stop,
slices[j][1].stop)]
merged_region = ((merged_region == reg + 1) +
(merged_region == j + 1))
mesh = mesh_region(region=merged_region, strel=strel)
sa_combined.append(mesh_surface_area(mesh))
# Interfacial area calculation
cn = sp.array(cn)
ia = 0.5 * (sa[cn[:, 0]] + sa[cn[:, 1]] - sa_combined)
ia[ia <= 0] = 1
result = namedtuple('interfacial_areas', ('conns', 'area'))
result.conns = cn
result.area = ia * voxel_size**2
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 in the image will not be considered for area calculation. voxel_size : scalar The resolution of the image, expressed as the length of one side of a voxel, so the volume of a voxel would be **voxel_size**-cubed. The default is 1. strel : array_like The structuring element used to blur the region. If not provided, then a spherical element (or disk) with radius 1 is used. See the docstring for ``mesh_region`` for more details, as this argument is passed to there. Returns ------- result : list A list containing the surface area of each region, offset by 1, such that the surface area of region 1 is stored in element 0 of the list. """ |
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 area from im
for i in tqdm(Ps):
reg = i - 1
if slices[reg] is not None:
s = extend_slice(slices[reg], im.shape)
sub_im = im[s]
mask_im = sub_im == i
mesh = mesh_region(region=mask_im, strel=strel)
sa[reg] = mesh_surface_area(mesh)
result = sa * voxel_size**2
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 elements in ``verts`` form a mesh element. Returns ------- surface_area : float The surface area of the mesh, calculated by ``skimage.measure.mesh_surface_area`` Notes ----- This function simply calls ``scikit-image.measure.mesh_surface_area``, but it allows for the passing of the ``mesh`` tuple returned by the ``mesh_region`` function, entirely for convenience. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.imshow``. """ |
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_xz.shape[1] + 10
new_im = sp.zeros([new_x + 20, new_y + 20], dtype=im.dtype)
# Add xy image to upper left corner
new_im[10:im_xy.shape[0]+10,
10:im_xy.shape[1]+10] = im_xy
# Add xz image to lower left coner
x_off = im_xy.shape[0]+20
y_off = im_xy.shape[1]+20
new_im[10:10 + im_xz.shape[0],
y_off:y_off + im_xz.shape[1]] = im_xz
new_im[x_off:x_off + im_yz.shape[0],
10:10 + im_yz.shape[1]] = im_yz
return new_im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 marked as 1 or True direction : string Specify the axis along which the camera will point. Options are 'X', 'Y', and 'Z'. Returns ------- image : 2D-array A 2D greyscale image suitable for use in matplotlib\'s ```imshow``` function. """ |
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)
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ND-image of the porous material with the solid phase marked as 1 or True direction : string Specify the axis along which the camera will point. Options are 'X', 'Y', and 'Z'. Returns ------- image : 2D-array A 2D greyscale image suitable for use in matplotlib\'s ```imshow``` function. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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``. Because ``regionprops_3D`` returns data in the same ``list`` format as the ``regionprops`` function in **Skimage** you can pass in either. Returns ------- DataFrame : Pandas DataFrame A Pandas DataFrame with each region corresponding to a row and each column corresponding to a key metric. All the values for a given property (e.g. 'sphericity') can be obtained as ``val = df['sphericity']``. Conversely, all the key metrics for a given region can be found with ``df.iloc[1]``. See Also -------- props_to_image regionprops_3d """ |
# 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)
except (TypeError, NotImplementedError, AttributeError):
pass
# Create a dictionary of all metrics that are simple scalar propertie
d = {}
for k in metrics:
try:
d[k] = sp.array([r[k] for r in regionprops])
except ValueError:
print('Error encountered evaluating ' + k + ' so skipping it')
# Create pandas data frame an return
df = DataFrame(d)
return df |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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``. shape : array_like The shape of the original image for which ``regionprops`` was obtained. prop : string The region property of interest. Can be a scalar item such as 'volume' in which case the the regions will be colored by their respective volumes, or can be an image-type property such as 'border' or 'convex_image', which will return an image composed of the sub-images. Returns ------- image : ND-array An ND-image the same size as the original image, with each region represented by the values specified in ``prop``. See Also -------- props_to_DataFrame regionprops_3d """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regionprops_3D(im):
r""" Calculates various metrics for each labeled region in a 3D image. The ``regionsprops`` method in **skimage** is very thorough for 2D images, but is a bit limited when it comes to 3D images, so this function aims to fill this gap. Parameters im : array_like An imaging containing at least one labeled region. If a boolean image is received than the ``True`` voxels are treated as a single region labeled ``1``. Regions labeled 0 are ignored in all cases. Returns ------- props : list An augmented version of the list returned by skimage's ``regionprops``. Information, such as ``volume``, can be found for region A using the following syntax: ``result[A-1].volume``. The returned list contains all the metrics normally returned by **skimage.measure.regionprops** plus the following: 'slice': Slice indices into the image that can be used to extract the region 'volume': Volume of the region in number of voxels. 'bbox_volume': Volume of the bounding box that contains the region. 'border': The edges of the region, found as the locations where the distance transform is 1. 'inscribed_sphere': An image containing the largest sphere can can fit entirely inside the region. 'surface_mesh_vertices': Obtained by applying the marching cubes algorithm on the region, AFTER first blurring the voxel image. This allows marching cubes more freedom to fit the surface contours. See also ``surface_mesh_simplices`` 'surface_mesh_simplices': This accompanies ``surface_mesh_vertices`` and together they can be used to define the region as a mesh. 'surface_area': Calculated using the mesh obtained as described above, using the ``porespy.metrics.mesh_surface_area`` method. 'sphericity': Defined as the ratio of the area of a sphere with the same volume as the region to the actual surface area of the region. 'skeleton': The medial axis of the region obtained using the ``skeletonize_3D`` method from **skimage**. 'convex_volume': Same as convex_area, but translated to a more meaningful name. See Also -------- snow_partitioning Notes ----- This function may seem slow compared to the skimage version, but that is because they defer calculation of certain properties until they are accessed, while this one evalulates everything (inlcuding the deferred properties from skimage's ``regionprops``) Regions can be identified using a watershed algorithm, which can be a bit tricky to obtain desired results. *PoreSpy* includes the SNOW algorithm, which may be helpful. """ |
print('_'*60)
print('Calculating regionprops')
results = regionprops(im, coordinates='xy')
for i in tqdm(range(len(results))):
mask = results[i].image
mask_padded = sp.pad(mask, pad_width=1, mode='constant')
temp = spim.distance_transform_edt(mask_padded)
dt = extract_subsection(temp, shape=mask.shape)
# ---------------------------------------------------------------------
# Slice indices
results[i].slice = results[i]._slice
# ---------------------------------------------------------------------
# Volume of regions in voxels
results[i].volume = results[i].area
# ---------------------------------------------------------------------
# Volume of bounding box, in voxels
results[i].bbox_volume = sp.prod(mask.shape)
# ---------------------------------------------------------------------
# Create an image of the border
results[i].border = dt == 1
# ---------------------------------------------------------------------
# Create an image of the maximal inscribed sphere
r = dt.max()
inv_dt = spim.distance_transform_edt(dt < r)
results[i].inscribed_sphere = inv_dt < r
# ---------------------------------------------------------------------
# Find surface area using marching cubes and analyze the mesh
tmp = sp.pad(sp.atleast_3d(mask), pad_width=1, mode='constant')
tmp = spim.convolve(tmp, weights=ball(1))/5
verts, faces, norms, vals = marching_cubes_lewiner(volume=tmp, level=0)
results[i].surface_mesh_vertices = verts
results[i].surface_mesh_simplices = faces
area = mesh_surface_area(verts, faces)
results[i].surface_area = area
# ---------------------------------------------------------------------
# Find sphericity
vol = results[i].volume
r = (3/4/sp.pi*vol)**(1/3)
a_equiv = 4*sp.pi*(r)**2
a_region = results[i].surface_area
results[i].sphericity = a_equiv/a_region
# ---------------------------------------------------------------------
# Find skeleton of region
results[i].skeleton = skeletonize_3d(mask)
# ---------------------------------------------------------------------
# Volume of convex image, equal to area in 2D, so just translating
results[i].convex_volume = results[i].convex_area
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snow_n(im, voxel_size=1, boundary_faces=['top', 'bottom', 'left', 'right', 'front', 'back'], marching_cubes_area=False, alias=None):
r""" Analyzes an image that has been segemented into N phases and extracts all a network for each of the N phases, including geometerical information as well as network connectivity between each phase. Parameters im : ND-array Image of porous material where each phase is represented by unique integer. Phase integer should start from 1 (0 is ignored) voxel_size : scalar The resolution of the image, expressed as the length of one side of a voxel, so the volume of a voxel would be **voxel_size**-cubed. The default is 1, which is useful when overlaying the PNM on the original image since the scale of the image is always 1 unit lenth per voxel. boundary_faces : list of strings Boundary faces labels are provided to assign hypothetical boundary nodes having zero resistance to transport process. For cubical geometry, the user can choose ‘left’, ‘right’, ‘top’, ‘bottom’, ‘front’ and ‘back’ face labels to assign boundary nodes. If no label is assigned then all six faces will be selected as boundary nodes automatically which can be trimmed later on based on user requirements. marching_cubes_area : bool If ``True`` then the surface area and interfacial area between regions will be calculated using the marching cube algorithm. This is a more accurate representation of area in extracted network, but is quite slow, so it is ``False`` by default. The default method simply counts voxels so does not correctly account for the voxelated nature of the images. alias : dict (Optional) A dictionary that assigns unique image label to specific phases. For example {1: 'Solid'} will show all structural properties associated with label 1 as Solid phase properties. If ``None`` then default labelling will be used i.e {1: 'Phase1',..}. Returns ------- A dictionary containing all N phases size data, as well as the network topological information. The dictionary names use the OpenPNM convention (i.e. 'pore.coords', 'throat.conns') so it may be converted directly to an OpenPNM network object using the ``update`` command. """ |
# -------------------------------------------------------------------------
# Get alias if provided by user
al = _create_alias_map(im, alias=alias)
# -------------------------------------------------------------------------
# Perform snow on each phase and merge all segmentation and dt together
snow = snow_partitioning_n(im, r_max=4, sigma=0.4, return_all=True,
mask=True, randomize=False, alias=al)
# -------------------------------------------------------------------------
# Add boundary regions
f = boundary_faces
regions = add_boundary_regions(regions=snow.regions, faces=f)
# -------------------------------------------------------------------------
# Padding distance transform to extract geometrical properties
dt = pad_faces(im=snow.dt, faces=f)
# -------------------------------------------------------------------------
# For only one phase extraction with boundary regions
phases_num = sp.unique(im).astype(int)
phases_num = sp.trim_zeros(phases_num)
if len(phases_num) == 1:
if f is not None:
snow.im = pad_faces(im=snow.im, faces=f)
regions = regions * (snow.im.astype(bool))
regions = make_contiguous(regions)
# -------------------------------------------------------------------------
# Extract N phases sites and bond information from image
net = regions_to_network(im=regions, dt=dt, voxel_size=voxel_size)
# -------------------------------------------------------------------------
# Extract marching cube surface area and interfacial area of regions
if marching_cubes_area:
areas = region_surface_areas(regions=regions)
interface_area = region_interface_areas(regions=regions, areas=areas,
voxel_size=voxel_size)
net['pore.surface_area'] = areas * voxel_size ** 2
net['throat.area'] = interface_area.area
# -------------------------------------------------------------------------
# Find interconnection and interfacial area between ith and jth phases
net = add_phase_interconnections(net=net, snow_partitioning_n=snow,
marching_cubes_area=marching_cubes_area,
alias=al)
# -------------------------------------------------------------------------
# label boundary cells
net = label_boundary_cells(network=net, boundary_faces=f)
# -------------------------------------------------------------------------
temp = _net_dict(net)
temp.im = im.copy()
temp.dt = dt
temp.regions = regions
return temp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 : string Path to output file voxel_size : int The side length of the voxels (voxels are cubic) origin : float data origin (according to selected voxel size) Notes ----- Outputs a vtk, vtp or vti file that can opened in ParaView """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 file, which will have `.net` file extension. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 for large data sets to be imaged without loss of information downsample : bool very large images acan be downsampled to half the size in each dimension, this doubles the effective voxel size voxel_size : int The side length of the voxels (voxels are cubic) vox : bool For an image that is binary (1's and 0's) this reduces the file size by using int8 format (can also be used to reduce file size when accuracy is not necessary ie: just visulization) Notes ----- Outputs a vtk, vtp or vti file that can opened in paraview """ |
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:]
imageToVTK(path+'1', cellData={'im': np.ascontiguousarray(im1)},
spacing=(vs, vs, vs))
imageToVTK(path+'2', origin=(0.0, 0.0, split*vs),
cellData={'im': np.ascontiguousarray(im2)},
spacing=(vs, vs, vs))
elif downsample:
im = spim.interpolation.zoom(im, zoom=0.5, order=0, mode='reflect')
imageToVTK(path, cellData={'im': np.ascontiguousarray(im)},
spacing=(2*vs, 2*vs, 2*vs))
else:
imageToVTK(path, cellData={'im': np.ascontiguousarray(im)},
spacing=(vs, vs, vs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 image of the porous material filename : string Path to output file solid : int The value of the solid voxels in the image used to convert image to binary with all other voxels assumed to be fluid. Notes ----- File produced contains 3 values: 2 = Solid, 1 = Interface, 0 = Pore Palabos will run the simulation applying the specified pressure drop from x = 0 to x = -1. """ |
# 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_im)
dt[dt > np.sqrt(2)] = 2
dt[(dt > 0)*(dt <= np.sqrt(2))] = 1
dt = dt.astype(int)
# Write out data
with open(filename, 'w') as f:
out_data = dt.flatten().tolist()
f.write('\n'.join(map(repr, out_data))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 direction along which the distance should be measured, the default is 0 (i.e. along the x-direction) mode : string Controls how the distance is measured. Options are: 'forward' - Distances are measured in the increasing direction along the specified axis 'reverse' - Distances are measured in the reverse direction. *'backward'* is also accepted. 'both' - Distances are calculated in both directions (by recursively calling itself), then reporting the minimum value of the two results. Returns ------- image : ND-array A copy of ``im`` with each foreground voxel containing the distance to the nearest background along the specified axis. """ |
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)
im = distance_transform_lin(im=im, axis=axis, mode='forward')
im = sp.flip(im, axis)
return im
elif mode in ['both']:
im_f = distance_transform_lin(im=im, axis=axis, mode='forward')
im_b = distance_transform_lin(im=im, axis=axis, mode='backward')
return sp.minimum(im_f, im_b)
else:
b = sp.cumsum(im > 0, axis=axis)
c = sp.diff(b*(im == 0), axis=axis)
d = sp.minimum.accumulate(c, axis=axis)
if im.ndim == 1:
e = sp.pad(d, pad_width=[1, 0], mode='constant', constant_values=0)
elif im.ndim == 2:
ax = [[[1, 0], [0, 0]], [[0, 0], [1, 0]]]
e = sp.pad(d, pad_width=ax[axis], mode='constant', constant_values=0)
elif im.ndim == 3:
ax = [[[1, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [0, 0]],
[[0, 0], [0, 0], [1, 0]]]
e = sp.pad(d, pad_width=ax[axis], mode='constant', constant_values=0)
f = im*(b + e)
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snow_partitioning(im, dt=None, r_max=4, sigma=0.4, return_all=False, mask=True, randomize=True):
r""" Partitions the void space into pore regions using a marker-based watershed algorithm, with specially filtered peaks as markers. The SNOW network extraction algorithm (Sub-Network of an Over-segmented Watershed) was designed to handle to perculiarities of high porosity materials, but it applies well to other materials as well. Parameters im : array_like A boolean image of the domain, with ``True`` indicating the pore space and ``False`` elsewhere. dt : array_like, optional The distance transform of the pore space. This is done automatically if not provided, but if the distance transform has already been computed then supplying it can save some time. r_max : int The radius of the spherical structuring element to use in the Maximum filter stage that is used to find peaks. The default is 4 sigma : float The standard deviation of the Gaussian filter used in step 1. The default is 0.4. If 0 is given then the filter is not applied, which is useful if a distance transform is supplied as the ``im`` argument that has already been processed. return_all : boolean If set to ``True`` a named tuple is returned containing the original image, the distance transform, the filtered peaks, and the final pore regions. The default is ``False`` mask : boolean Apply a mask to the regions where the solid phase is. Default is ``True`` randomize : boolean If ``True`` (default), then the region colors will be randomized before returning. This is helpful for visualizing otherwise neighboring regions have simlar coloring are are hard to distinguish. Returns ------- image : ND-array An image the same shape as ``im`` with the void space partitioned into pores using a marker based watershed with the peaks found by the SNOW algorithm [1]. Notes ----- If ``return_all`` is ``True`` then a **named tuple** is returned containing all of the images used during the process. They can be access as attriutes with the following names: * ``im``: The binary image of the void space * ``dt``: The distance transform of the image * ``peaks``: The peaks of the distance transform after applying the steps of the SNOW algorithm * ``regions``: The void space partitioned into pores using a marker based watershed with the peaks found by the SNOW algorithm References [1] Gostick, J. "A versatile and efficient network extraction algorithm using marker-based watershed segmenation". Physical Review E. (2017) """ |
tup = namedtuple('results', field_names=['im', 'dt', 'peaks', 'regions'])
print('_'*60)
print("Beginning SNOW Algorithm")
im_shape = sp.array(im.shape)
if im.dtype is not bool:
print('Converting supplied image (im) to boolean')
im = im > 0
if dt is None:
print('Peforming Distance Transform')
if sp.any(im_shape == 1):
ax = sp.where(im_shape == 1)[0][0]
dt = spim.distance_transform_edt(input=im.squeeze())
dt = sp.expand_dims(dt, ax)
else:
dt = spim.distance_transform_edt(input=im)
tup.im = im
tup.dt = dt
if sigma > 0:
print('Applying Gaussian blur with sigma =', str(sigma))
dt = spim.gaussian_filter(input=dt, sigma=sigma)
peaks = find_peaks(dt=dt, r_max=r_max)
print('Initial number of peaks: ', spim.label(peaks)[1])
peaks = trim_saddle_points(peaks=peaks, dt=dt, max_iters=500)
print('Peaks after trimming saddle points: ', spim.label(peaks)[1])
peaks = trim_nearby_peaks(peaks=peaks, dt=dt)
peaks, N = spim.label(peaks)
print('Peaks after trimming nearby peaks: ', N)
tup.peaks = peaks
if mask:
mask_solid = im > 0
else:
mask_solid = None
regions = watershed(image=-dt, markers=peaks, mask=mask_solid)
if randomize:
regions = randomize_colors(regions)
if return_all:
tup.regions = regions
return tup
else:
return regions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snow_partitioning_n(im, r_max=4, sigma=0.4, return_all=True, mask=True, randomize=False, alias=None):
r""" This function partitions an imaging oontain an arbitrary number of phases into regions using a marker-based watershed segmentation. Its an extension of snow_partitioning function with all phases partitioned together. Parameters im : ND-array Image of porous material where each phase is represented by unique integer starting from 1 (0's are ignored). r_max : scalar The radius of the spherical structuring element to use in the Maximum filter stage that is used to find peaks. The default is 4. sigma : scalar The standard deviation of the Gaussian filter used. The default is 0.4. If 0 is given then the filter is not applied, which is useful if a distance transform is supplied as the ``im`` argument that has already been processed. return_all : boolean (default is False) If set to ``True`` a named tuple is returned containing the original image, the combined distance transform, list of each phase max label, and the final combined regions of all phases. mask : boolean (default is True) Apply a mask to the regions which are not under concern. randomize : boolean If ``True`` (default), then the region colors will be randomized before returning. This is helpful for visualizing otherwise neighboring regions have similar coloring and are hard to distinguish. alias : dict (Optional) A dictionary that assigns unique image label to specific phases. For example {1: 'Solid'} will show all structural properties associated with label 1 as Solid phase properties. If ``None`` then default labelling will be used i.e {1: 'Phase1',..}. Returns ------- An image the same shape as ``im`` with the all phases partitioned into regions using a marker based watershed with the peaks found by the SNOW algorithm [1]. If ``return_all`` is ``True`` then a **named tuple** is returned with the following attribute: * ``im`` : The actual image of the porous material * ``dt`` : The combined distance transform of the image * ``phase_max_label`` : The list of max label of each phase in order to distinguish between each other * ``regions`` : The partitioned regions of n phases using a marker based watershed with the peaks found by the SNOW algorithm References [1] Gostick, J. "A versatile and efficient network extraction algorithm using marker-based watershed segmentation". Physical Review E. (2017) [2] Khan, ZA et al. "Dual network extraction algorithm to investigate multiple transport processes in porous materials: Image-based modeling of pore and grain-scale processes". Computers in Chemical Engineering. (2019) See Also snow_partitioning Notes ----- In principle it is possible to perform a distance transform on each phase separately, merge these into a single image, then apply the watershed only once. This, however, has been found to create edge artifacts between regions arising from the way watershed handles plateaus in the distance transform. To overcome this, this function applies the watershed to each of the distance transforms separately, then merges the segmented regions back into a single image. """ |
# Get alias if provided by user
al = _create_alias_map(im=im, alias=alias)
# Perform snow on each phase and merge all segmentation and dt together
phases_num = sp.unique(im * 1)
phases_num = sp.trim_zeros(phases_num)
combined_dt = 0
combined_region = 0
num = [0]
for i in phases_num:
print('_' * 60)
if alias is None:
print('Processing Phase {}'.format(i))
else:
print('Processing Phase {}'.format(al[i]))
phase_snow = snow_partitioning(im == i,
dt=None, r_max=r_max, sigma=sigma,
return_all=return_all, mask=mask,
randomize=randomize)
if len(phases_num) == 1 and phases_num == 1:
combined_dt = phase_snow.dt
combined_region = phase_snow.regions
else:
combined_dt += phase_snow.dt
phase_snow.regions *= phase_snow.im
phase_snow.regions += num[i - 1]
phase_ws = phase_snow.regions * phase_snow.im
phase_ws[phase_ws == num[i - 1]] = 0
combined_region += phase_ws
num.append(sp.amax(combined_region))
if return_all:
tup = namedtuple('results', field_names=['im', 'dt', 'phase_max_label',
'regions'])
tup.im = im
tup.dt = combined_dt
tup.phase_max_label = num[1:]
tup.regions = combined_region
return tup
else:
return combined_region |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. This controls the localness of any maxima. The default is 4 voxels. footprint : ND-array Specifies the shape of the structuring element used to define the neighborhood when looking for peaks. If none is specified then a spherical shape is used (or circular in 2D). Returns ------- image : ND-array An array of booleans with ``True`` values at the location of any local maxima. Notes ----- It is also possible ot the ``peak_local_max`` function from the ``skimage.feature`` module as follows: ``peaks = peak_local_max(image=dt, min_distance=r, exclude_border=0, indices=False)`` This automatically uses a square structuring element which is significantly faster than using a circular or spherical element. """ |
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:
footprint = disk
elif im.ndim == 3:
footprint = ball
else:
raise Exception("only 2-d and 3-d images are supported")
mx = spim.maximum_filter(dt + 2*(~im), footprint=footprint(r_max))
peaks = (dt == mx)*im
return peaks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ------- image : ND-array An array with the same number of isolated peaks as the original image, but fewer total voxels. Notes ----- The center of mass of a group of voxels is used as the new single voxel, so if the group has an odd shape (like a horse shoe), the new voxel may *not* lie on top of the original set. """ |
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.arange(1, N+1))
inds = sp.floor(inds).astype(int)
# Centroid may not be on old pixel, so create a new peaks image
peaks_new = sp.zeros_like(peaks, dtype=bool)
peaks_new[tuple(inds.T)] = True
return peaks_new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 (``dt``) dt : ND-array The distance transform of the pore space for which the true peaks are sought. max_iters : int The maximum number of iterations to run while eroding the saddle points. The default is 10, which is usually not reached; however, a warning is issued if the loop ends prior to removing all saddle points. Returns ------- image : ND-array An image with fewer peaks than the input image References [1] Gostick, J. "A versatile and efficient network extraction algorithm using marker-based watershed segmenation". Physical Review E. (2017) """ |
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=10)
peaks_i = labels[s] == i+1
dt_i = dt[s]
im_i = dt_i > 0
iters = 0
peaks_dil = sp.copy(peaks_i)
while iters < max_iters:
iters += 1
peaks_dil = spim.binary_dilation(input=peaks_dil,
structure=cube(3))
peaks_max = peaks_dil*sp.amax(dt_i*peaks_dil)
peaks_extended = (peaks_max == dt_i)*im_i
if sp.all(peaks_extended == peaks_i):
break # Found a true peak
elif sp.sum(peaks_extended*peaks_i) == 0:
peaks_i = False
break # Found a saddle point
peaks[s] = peaks_i
if iters >= max_iters:
print('Maximum number of iterations reached, consider'
+ 'running again with a larger value of max_iters')
return peaks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 The distance transform of the pore space for which the true peaks are sought. Returns ------- image : ND-array An array the same size as ``peaks`` containing a subset of the peaks in the original image. Notes ----- Each pair of peaks is considered simultaneously, so for a triplet of peaks each pair is considered. This ensures that only the single peak that is furthest from the solid is kept. No iteration is required. References [1] Gostick, J. "A versatile and efficient network extraction algorithm using marker-based watershed segmenation". Physical Review E. (2017) """ |
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,
index=sp.arange(1, N+1))
crds = sp.vstack(crds).astype(int) # Convert to numpy array of ints
# Get distance between each peak as a distance map
tree = sptl.cKDTree(data=crds)
temp = tree.query(x=crds, k=2)
nearest_neighbor = temp[1][:, 1]
dist_to_neighbor = temp[0][:, 1]
del temp, tree # Free-up memory
dist_to_solid = dt[tuple(crds.T)] # Get distance to solid for each peak
hits = sp.where(dist_to_neighbor < dist_to_solid)[0]
# Drop peak that is closer to the solid than it's neighbor
drop_peaks = []
for peak in hits:
if dist_to_solid[peak] < dist_to_solid[nearest_neighbor[peak]]:
drop_peaks.append(peak)
else:
drop_peaks.append(nearest_neighbor[peak])
drop_peaks = sp.unique(drop_peaks)
# Remove peaks from image
slices = spim.find_objects(input=peaks)
for s in drop_peaks:
peaks[slices[s]] = 0
return (peaks > 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_disconnected_voxels """ |
im = sp.copy(im)
holes = find_disconnected_voxels(im)
im[holes] = False
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 -------- find_disconnected_voxels """ |
im = sp.copy(im)
holes = find_disconnected_voxels(~im)
im[holes] = True
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 The image of the porous material with ```True`` values indicating the phase of interest inlet_axis : int Inlet axis of boundary condition. For three dimensional image the number ranges from 0 to 2. For two dimensional image the range is between 0 to 1. outlet_axis : int Outlet axis of boundary condition. For three dimensional image the number ranges from 0 to 2. For two dimensional image the range is between 0 to 1. Returns ------- image : ND-array A copy of ``im`` with all the nonpercolating paths removed See Also -------- find_disconnected_voxels trim_floating_solid trim_blind_pores """ |
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]
inlet = sp.zeros_like(im, dtype=int)
outlet = sp.zeros_like(im, dtype=int)
if im.ndim == 3:
if inlet_axis == 0:
inlet[0, :, :] = 1
elif inlet_axis == 1:
inlet[:, 0, :] = 1
elif inlet_axis == 2:
inlet[:, :, 0] = 1
if outlet_axis == 0:
outlet[-1, :, :] = 1
elif outlet_axis == 1:
outlet[:, -1, :] = 1
elif outlet_axis == 2:
outlet[:, :, -1] = 1
if im.ndim == 2:
if inlet_axis == 0:
inlet[0, :] = 1
elif inlet_axis == 1:
inlet[:, 0] = 1
if outlet_axis == 0:
outlet[-1, :] = 1
elif outlet_axis == 1:
outlet[:, -1] = 1
IN = sp.unique(labels*inlet)
OUT = sp.unique(labels*outlet)
new_im = sp.isin(labels, list(set(IN) ^ set(OUT)), invert=True)
im[new_im == 0] = True
return ~im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 mode : string {'maxima' | 'minima' | 'extrema'} Specifies whether to remove maxima or minima or both Returns ------- image : ND-array A copy of the input image with all the peaks and/or valleys removed. Notes ----- This function is referred to as **imhmax** or **imhmin** in Matlab. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 dt : ND-array The distance transform of the phase of interest Returns ------- image : ND-array An ND-array the same shape as ``dt`` with numerical values indicating the maximum amount of error in each volxel, which is found by subtracting the distance to nearest edge of image from the distance transform value. In other words, this is the error that would be found if there were a solid voxel lurking just beyond the nearest edge of the image. Obviously, voxels with a value of zero have no error. """ |
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 result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 values indicating regions. Returns ------- image : ND-array A copy of ``im`` with each voxel value indicating the size of the region to which it belongs. This is particularly useful for finding chord sizes on the image produced by ``apply_chords``. """ |
if im.dtype == bool:
im = spim.label(im)[0]
counts = sp.bincount(im.flatten())
counts[0] = 0
chords = counts[im]
return chords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 is 1 voxel. This can be decreased to 0, meaning that the chords all touch each other, which automatically sets to the ``label`` argument to ``True``. axis : int (default = 0) The axis along which the chords are drawn. trim_edges : bool (default = ``True``) Whether or not to remove chords that touch the edges of the image. These chords are artifically shortened, so skew the chord length distribution. label : bool (default is ``False``) If ``True`` the chords in the returned image are each given a unique label, such that all voxels lying on the same chord have the same value. This is automatically set to ``True`` if spacing is 0, but is ``False`` otherwise. Returns ------- image : ND-array A copy of ``im`` with non-zero values indicating the chords. See Also -------- apply_chords_3D """ |
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 0')
if spacing == 0:
label = True
result = sp.zeros(im.shape, dtype=int) # Will receive chords at end
slxyz = [slice(None, None, spacing*(axis != i) + 1) for i in [0, 1, 2]]
slices = tuple(slxyz[:im.ndim])
s = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] # Straight-line structuring element
if im.ndim == 3: # Make structuring element 3D if necessary
s = sp.pad(sp.atleast_3d(s), pad_width=((0, 0), (0, 0), (1, 1)),
mode='constant', constant_values=0)
im = im[slices]
s = sp.swapaxes(s, 0, axis)
chords = spim.label(im, structure=s)[0]
if trim_edges: # Label on border chords will be set to 0
chords = clear_border(chords)
result[slices] = chords # Place chords into empty image created at top
if label is False: # Remove label if not requested
result = result > 0
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 space marked as True. spacing : int (default = 0) Chords are automatically separed by 1 voxel on all sides, and this argument increases the separation. trim_edges : bool (default is ``True``) Whether or not to remove chords that touch the edges of the image. These chords are artifically shortened, so skew the chord length distribution Returns ------- image : ND-array A copy of ``im`` with values of 1 indicating x-direction chords, 2 indicating y-direction chords, and 3 indicating z-direction chords. Notes ----- The chords are separated by a spacing of at least 1 voxel so that tools that search for connected components, such as ``scipy.ndimage.label`` can detect individual chords. See Also -------- apply_chords """ |
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 this function')
if spacing < 0:
raise Exception('Spacing cannot be less than 0')
ch = sp.zeros_like(im, dtype=int)
ch[:, ::4+2*spacing, ::4+2*spacing] = 1 # X-direction
ch[::4+2*spacing, :, 2::4+2*spacing] = 2 # Y-direction
ch[2::4+2*spacing, 2::4+2*spacing, :] = 3 # Z-direction
chords = ch*im
if trim_edges:
temp = clear_border(spim.label(chords > 0)[0]) > 0
chords = temp*chords
return chords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def porosimetry(im, sizes=25, inlets=None, access_limited=True, mode='hybrid'):
r""" Performs a porosimetry simulution on the image Parameters im : ND-array An ND image of the porous material containing True values in the pore space. sizes : array_like or scalar The sizes to invade. If a list of values of provided they are used directly. If a scalar is provided then that number of points spanning the min and max of the distance transform are used. inlets : ND-array, boolean A boolean mask with True values indicating where the invasion enters the image. By default all faces are considered inlets, akin to a mercury porosimetry experiment. Users can also apply solid boundaries to their image externally before passing it in, allowing for complex inlets like circular openings, etc. This argument is only used if ``access_limited`` is ``True``. access_limited : Boolean This flag indicates if the intrusion should only occur from the surfaces (``access_limited`` is True, which is the default), or if the invading phase should be allowed to appear in the core of the image. The former simulates experimental tools like mercury intrusion porosimetry, while the latter is useful for comparison to gauge the extent of shielding effects in the sample. mode : string Controls with method is used to compute the result. Options are: 'hybrid' - (default) Performs a distance tranform of the void space, thresholds to find voxels larger than ``sizes[i]``, trims the resulting mask if ``access_limitations`` is ``True``, then dilates it using the efficient fft-method to obtain the non-wetting fluid configuration. 'dt' - Same as 'hybrid', except uses a second distance transform, relative to the thresholded mask, to find the invading fluid configuration. The choice of 'dt' or 'hybrid' depends on speed, which is system and installation specific. 'mio' - Using a single morphological image opening step to obtain the invading fluid confirguration directly, *then* trims if ``access_limitations`` is ``True``. This method is not ideal and is included mostly for comparison purposes. The morphological operations are done using fft-based method implementations. Returns ------- image : ND-array A copy of ``im`` with voxel values indicating the sphere radius at which it becomes accessible from the inlets. This image can be used to find invading fluid configurations as a function of applied capillary pressure by applying a boolean comparison: ``inv_phase = im > r`` where ``r`` is the radius (in voxels) of the invading sphere. Of course, ``r`` can be converted to capillary pressure using your favorite model. Notes ----- There are many ways to perform this filter, and PoreSpy offer 3, which users can choose between via the ``mode`` argument. These methods all work in a similar way by finding which foreground voxels can accomodate a sphere of a given radius, then repeating for smaller radii. See Also -------- fftmorphology local_thickness """ |
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.')
dt = spim.distance_transform_edt(im > 0)
if inlets is None:
inlets = get_border(im.shape, mode='faces')
if isinstance(sizes, int):
sizes = sp.logspace(start=sp.log10(sp.amax(dt)), stop=0, num=sizes)
else:
sizes = sp.unique(sizes)[-1::-1]
if im.ndim == 2:
strel = ps_disk
else:
strel = ps_ball
if mode == 'mio':
pw = int(sp.floor(dt.max()))
impad = sp.pad(im, mode='symmetric', pad_width=pw)
inletspad = sp.pad(inlets, mode='symmetric', pad_width=pw)
inlets = sp.where(inletspad)
# sizes = sp.unique(sp.around(sizes, decimals=0).astype(int))[-1::-1]
imresults = sp.zeros(sp.shape(impad))
for r in tqdm(sizes):
imtemp = fftmorphology(impad, strel(r), mode='erosion')
if access_limited:
imtemp = trim_disconnected_blobs(imtemp, inlets)
imtemp = fftmorphology(imtemp, strel(r), mode='dilation')
if sp.any(imtemp):
imresults[(imresults == 0)*imtemp] = r
imresults = extract_subsection(imresults, shape=im.shape)
elif mode == 'dt':
inlets = sp.where(inlets)
imresults = sp.zeros(sp.shape(im))
for r in tqdm(sizes):
imtemp = dt >= r
if access_limited:
imtemp = trim_disconnected_blobs(imtemp, inlets)
if sp.any(imtemp):
imtemp = spim.distance_transform_edt(~imtemp) < r
imresults[(imresults == 0)*imtemp] = r
elif mode == 'hybrid':
inlets = sp.where(inlets)
imresults = sp.zeros(sp.shape(im))
for r in tqdm(sizes):
imtemp = dt >= r
if access_limited:
imtemp = trim_disconnected_blobs(imtemp, inlets)
if sp.any(imtemp):
imtemp = fftconvolve(imtemp, strel(r), mode='same') > 0.0001
imresults[(imresults == 0)*imtemp] = r
else:
raise Exception('Unreckognized mode ' + mode)
return imresults |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ------- image : ND-array An array of the same shape as ``im``, but with all foreground voxels not connected to the ``inlets`` removed. """ |
temp = sp.zeros_like(im)
temp[inlets] = True
labels, N = spim.label(im + temp)
im = im ^ (clear_border(labels=labels) > 0)
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 vectorized array comparisons possible.
'''
ndim = len(np.shape(im))
axial_shift = _get_axial_shifts(ndim, include_diagonals)
if ndim == 2:
stack = np.zeros([np.shape(im)[0],
np.shape(im)[1],
len(axial_shift)+1])
stack[:, :, 0] = im
for i in range(len(axial_shift)):
ax0, ax1 = axial_shift[i]
temp = np.roll(np.roll(im, ax0, 0), ax1, 1)
stack[:, :, i+1] = temp
return stack
elif ndim == 3:
stack = np.zeros([np.shape(im)[0],
np.shape(im)[1],
np.shape(im)[2],
len(axial_shift)+1])
stack[:, :, :, 0] = im
for i in range(len(axial_shift)):
ax0, ax1, ax2 = axial_shift[i]
temp = np.roll(np.roll(np.roll(im, ax0, 0), ax1, 1), ax2, 2)
stack[:, :, :, i+1] = temp
return stack |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 partitioned into regions and labeled values : array_like An array containing the numerical values to insert into each region. The value at location *n* will be inserted into the image where ``regions`` is *n+1*. This mis-match is caused by the fact that 0's in the ``regions`` image is assumed to be the backgroung phase, while pore index 0 is valid. Notes ----- This function assumes that the array of pore values are indexed starting at location 0, while in the region image 0's indicate background phase and the region indexing starts at 1. That is, region 1 corresponds to pore 0. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 can choose ‘left’, ‘right’, ‘top’, ‘bottom’, ‘front’ and ‘back’ face labels to assign boundary nodes. If no label is assigned then all six faces will be selected as boundary nodes automatically which can be trimmed later on based on user requirements. Returns ------- The same dictionar s pass ing, but containing boundary nodes labels. For example network['pore.left'], network['pore.right'], network['pore.top'], network['pore.bottom'] etc. Notes ----- The dictionary names use the OpenPNM convention so it may be converted directly to an OpenPNM network object using the ``update`` command. """ |
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
dic['bottom'] = 1
for i in f:
if i in ['left', 'front', 'bottom']:
network['pore.{}'.format(i)] = (coords[:, dic[i]] <
min(condition[:, dic[i]]))
elif i in ['right', 'back', 'top']:
network['pore.{}'.format(i)] = (coords[:, dic[i]] >
max(condition[:, dic[i]]))
return network |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 The sub-image to insert center : tuple Coordinates indicating the position in the main image where the inserted imaged will be centered. If ``center`` is given then ``corner`` cannot be specified. Note that ``center`` can only be used if all dimensions of ``element`` are odd, otherwise the meaning of center is not defined. corner : tuple Coordinates indicating the position in the main image where the lower corner (i.e. [0, 0, 0]) of the inserted image should be anchored. If ``corner`` is given then ``corner`` cannot be specified. value : scalar A scalar value to apply to the sub-image. The default is 1. mode : string If 'overwrite' (default) the inserted image replaces the values in the main image. If 'overlay' the inserted image is added to the main image. In both cases the inserted image is multiplied by ``value`` first. Returns ------- im : ND-array A copy of ``im`` with the supplied element inserted. """ |
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 range(im.ndim):
r, d = sp.divmod(element.shape[dim], 2)
if d == 0:
raise Exception('Cannot specify center point when element ' +
'has one or more even dimension')
lower_im = sp.amax((center[dim] - r, 0))
upper_im = sp.amin((center[dim] + r + 1, im.shape[dim]))
s_im.append(slice(lower_im, upper_im))
lower_el = sp.amax((lower_im - center[dim] + r, 0))
upper_el = sp.amin((upper_im - center[dim] + r,
element.shape[dim]))
s_el.append(slice(lower_el, upper_el))
elif (corner is not None) and (center is None):
for dim in range(im.ndim):
L = int(element.shape[dim])
lower_im = sp.amax((corner[dim], 0))
upper_im = sp.amin((corner[dim] + L, im.shape[dim]))
s_im.append(slice(lower_im, upper_im))
lower_el = sp.amax((lower_im - corner[dim], 0))
upper_el = sp.amin((upper_im - corner[dim],
element.shape[dim]))
s_el.append(slice(min(lower_el, upper_el), upper_el))
else:
raise Exception('Cannot specify both corner and center')
if mode == 'overlay':
im[tuple(s_im)] = im[tuple(s_im)] + element[tuple(s_el)]*value
elif mode == 'overwrite':
im[tuple(s_im)] = element[tuple(s_el)]*value
else:
raise Exception('Invalid mode ' + mode)
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 1 voxel is assumed. spacing : scalar The center to center distance of the holes. The hole sizes will be randomly distributed between this values down to 3 voxels. Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space """ |
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,
int(shape[0]/spacing)))
Xi = sp.array(Xi, dtype=int)
Yi = sp.ceil(sp.linspace(spacing/2,
shape[1]-(spacing/2)-1,
int(shape[1]/spacing)))
Yi = sp.array(Yi, dtype=int)
temp[tuple(sp.meshgrid(Xi, Yi))] = 1
inds = sp.where(temp)
for i in range(len(inds[0])):
r = sp.random.randint(1, (spacing/2))
try:
s1 = slice(inds[0][i]-r, inds[0][i]+r+1)
s2 = slice(inds[1][i]-r, inds[1][i]+r+1)
temp[s1, s2] = ps_disk(r)
except ValueError:
odd_shape = sp.shape(temp[s1, s2])
temp[s1, s2] = ps_disk(r)[:odd_shape[0], :odd_shape[1]]
im = sp.broadcast_to(array=sp.atleast_3d(temp), shape=shape)
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 polydisperse disks is returns porosity : scalar The porosity of the image, defined as the number of void voxels divided by the number of voxels in the image. The specified value is only matched approximately, so it's suggested to check this value after the image is generated. dist : scipy.stats distribution object This should be an initialized distribution chosen from the large number of options in the ``scipy.stats`` submodule. For instance, a normal distribution with a mean of 20 and a standard deviation of 10 can be obtained with ``dist = scipy.stats.norm(loc=20, scale=10)`` nbins : scalar The number of discrete sphere sizes that will be used to generate the image. This function generates ``nbins`` images of monodisperse spheres that span 0.05 and 0.95 of the possible values produced by the provided distribution, then overlays them to get polydispersivity. Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space """ |
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))
im = sp.ones(shape, dtype=bool)
for r in Rs:
phi_im = im.sum() / sp.prod(shape)
phi_corrected = 1 - (1 - phi_desired) / phi_im
temp = overlapping_spheres(shape=shape, radius=r, porosity=phi_corrected)
im = im * temp
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 Returns ------- A 2-by-N array of vertex indices, indicating the start and end points of each vertex in the Voronoi diagram. These vertex indices can be used to index straight into the ``vor.vertices`` array to get spatial positions. """ |
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, axis=1) # Identify edges at infinity
edges = edges[~mask] # Remove edges at infinity
edges = sp.sort(edges, axis=1) # Move all points to upper triangle
# Remove duplicate pairs
edges = edges[:, 0] + 1j*edges[:, 1] # Convert to imaginary
edges = sp.unique(edges) # Remove duplicates
edges = sp.vstack((sp.real(edges), sp.imag(edges))).T # Back to real
edges = sp.array(edges, dtype=int)
return edges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 : scalar The porosity of the final image, accurate to the given tolerance. iter_max : int Maximum number of iterations for the iterative algorithm that improves the porosity of the final image to match the given value. tol : float Tolerance for porosity of the final image compared to the given value. Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space Notes ----- This method can also be used to generate a dispersion of hollows by treating ``porosity`` as solid volume fraction and inverting the returned image. """ |
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(size=shape)
# Helper functions for calculating porosity: phi = g(f(N))
f = lambda N: spim.distance_transform_edt(im > N/bulk_vol) < radius
g = lambda im: 1 - im.sum() / sp.prod(shape)
# # Newton's method for getting image porosity match the given
# w = 1.0 # Damping factor
# dN = 5 if ndim == 2 else 25 # Perturbation
# for i in range(iter_max):
# err = g(f(N)) - porosity
# d_err = (g(f(N+dN)) - g(f(N))) / dN
# if d_err == 0:
# break
# if abs(err) <= tol:
# break
# N2 = N - int(err/d_err) # xnew = xold - f/df
# N = w * N2 + (1-w) * N
# Bisection search: N is always undershoot (bc. of overlaps)
N_low, N_high = N, 4*N
for i in range(iter_max):
N = sp.mean([N_high, N_low], dtype=int)
err = g(f(N)) - porosity
if err > 0:
N_low = N
else:
N_high = N
if abs(err) <= tol:
break
return ~f(N) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 If specified, this will threshold the image to the specified value prior to returning. If no value is given (the default), then the scalar noise field is returned. octaves : int Controls the *texture* of the noise, with higher octaves giving more complex features over larger length scales. frequency : array_like Controls the relative sizes of the features, with higher frequencies giving larger features. A scalar value will apply the same frequency in all directions, given an isotropic field; a vector value will apply the specified values along each axis to create anisotropy. mode : string Which noise algorithm to use, either ``'simplex'`` (default) or ``'perlin'``. Returns ------- image : ND-array If porosity is given, then a boolean array with ``True`` values denoting the pore space is returned. If not, then normally distributed and spatially correlated randomly noise is returned. Notes ----- This method depends the a package called 'noise' which must be compiled. It is included in the Anaconda distribution, or a platform specific binary can be downloaded. See Also -------- porespy.tools.norm_to_uniform """ |
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) == 3:
Lx, Ly, Lz = shape
if mode == 'simplex':
f = noise.snoise3
else:
f = noise.pnoise3
frequency = sp.atleast_1d(frequency)
if frequency.size == 1:
freq = sp.full(shape=[3, ], fill_value=frequency[0])
elif frequency.size == 2:
freq = sp.concatenate((frequency, [1]))
else:
freq = sp.array(frequency)
im = sp.zeros(shape=[Lx, Ly, Lz], dtype=float)
for x in range(Lx):
for y in range(Ly):
for z in range(Lz):
im[x, y, z] = f(x=x/freq[0], y=y/freq[1], z=z/freq[2],
octaves=octaves)
im = im.squeeze()
if porosity:
im = norm_to_uniform(im, scale=[0, 1])
im = im < porosity
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ``None`` is specified, then the scalar noise field is converted to a uniform distribution and returned without thresholding. blobiness : int or list of ints(default = 1) Controls the morphology of the blobs. A higher number results in a larger number of small blobs. If a list is supplied then the blobs are anisotropic. Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space See Also -------- norm_to_uniform """ |
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:
im = im < porosity
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 radius of the cylinders in voxels ncylinders : scalar The number of cylinders to add to the domain. Adjust this value to control the final porosity, which is not easily specified since cylinders overlap and intersect different fractions of the domain. theta_max : scalar A value between 0 and 90 that controls the amount of rotation *in the* XY plane, with 0 meaning all fibers point in the X-direction, and 90 meaning they are randomly rotated about the Z axis by as much as +/- 90 degrees. phi_max : scalar A value between 0 and 90 that controls the amount that the fibers lie *out of* the XY plane, with 0 meaning all fibers lie in the XY plane, and 90 meaning that fibers are randomly oriented out of the plane by as much as +/- 90 degrees. Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space """ |
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
if (phi_max > 90) or (phi_max < 0):
raise Exception('phi_max must be betwen 0 and 90')
if (theta_max > 90) or (theta_max < 0):
raise Exception('theta_max must be betwen 0 and 90')
n = 0
while n < ncylinders:
# Choose a random starting point in domain
x = sp.rand(3)*shape
# Chose a random phi and theta within given ranges
phi = (sp.pi/2 - sp.pi*sp.rand())*phi_max/90
theta = (sp.pi/2 - sp.pi*sp.rand())*theta_max/90
X0 = R*sp.array([sp.cos(phi)*sp.cos(theta),
sp.cos(phi)*sp.sin(theta),
sp.sin(phi)])
[X0, X1] = [x + X0, x - X0]
crds = line_segment(X0, X1)
lower = ~sp.any(sp.vstack(crds).T < [0, 0, 0], axis=1)
upper = ~sp.any(sp.vstack(crds).T >= shape, axis=1)
valid = upper*lower
if sp.any(valid):
im[crds[0][valid], crds[1][valid], crds[2][valid]] = 1
n += 1
im = sp.array(im, dtype=bool)
dt = spim.distance_transform_edt(~im) < radius
return ~dt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 lists containing the X, Y, and Z coordinates of all voxels that should be drawn between the start and end points to create a solid line. """ |
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.rint(sp.linspace(X0[2], X1[2], L)).astype(int)
return [x, y, z]
else:
L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]]])) + 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)
return [x, y] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _remove_edge(im, r):
r'''
Fill in the edges of the input image.
Used by RSA to ensure that no elements are placed too close to the edge.
'''
edge = sp.ones_like(im)
if len(im.shape) == 2:
sx, sy = im.shape
edge[r:sx-r, r:sy-r] = im[r:sx-r, r:sy-r]
else:
sx, sy, sz = im.shape
edge[r:sx-r, r:sy-r, r:sz-r] = im[r:sx-r, r:sy-r, r:sz-r]
return edge |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def align_image_with_openpnm(im):
r""" Rotates an image to agree with the coordinates used in OpenPNM. It is unclear why they are not in agreement to start with. This is necessary for overlaying the image and the network in Paraview. Parameters im : ND-array The image to be rotated. Can be the Boolean image of the pore space or any other image of interest. Returns ------- image : ND-array Returns a copy of ``im`` rotated accordingly. """ |
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 = sp.copy(im)
if im.ndim == 2:
im = (sp.swapaxes(im, 1, 0))
im = im[-1::-1, :]
elif im.ndim == 3:
im = (sp.swapaxes(im, 2, 0))
im = im[:, -1::-1, :]
return im |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fftmorphology(im, strel, mode='opening'):
r""" Perform morphological operations on binary images using fft approach for improved performance Parameters im : nd-array The binary image on which to perform the morphological operation strel : nd-array The structuring element to use. Must have the same dims as ``im``. mode : string The type of operation to perform. Options are 'dilation', 'erosion', 'opening' and 'closing'. Returns ------- image : ND-array A copy of the image with the specified moropholgical operation applied using the fft-based methods available in scipy.fftconvolve. Notes ----- This function uses ``scipy.signal.fftconvolve`` which *can* be more than 10x faster than the standard binary morphology operation in ``scipy.ndimage``. This speed up may not always be realized, depending on the scipy distribution used. Examples -------- Check that erosion, dilation, opening, and closing are all the same as the ``scipy.ndimage`` functions: True True True True """ |
def erode(im, strel):
t = fftconvolve(im, strel, mode='same') > (strel.sum() - 0.1)
return t
def dilate(im, strel):
t = fftconvolve(im, strel, mode='same') > 0.1
return t
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.')
# Perform erosion and dilation
# The array must be padded with 0's so it works correctly at edges
temp = sp.pad(array=im, pad_width=1, mode='constant', constant_values=0)
if mode.startswith('ero'):
temp = erode(temp, strel)
if mode.startswith('dila'):
temp = dilate(temp, strel)
# Remove padding from resulting image
if im.ndim == 2:
result = temp[1:-1, 1:-1]
elif im.ndim == 3:
result = temp[1:-1, 1:-1, 1:-1]
# Perform opening and closing
if mode.startswith('open'):
temp = fftmorphology(im=im, strel=strel, mode='erosion')
result = fftmorphology(im=temp, strel=strel, mode='dilation')
if mode.startswith('clos'):
temp = fftmorphology(im=im, strel=strel, mode='dilation')
result = fftmorphology(im=temp, strel=strel, mode='erosion')
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subdivide(im, divs=2):
r""" Returns slices into an image describing the specified number of sub-arrays. This function is useful for performing operations on smaller images for memory or speed. Note that for most typical operations this will NOT work, since the image borders would cause artifacts (e.g. ``distance_transform``) Parameters im : ND-array The image of the porous media divs : scalar or array_like The number of sub-divisions to create in each axis of the image. If a scalar is given it is assumed this value applies in all dimensions. Returns ------- slices : 1D-array A 1-D array containing slice objects for indexing into ``im`` that extract the sub-divided arrays. Notes ----- This method uses the `array_split package <https://github.com/array-split/array_split>`_ which offers the same functionality as the ``split`` method of Numpy's ND-array, but supports the splitting multidimensional arrays in all dimensions. Examples -------- ``s`` contains an array with the shape given by ``divs``. To access the first and last quadrants of ``im`` use: (100, 100) (100, 100) It can be easier to index the array with the slices by applying ``flatten`` first: (100, 100) (100, 100) (100, 100) (100, 100) """ |
# Expand scalar divs
if isinstance(divs, int):
divs = [divs for i in range(im.ndim)]
s = shape_split(im.shape, axis=divs)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bbox_to_slices(bbox):
r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an image. This function returns a tuples of slices can be, such as: ``im[bbox_to_slices([xmin, ymin, xmax, ymax])]``. Parameters bbox : tuple of ints The bounding box indices in the form (``xmin``, ``ymin``, ``zmin``, ``xmax``, ``ymax``, ``zmax``). For a 2D image, simply omit the ``zmin`` and ``zmax`` entries. Returns ------- slices : tuple A tuple of slice objects that can be used to directly index into a larger image. """ |
if len(bbox) == 4:
ret = (slice(bbox[0], bbox[2]),
slice(bbox[1], bbox[3]))
else:
ret = (slice(bbox[0], bbox[3]),
slice(bbox[1], bbox[4]),
slice(bbox[2], bbox[5]))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_slice(im, center, size, pad=0):
r""" Given a ``center`` location and ``radius`` of a feature, returns the slice object into the ``im`` that bounds the feature but does not extend beyond the image boundaries. Parameters im : ND-image The image of the porous media center : array_like The coordinates of the center of the feature of interest size : array_like or scalar The size of the feature in each direction. If a scalar is supplied, this implies the same size in all directions. pad : scalar or array_like The amount to pad onto each side of the slice. The default is 0. A scalar value will increase the slice size equally in all directions, while an array the same shape as ``im.shape`` can be passed to pad a specified amount in each direction. Returns ------- slices : list A list of slice objects, each indexing into one dimension of the image. """ |
p = sp.ones(shape=im.ndim, dtype=int) * sp.array(pad)
s = sp.ones(shape=im.ndim, dtype=int) * sp.array(size)
slc = []
for dim in range(im.ndim):
lower_im = sp.amax((center[dim] - s[dim] - p[dim], 0))
upper_im = sp.amin((center[dim] + s[dim] + 1 + p[dim], im.shape[dim]))
slc.append(slice(lower_im, upper_im))
return slc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_outer_region(im, r=0):
r""" Finds regions of the image that are outside of the solid matrix. This function uses the rolling ball method to define where the outer region ends and the void space begins. This function is particularly useful for samples that do not fill the entire rectangular image, such as cylindrical cores or samples with non- parallel faces. Parameters im : ND-array Image of the porous material with 1's for void and 0's for solid r : scalar The radius of the rolling ball to use. If not specified then a value is calculated as twice maximum of the distance transform. The image size is padded by this amount in all directions, so the image can become quite large and unwieldy if too large a value is given. Returns ------- image : ND-array A boolean mask the same shape as ``im``, containing True in all voxels identified as *outside* the sample. """ |
if r == 0:
dt = spim.distance_transform_edt(input=im)
r = int(sp.amax(dt)) * 2
im_padded = sp.pad(array=im, pad_width=r, mode='constant',
constant_values=True)
dt = spim.distance_transform_edt(input=im_padded)
seeds = (dt >= r) + get_border(shape=im_padded.shape)
# Remove seeds not connected to edges
labels = spim.label(seeds)[0]
mask = labels == 1 # Assume label of 1 on edges, assured by adding border
dt = spim.distance_transform_edt(~mask)
outer_region = dt < r
outer_region = extract_subsection(im=outer_region, shape=im.shape)
return outer_region |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.