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[...
<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 ...
<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() ...
<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, ou...
<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_...
<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.T...
<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_sc...
<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...
<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=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 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: ...
<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(riem...
<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: ...
<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_CHECKSEQ...
<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( ou...
<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_i...
<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_scrip...
<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 OverwinterT...
<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. ...
<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 = l...
<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 ...
<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,...
<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_command...
<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): ...
<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 retur...
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(me...
<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 specifie...
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(sha...
<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...
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 re...
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 ...
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/...
<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 spa...
# 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...
<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 ``...
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_ed...
<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 co...
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 conta...
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...
<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 regio...
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 dimensiona...
<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 t...
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 fr...
<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...
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 --...
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.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 sem(im, direction='X'): r""" Simulates an SEM photograph looking into the porous material in the specified direction. Features are colored according to their...
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 ...
<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 ac...
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, ca...
# 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 (T...
<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``....
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...
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_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 snow_n(im, voxel_size=1, boundary_faces=['top', 'bottom', 'left', 'right', 'front', 'back'], marching_cubes_area=False, alias=None): r""" Analyzes an image t...
# ------------------------------------------------------------------------- # 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 ...
<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 Parameter...
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 ...
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 imag...
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:] imageToVT...
<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. U...
# 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) ...
<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. ...
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) ...
<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 mar...
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...
<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 arb...
# 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:...
<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 ...
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: ...
<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...
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, ...
<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 transf...
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) ...
<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 sol...
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, in...
<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 Return...
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 materia...
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 per...
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 =...
<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 vall...
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 sin...
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...
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...
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') ...
<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 plu...
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 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 porosimetry(im, sizes=25, inlets=None, access_limited=True, mode='hybrid'): r""" Performs a porosimetry simulution on the image Parameters im : ND-array An N...
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: ...
<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...
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 i...
<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 numberin...
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 di...
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['bo...
<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 ...
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 rang...
<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 th...
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, ...
<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 wi...
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 ...
<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 eea...
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, axi...
<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-dispe...
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=sh...
<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 ...
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: ...
<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...
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: ...
<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....
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 ...
<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] o...
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(...
<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...
<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....
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)...
<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 : ...
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(...
<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 ...
# 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 ...
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 fe...
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.appe...
<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 ...
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) ...