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 add_summary(self, summary, global_step=None): """Adds a `Summary` protocol buffer to the event file. This method wraps the provided summary in an `Event` pro...
if isinstance(summary, bytes): summ = summary_pb2.Summary() summ.ParseFromString(summary) summary = summ # We strip metadata from values with tags that we have seen before in order # to save space - we just store the metadata on the first value with a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_graph(self, graph): """Adds a `Graph` protocol buffer to the event file."""
event = event_pb2.Event(graph_def=graph.SerializeToString()) self._add_event(event, 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 add_scalar(self, tag, value, global_step=None): """Adds scalar data to the event file. Parameters tag : str Name for the scalar plot. value : float, tuple, l...
if isinstance(value, (tuple, list, dict)): if isinstance(value, (tuple, list)): if len(value) != 2: raise ValueError('expected two elements in value, while received %d' % len(value)) value = {value[0]: value[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 _add_scalars(self, tag, scalar_dict, global_step=None): """Adds multiple scalars to summary. This enables drawing multiple curves in one plot. Parameters tag...
timestamp = time.time() fw_logdir = self._file_writer.get_logdir() for scalar_name, scalar_value in scalar_dict.items(): fw_tag = fw_logdir + '/' + tag + '/' + scalar_name if fw_tag in self._all_writers.keys(): fw = self._all_writers[fw_tag] 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 add_histogram(self, tag, values, global_step=None, bins='default'): """Add histogram data to the event file. Note: This function internally calls `asnumpy()`...
if bins == 'default': bins = self._get_default_bins() self._file_writer.add_summary(histogram_summary(tag, values, bins), global_step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_image(self, tag, image, global_step=None): """Add image data to the event file. This function supports input as a 2D, 3D, or 4D image. If the input image...
self._file_writer.add_summary(image_summary(tag, image), global_step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_audio(self, tag, audio, sample_rate=44100, global_step=None): """Add audio data to the event file. Note: This function internally calls `asnumpy()` for M...
self._file_writer.add_summary(audio_summary(tag, audio, sample_rate=sample_rate), global_step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_text(self, tag, text, global_step=None): """Add text data to the event file. Parameters tag : str Name for the `text`. text : str Text to be saved to the...
self._file_writer.add_summary(text_summary(tag, text), global_step) if tag not in self._text_tags: self._text_tags.append(tag) extension_dir = self.get_logdir() + '/plugins/tensorboard_text/' if not os.path.exists(extension_dir): os.makedirs(extension...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_pr_curve(self, tag, labels, predictions, num_thresholds, global_step=None, weights=None): """Adds precision-recall curve. Note: This function internally ...
if num_thresholds < 2: raise ValueError('num_thresholds must be >= 2') labels = _make_numpy_array(labels) predictions = _make_numpy_array(predictions) self._file_writer.add_summary(pr_curve_summary(tag, labels, predictions, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rectangular(n): """Checks to see if a 2D list is a valid 2D matrix"""
for i in n: if len(i) != len(n[0]): return False return 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 _is_2D_matrix(matrix): """Checks to see if a ndarray is 2D or a list of lists is 2D"""
return ((isinstance(matrix[0], list) and _rectangular(matrix) and not isinstance(matrix[0][0], list)) or (not isinstance(matrix, list) and matrix.shape == 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 _save_image(image, filename, nrow=8, padding=2, square_image=True): """Saves a given Tensor into an image file. If the input tensor contains multiple images,...
if not isinstance(image, NDArray): raise TypeError('MXNet NDArray expected, received {}'.format(str(type(image)))) image = _prepare_image(image, nrow=nrow, padding=padding, square_image=square_image) if Image is None: raise ImportError('saving image failed because PIL is not found') 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 _save_embedding_tsv(data, file_path): """Given a 2D `NDarray` or a `numpy.ndarray` as embeding, save it in tensors.tsv under the path provided by the user.""...
if isinstance(data, np.ndarray): data_list = data.tolist() elif isinstance(data, NDArray): data_list = data.asnumpy().tolist() else: raise TypeError('expected NDArray of np.ndarray, while received type {}'.format( str(type(data)))) with open(os.path.join(file_path, '...
<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_image(tensor): """Converts an NDArray type image to Image protobuf"""
assert isinstance(tensor, NDArray) if Image is None: raise ImportError('need to install PIL for visualizing images') height, width, channel = tensor.shape tensor = _make_numpy_array(tensor) image = Image.fromarray(tensor) output = io.BytesIO() image.save(output, format='PNG') 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 pr_curve_summary(tag, labels, predictions, num_thresholds, weights=None): """Outputs a precision-recall curve `Summary` protocol buffer. Parameters tag : str...
# num_thresholds > 127 results in failure of creating protobuf, # probably a bug of protobuf if num_thresholds > 127: logging.warning('num_thresholds>127 would result in failure of creating pr_curve protobuf,' ' clipping it at 127') num_thresholds = 127 labels = ...
<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_nodes_from_symbol(sym): """Given a symbol and shapes, return a list of `NodeDef`s for visualizing the the graph in TensorBoard."""
if not isinstance(sym, Symbol): raise TypeError('sym must be an `mxnet.symbol.Symbol`,' ' received type {}'.format(str(type(sym)))) conf = json.loads(sym.tojson()) nodes = conf['nodes'] data2op = {} # key: data id, value: list of ops to whom data is an input for 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 temporal_derivatives(order, variables, data): """ Compute temporal derivative terms by the method of backwards differences. Parameters order: range or list(i...
variables_deriv = OrderedDict() data_deriv = OrderedDict() if 0 in order: data_deriv[0] = data[variables] variables_deriv[0] = variables order = set(order) - set([0]) for o in order: variables_deriv[o] = ['{}_derivative{}'.format(v, o) for v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exponential_terms(order, variables, data): """ Compute exponential expansions. Parameters order: range or list(int) A list of exponential terms to include. F...
variables_exp = OrderedDict() data_exp = OrderedDict() if 1 in order: data_exp[1] = data[variables] variables_exp[1] = variables order = set(order) - set([1]) for o in order: variables_exp[o] = ['{}_power{}'.format(v, o) for v in variables] data_exp[o] = data[var...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _order_as_range(order): """Convert a hyphenated string representing order for derivative or exponential terms into a range object that can be passed as input...
order = order.split('-') order = [int(o) for o in order] if len(order) > 1: order = range(order[0], (order[-1] + 1)) return order
<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_and_expand_exponential(expr, variables, data): """Check if the current operation specifies exponential expansion. ^^6 specifies all powers up to the 6...
if re.search(r'\^\^[0-9]+$', expr): order = re.compile(r'\^\^([0-9]+)$').findall(expr) order = range(1, int(*order) + 1) variables, data = exponential_terms(order, variables, data) elif re.search(r'\^[0-9]+[\-]?[0-9]*$', expr): order = re.compile(r'\^([0-9]+[\-]?[0-9]*)').findal...
<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_and_expand_derivative(expr, variables, data): """Check if the current operation specifies a temporal derivative. dd6x specifies all derivatives up to ...
if re.search(r'^dd[0-9]+', expr): order = re.compile(r'^dd([0-9]+)').findall(expr) order = range(0, int(*order) + 1) (variables, data) = temporal_derivatives(order, variables, data) elif re.search(r'^d[0-9]+[\-]?[0-9]*', expr): order = re.compile(r'^d([0-9]+[\-]?[0-9]*)').findal...
<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_and_expand_subformula(expression, parent_data, variables, data): """Check if the current operation contains a suboperation, and parse it where appropr...
grouping_depth = 0 for i, char in enumerate(expression): if char == '(': if grouping_depth == 0: formula_delimiter = i + 1 grouping_depth += 1 elif char == ')': grouping_depth -= 1 if grouping_depth == 0: expr = exp...
<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_expression(expression, parent_data): """ Parse an expression in a model formula. Parameters expression: str Formula expression: either a single variabl...
variables = None data = None variables, data = _check_and_expand_subformula(expression, parent_data, variables, data) variables, data = _check_and_exp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_shorthand(model_formula, variables): """Expand shorthand terms in the model formula. """
wm = 'white_matter' gsr = 'global_signal' rps = 'trans_x + trans_y + trans_z + rot_x + rot_y + rot_z' fd = 'framewise_displacement' acc = _get_matches_from_data('a_comp_cor_[0-9]+', variables) tcc = _get_matches_from_data('t_comp_cor_[0-9]+', variables) dv = _get_matches_from_data('^std_dva...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unscramble_regressor_columns(parent_data, data): """Reorder the columns of a confound matrix such that the columns are in the same order as the input data w...
matches = ['_power[0-9]+', '_derivative[0-9]+'] var = OrderedDict((c, deque()) for c in parent_data.columns) for c in data.columns: col = c for m in matches: col = re.sub(m, '', col) if col == c: var[col].appendleft(c) else: var[col].appen...
<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_formula(model_formula, parent_data, unscramble=False): """ Recursively parse a model formula by breaking it into additive atoms and tracking grouping s...
variables = {} data = {} expr_delimiter = 0 grouping_depth = 0 model_formula = _expand_shorthand(model_formula, parent_data.columns) for i, char in enumerate(model_formula): if char == '(': grouping_depth += 1 elif char == ')': grouping_depth -= 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 mask(in_file, mask_file, new_name): """ Apply a binary mask to an image. Parameters in_file : str Path to a NIfTI file to mask mask_file : str Path to a bina...
import nibabel as nb import os # Load the input image in_nii = nb.load(in_file) # Load the mask image mask_nii = nb.load(mask_file) # Set all non-mask voxels in the input file to zero. data = in_nii.get_data() data[mask_nii.get_data() == 0] = 0 # Save the new masked image. 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 create_cfm(in_file, lesion_mask=None, global_mask=True, out_path=None): """ Create a mask to constrain registration. Parameters in_file : str Path to an exis...
import os import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix if out_path is None: out_path = fname_presuffix(in_file, suffix='_cfm', newpath=os.getcwd()) else: out_path = os.path.abspath(out_path) if not global_mask and not lesion_ma...
<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_settings(self): """ Return any settings defined by the user, as well as any pre-defined settings files that exist for the image modalities to be registe...
# If user-defined settings exist... if isdefined(self.inputs.settings): # Note this in the log and return those settings. NIWORKFLOWS_LOG.info('User-defined settings, overriding defaults') return self.inputs.settings # Define a prefix for output files based ...
<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_ants_args(self): args = {'moving_image': self.inputs.moving_image, 'num_threads': self.inputs.num_threads, 'float': self.inputs.float, 'terminal_output'...
# If a moving mask is provided... if isdefined(self.inputs.moving_mask): # If explicit masking is enabled... if self.inputs.explicit_masking: # Mask the moving image. # Do not use a moving mask during registration. args['moving_ima...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dollars_to_math(source): r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backt...
s = "\n".join(source) if s.find("$") == -1: return # This searches for "$blah$" inside a pair of curly braces -- # don't change these, since they're probably coming from a nested # math environment. So for each match, we replace it with a temporary # string, and later on we substitute ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_run_hook(self, runtime): """ there is not inner interface to run """
self._fixed_image = self.inputs.after self._moving_image = self.inputs.before self._contour = self.inputs.wm_seg if isdefined(self.inputs.wm_seg) else None NIWORKFLOWS_LOG.info( 'Report - setting before (%s) and after (%s) images', self._fixed_image, self._moving...
<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_data_path(data_dir=None): """ Get data storage directory data_dir: str Path of the data directory. Used to force data storage in a specified location. :...
data_dir = data_dir or '' default_dirs = [Path(d).expanduser().resolve() for d in os.getenv('CRN_SHARED_DATA', '').split(os.pathsep) if d.strip()] default_dirs += [Path(d).expanduser().resolve() for d in os.getenv('CRN_DATA', '').split(os.pathse...
<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_dataset(dataset_name, dataset_prefix=None, data_dir=None, default_paths=None, verbose=1): """ Create if necessary and returns data directory of given da...
dataset_folder = dataset_name if not dataset_prefix \ else '%s%s' % (dataset_prefix, dataset_name) default_paths = default_paths or '' paths = [p / dataset_folder for p in _get_data_path(data_dir)] all_paths = [Path(p) / dataset_folder for p in default_paths.split(os.pathsep)]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _md5_sum_file(path): """ Calculates the MD5 sum of a file. """
with Path(path).open('rb') as fhandle: md5sum = hashlib.md5() while True: data = fhandle.read(8192) if not data: break md5sum.update(data) return md5sum.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk_report_(bytes_so_far, total_size, initial_size, t_0): """Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int t...
if not total_size: sys.stderr.write("\rDownloaded {0:d} of ? bytes.".format(bytes_so_far)) else: # Estimate remaining download time total_percent = float(bytes_so_far) / total_size current_download_size = bytes_so_far - initial_size bytes_remaining = total_size - byte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refine_aseg(aseg, ball_size=4): """ First step to reconcile ANTs' and FreeSurfer's brain masks. Here, the ``aseg.mgz`` mask from FreeSurfer is refined in two...
# Read aseg data bmask = aseg.copy() bmask[bmask > 0] = 1 bmask = bmask.astype(np.uint8) # Morphological operations selem = sim.ball(ball_size) newmask = sim.binary_closing(bmask, selem) newmask = binary_fill_holes(newmask.astype(np.uint8), selem).astype(np.uint8) return newmask.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4): """ Grow mask including pixels that have a high likelihood. GM tissue parameters are sampled in ...
selem = sim.ball(bw) if ants_segs is None: ants_segs = np.zeros_like(aseg, dtype=np.uint8) aseg[aseg == 42] = 3 # Collapse both hemispheres gm = anat.copy() gm[aseg != 3] = 0 refined = refine_aseg(aseg) newrefmask = sim.binary_dilation(refined, selem) - refined indices = np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def medial_wall_to_nan(in_file, subjects_dir, target_subject, newpath=None): """ Convert values on medial wall to NaNs """
import nibabel as nb import numpy as np import os fn = os.path.basename(in_file) if not target_subject.startswith('fs'): return in_file cortex = nb.freesurfer.read_label(os.path.join( subjects_dir, target_subject, 'label', '{}.cortex.label'.format(fn[:2]))) func = nb.load(...
<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_link_node(rawtext, app, type, slug, options): """Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sph...
try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) ref = base + type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub issue. Returns 2 part tuple containing list of nodes to inser...
try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problema...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert ...
app = inliner.document.settings.env.app #app.info('user link %r' % text) ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub commit. Returns 2 part tuple containing list of nodes to ins...
app = inliner.document.settings.env.app #app.info('user link %r' % text) try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_proj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _import(self, name): ''' Import namespace package ''' mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def discover_modules(self): ''' Return module sequence discovered from ``self.package_name`` Parameters ---------- None Returns ------- mods : sequence Sequence of module names within ``self.package_name`` Examples -------- ...
<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_metadata_for_nifti(in_file, bids_dir=None, validate=True): """Fetch metadata for a given nifti file 'SIEMENS' """
return _init_layout(in_file, bids_dir, validate).get_metadata( str(in_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 group_multiecho(bold_sess): """ Multiplexes multi-echo EPIs into arrays. Dual-echo is a special case of multi-echo, which is treated as single-echo data. ['s...
from itertools import groupby def _grp_echos(x): if '_echo-' not in x: return x echo = re.search("_echo-\\d*", x).group(0) return x.replace(echo, "_echo-?") ses_uids = [] for _, bold in groupby(bold_sess, key=_grp_echos): bold = list(bold) # If sing...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _define_variant(self): """Assign arbitrary label to combination of CIFTI spaces"""
space = None variants = { # to be expanded once addtional spaces are supported 'space1': ['fsaverage5', 'MNI152NLin2009cAsym'], 'space2': ['fsaverage6', 'MNI152NLin2009cAsym'], } for sp, targets in variants.items(): if all(target in target...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_data(self): """Converts inputspec to files"""
if (self.inputs.surface_target == "fsnative" or self.inputs.volume_target != "MNI152NLin2009cAsym"): # subject space is not support yet raise NotImplementedError annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorient(in_file, newpath=None): """Reorient Nifti files to RAS"""
out_file = fname_presuffix(in_file, suffix='_ras', newpath=newpath) nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file) return out_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 normalize_xform(img): """ Set identical, valid qform and sform matrices in an image Selects the best available affine (sform > qform > shape-based), and coer...
# Let nibabel convert from affine to quaternions, and recover xform tmp_header = img.header.copy() tmp_header.set_qform(img.affine) xform = tmp_header.get_qform() xform_code = 2 # Check desired codes qform, qform_code = img.get_qform(coded=True) sform, sform_code = img.get_sform(coded=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def demean(in_file, in_mask, only_mask=False, newpath=None): """Demean ``in_file`` within the mask defined by ``in_mask``"""
import os import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_file = fname_presuffix(in_file, suffix='_demeaned', newpath=os.getcwd()) nii = nb.load(in_file) msk = nb.load(in_mask).get_data() data = nii.get_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 nii_ones_like(in_file, value, dtype, newpath=None): """Create a NIfTI file filled with ``value``, matching properties of ``in_file``"""
import os import numpy as np import nibabel as nb nii = nb.load(in_file) data = np.ones(nii.shape, dtype=float) * value out_file = os.path.join(newpath or os.getcwd(), "filled.nii.gz") nii = nb.Nifti1Image(data, nii.affine, nii.header) nii.set_data_dtype(dtype) nii.to_filename(out...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorient_wf(name='ReorientWorkflow'): """A workflow to reorient images to 'RPI' orientation"""
workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_file']), name='outputnode') deoblique = pe.Node(afni.Refit(deoblique=True), name='deoblique') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None, drop_columns=None, enforce_case=True): """ Convert metadata from TSV format to JSON forma...
import pandas as pd # Adapted from https://dev.to/rrampage/snake-case-to-camel-case-and- ... # back-using-regular-expressions-and-python-m9j re_to_camel = r'(.*?)_([a-zA-Z0-9])' re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)' def snake(match): return '{}_{}'.format(matc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None, mask_erosion_prop=None, erosion_prop=None, pthres=0.95, newpath=None): """ Generate a mask f...
tpm_img = nb.load(in_tpm) roi_mask = (tpm_img.get_data() >= pthres).astype(np.uint8) eroded_mask_file = None erode_in = (mask_erosion_mm is not None and mask_erosion_mm > 0 or mask_erosion_prop is not None and mask_erosion_prop < 1) if erode_in: eroded_mask_file = fname_pre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_reports(reportlets_dir, out_dir, subject_label, run_uuid, config=None, packagename=None): """ Runs the reports .. testsetup:: .. doctest:: 0 .. testclean...
report = Report(Path(reportlets_dir), out_dir, run_uuid, config=config, subject_id=subject_label, packagename=packagename) return report.generate_report()
<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_reports(subject_list, output_dir, work_dir, run_uuid, config=None, packagename=None): """ A wrapper to run_reports on a given ``subject_list`` """
reports_dir = str(Path(work_dir) / 'reportlets') report_errors = [ run_reports(reports_dir, output_dir, subject_label, run_uuid, config, packagename=packagename) for subject_label in subject_list ] errno = sum(report_errors) if errno: import logging ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self, config): """ Traverse the reports config definition and instantiate reportlets. This method also places figures in their final location. """
for subrep_cfg in config: # First determine whether we need to split by some ordering # (ie. sessions / tasks / runs), which are separated by commas. orderings = [s for s in subrep_cfg.get('ordering', '').strip().split(',') if s] queries = [] for key ...
<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_report(self): """Once the Report has been indexed, the final HTML can be generated"""
logs_path = self.out_dir / 'logs' boilerplate = [] boiler_idx = 0 if (logs_path / 'CITATION.html').exists(): text = (logs_path / 'CITATION.html').read_text(encoding='UTF-8') text = '<div class="boiler-html">%s</div>' % re.compile( '<body>(.*?)</...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _applytfms(args): """ Applies ANTs' antsApplyTransforms to the input image. All inputs are zipped in one tuple to make it digestible by multiprocessing's map...
import nibabel as nb from nipype.utils.filemanip import fname_presuffix from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms in_file, in_xform, ifargs, index, newpath = args out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _arrange_xfms(transforms, num_files, tmp_folder): """ Convenience method to arrange the list of transforms that should be applied to each input file """
base_xform = ['#Insight Transform File V1.0', '#Transform 0'] # Initialize the transforms matrix xfms_T = [] for i, tf_file in enumerate(transforms): # If it is a deformation field, copy to the tfs_matrix directly if guess_type(tf_file)[0] != 'text/plain': xfms_T.append([tf_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_transform(fname): """Load affine transform from file Parameters fname : str or None Filename of an LTA or FSL-style MAT transform file. If ``None``, ret...
if fname is None: return np.eye(4) if fname.endswith('.mat'): return np.loadtxt(fname) elif fname.endswith('.lta'): with open(fname, 'rb') as fobj: for line in fobj: if line.startswith(b'1 4 4'): break lines = fobj.readlin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vertex_normals(vertices, faces): """Calculates the normals of a triangular mesh"""
def normalize_v3(arr): ''' Normalize a numpy array of 3 component vectors shape=(n,3) ''' lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2) arr /= lens[:, np.newaxis] tris = vertices[faces] facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) nor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pointcloud2ply(vertices, normals, out_file=None): """Converts the file to PLY format"""
from pathlib import Path import pandas as pd from pyntcloud import PyntCloud df = pd.DataFrame(np.hstack((vertices, normals))) df.columns = ['x', 'y', 'z', 'nx', 'ny', 'nz'] cloud = PyntCloud(df) if out_file is None: out_file = Path('pointcloud.ply').resolve() cloud.to_file(st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ply2gii(in_file, metadata, out_file=None): """Convert from ply to GIfTI"""
from pathlib import Path from numpy import eye from nibabel.gifti import ( GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray, ) from pyntcloud import PyntCloud in_file = Path(in_file) surf = PyntCloud.from_file(str(in_file)) # Update centroid metadata metadata.up...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s '/path/to/sub-045_T1w.nii.gz' """
import os from nipype.utils.filemanip import filename_to_list base, in_file = os.path.split(filename_to_list(in_files)[0]) subject_label = in_file.split("_", 1)[0].split("-")[1] return os.path.join(base, "sub-%s_T1w.nii.gz" % subject_label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_suffix(in_files, suffix): """ Wrap nipype's fname_presuffix to conveniently just add a prefix 'sub-045_ses-test_T1w_test.nii.gz' """
import os.path as op from nipype.utils.filemanip import fname_presuffix, filename_to_list return op.basename(fname_presuffix(filename_to_list(in_files)[0], suffix=suffix))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_txt(path): """Read a txt crashfile """
from pathlib import Path lines = Path(path).read_text().splitlines() data = {'file': str(path)} traceback_start = 0 if lines[0].startswith('Node'): data['node'] = lines[0].split(': ', 1)[1].strip() data['node_dir'] = lines[1].split(': ', 1)[1].strip() inputs = [] cur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conform_mask(in_mask, in_reference): """Ensures the mask headers make sense and match those of the T1w"""
from pathlib import Path import nibabel as nb from nipype.utils.filemanip import fname_presuffix ref = nb.load(in_reference) nii = nb.load(in_mask) hdr = nii.header.copy() hdr.set_data_dtype('int16') hdr.set_slope_inter(1, 0) qform, qcode = ref.header.get_qform(coded=True) 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 get_template(template_name, data_dir=None, url=None, resume=True, verbose=1): """Download and load a template"""
warn(DEPRECATION_MSG) if template_name.startswith('tpl-'): template_name = template_name[4:] # An aliasing mechanism. Please avoid template_name = TEMPLATE_ALIASES.get(template_name, template_name) return get_dataset(template_name, dataset_prefix='tpl-', data_dir=data_dir, ...
<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_bids_examples(data_dir=None, url=None, resume=True, verbose=1, variant='BIDS-examples-1-1.0.0-rc3u5'): """Download BIDS-examples-1"""
warn(DEPRECATION_MSG) variant = 'BIDS-examples-1-1.0.0-rc3u5' if variant not in BIDS_EXAMPLES else variant if url is None: url = BIDS_EXAMPLES[variant][0] md5 = BIDS_EXAMPLES[variant][1] return fetch_file(variant, url, data_dir, resume=resume, verbose=verbose, md5sum=m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def svg2str(display_object, dpi=300): """ Serializes a nilearn display object as a string """
from io import StringIO image_buf = StringIO() display_object.frame_axes.figure.savefig( image_buf, dpi=dpi, format='svg', facecolor='k', edgecolor='k') return image_buf.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_svg(display_object, dpi=300, compress='auto'): """ Removes the preamble of the svg files generated with nilearn """
image_svg = svg2str(display_object, dpi) if compress is True or compress == 'auto': image_svg = svg_compress(image_svg, compress) image_svg = re.sub(' height="[0-9]+[a-z]*"', '', image_svg, count=1) image_svg = re.sub(' width="[0-9]+[a-z]*"', '', image_svg, count=1) image_svg = re.sub(' vie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cuts_from_bbox(mask_nii, cuts=3): """Finds equi-spaced cuts for presenting images"""
from nibabel.affines import apply_affine mask_data = mask_nii.get_data() > 0.0 # First, project the number of masked voxels on each axes ijk_counts = [ mask_data.sum(2).sum(1), # project sagittal planes to transverse (i) axis mask_data.sum(2).sum(0), # project coronal planes to to 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 _3d_in_file(in_file): ''' if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file ''' in_file = filemanip.filename_to_list(in_file)[0] try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_to_2d(data, max_axis): """ Projects 3d data cube along one axis using maximum intensity with preservation of the signs. Adapted from nilearn. """
import numpy as np # get the shape of the array we are projecting to new_shape = list(data.shape) del new_shape[max_axis] # generate a 3D indexing array that points to max abs value in the # current projection a1, a2 = np.indices(new_shape) inds = [a1, a2] inds.insert(max_axis, np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Install entry-point """
from os import path as op from inspect import getfile, currentframe from setuptools import setup, find_packages from niworkflows.__about__ import ( __packagename__, __author__, __email__, __maintainer__, __license__, __description__, __longdesc__,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afni_wf(name='AFNISkullStripWorkflow', unifize=False, n4_nthreads=1): """ Skull-stripping workflow Originally derived from the `codebase of the QAP <https://...
workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['bias_corrected', 'out_file', 'out_mask', 'bias_image']), name='outputnode') inu_n4 = pe.Node( ...
<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(url, headers={}, params=None): """Tries to GET data from an endpoint using retries"""
param_string = _foursquare_urlencode(params) for i in xrange(NUM_REQUEST_RETRIES): try: try: response = requests.get(url, headers=headers, params=param_string, verify=VERIFY_SSL) return _process_response(response) except requests.exceptions.Reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post(url, headers={}, data=None, files=None): """Tries to POST data to an endpoint"""
try: response = requests.post(url, headers=headers, data=data, files=files, verify=VERIFY_SSL) return _process_response(response) except requests.exceptions.RequestException as e: _log_and_raise_exception('Error connecting with foursquare API', 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 _process_response(response): """Make the request and handle exception processing"""
# Read the response as JSON try: data = response.json() except ValueError: _log_and_raise_exception('Invalid response', response.text) # Default case, Got proper response if response.status_code == 200: return { 'headers': response.headers, 'data': data } return _raise_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raise_error_from_response(data): """Processes the response data"""
# Check the meta-data for why this request failed meta = data.get('meta') if meta: # Account for foursquare conflicts # see: https://developer.foursquare.com/overview/responses if meta.get('code') in (200, 409): return data exc = error_types.get(meta.get('errorType')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _foursquare_urlencode(query, doseq=0, safe_chars="&/,+"): """Gnarly hack because Foursquare doesn't properly handle standard url encoding"""
# Original doc: http://docs.python.org/2/library/urllib.html#urllib.urlencode # Works the same way as urllib.urlencode except two differences - # 1. it uses `quote()` instead of `quote_plus()` # 2. it takes an extra parameter called `safe_chars` which is a string # having the characters which 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 _attach_endpoints(self): """Dynamically attach endpoint callables to this client"""
for name, endpoint in inspect.getmembers(self): if inspect.isclass(endpoint) and issubclass(endpoint, self._Endpoint) and (endpoint is not self._Endpoint): endpoint_instance = endpoint(self.base_requester) setattr(self, endpoint_instance.endpoint, endpoint_instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword argumen...
self.registry.append((widget, basename, parameters))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterator(self): """ Execute the API request and return an iterator over the objects. This method does not use the query cache. """
for obj in (self.execute().json().get("items") or []): yield self.api_obj_class(self.api, obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(self): """ Get Kubernetes API version """
response = self.get(version="", base="/version") response.raise_for_status() data = response.json() return (data["major"], data["minor"])
<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_kwargs(self, **kwargs): """ Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API end...
version = kwargs.pop("version", "v1") if version == "v1": base = kwargs.pop("base", "/api") elif "/" in version: base = kwargs.pop("base", "/apis") else: if "base" not in kwargs: raise TypeError("unknown API version; base kwarg must be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, *args, **kwargs): """ Makes an API request based on arguments. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.request(*args, **self.get_kwargs(**kwargs))
<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(self, *args, **kwargs): """ Executes an HTTP GET. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.get(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self, *args, **kwargs): """ Executes an HTTP OPTIONS. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.options(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(self, *args, **kwargs): """ Executes an HTTP HEAD. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.head(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, *args, **kwargs): """ Executes an HTTP POST. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.post(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, *args, **kwargs): """ Executes an HTTP PUT. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.put(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(self, *args, **kwargs): """ Executes an HTTP PATCH. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.patch(*args, **self.get_kwargs(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, *args, **kwargs): """ Executes an HTTP DELETE. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """
return self.session.delete(*args, **self.get_kwargs(**kwargs))
<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_file(cls, filename, **kwargs): """ Creates an instance of the KubeConfig class from a kubeconfig file. :Parameters: - `filename`: The full path to the c...
filename = os.path.expanduser(filename) if not os.path.isfile(filename): raise exceptions.PyKubeError("Configuration file {} not found".format(filename)) with open(filename) as f: doc = yaml.safe_load(f.read()) self = cls(doc, **kwargs) self.filename = fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clusters(self): """ Returns known clusters by exposing as a read-only property. """
if not hasattr(self, "_clusters"): cs = {} for cr in self.doc["clusters"]: cs[cr["name"]] = c = copy.deepcopy(cr["cluster"]) if "server" not in c: c["server"] = "http://localhost" BytesOrFile.maybe_set(c, "certificate-a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def users(self): """ Returns known users by exposing as a read-only property. """
if not hasattr(self, "_users"): us = {} if "users" in self.doc: for ur in self.doc["users"]: us[ur["name"]] = u = copy.deepcopy(ur["user"]) BytesOrFile.maybe_set(u, "client-certificate") BytesOrFile.maybe_set(u,...