def cmdline(self): cmd = super(StructuralReference, self).cmdline if len(self.inputs.in_files) > 1: return cmd img = nb.load(self.inputs.in_files[0]) if len(img.shape) > 3 and img.shape[3] > 1: return cmd out_file = self._list_outputs()['out_file'] copyfile(self.inputs.in_files[0], out_file) return "echo Only one time point!"
def _copy_any(src, dst): src_isgz = src.endswith('.gz') dst_isgz = dst.endswith('.gz') if src_isgz == dst_isgz: copyfile(src, dst, copy=True, use_hardlink=True) return False # Make sure we do not reuse the hardlink later # Unlink target (should not exist) if os.path.exists(dst): os.unlink(dst) src_open = gzip.open if src_isgz else open dst_open = gzip.open if dst_isgz else open with src_open(src, 'rb') as f_in: with dst_open(dst, 'wb') as f_out: copyfileobj(f_in, f_out) return True
def inject_skullstripped(subjects_dir, subject_id, skullstripped): mridir = op.join(subjects_dir, subject_id, 'mri') t1 = op.join(mridir, 'T1.mgz') bm_auto = op.join(mridir, 'brainmask.auto.mgz') bm = op.join(mridir, 'brainmask.mgz') if not op.exists(bm_auto): img = nb.load(t1) mask = nb.load(skullstripped) bmask = new_img_like(mask, mask.get_data() > 0) resampled_mask = resample_to_img(bmask, img, 'nearest') masked_image = new_img_like(img, img.get_data() * resampled_mask.get_data()) masked_image.to_filename(bm_auto) if not op.exists(bm): copyfile(bm_auto, bm, copy=True, use_hardlink=True) return subjects_dir, subject_id
def index(self, config): fig_dir = 'figures' subject_dir = self.root.split('/')[-1] subject = re.search('^(?P<subject_id>sub-[a-zA-Z0-9]+)$', subject_dir).group() svg_dir = os.path.join(self.out_dir, 'fmriprep', subject, fig_dir) os.makedirs(svg_dir, exist_ok=True) reportlet_list = list(sorted([str(f) for f in Path(self.root).glob('**/*.*')])) for subrep_cfg in config: reportlets = [] for reportlet_cfg in subrep_cfg['reportlets']: rlet = Reportlet(**reportlet_cfg) for src in reportlet_list: ext = src.split('.')[-1] if rlet.file_pattern.search(src): contents = None if ext == 'html': with open(src) as fp: contents = fp.read().strip() elif ext == 'svg': fbase = os.path.basename(src) copyfile(src, os.path.join(svg_dir, fbase), copy=True, use_hardlink=True) contents = os.path.join(subject, fig_dir, fbase) if contents: rlet.source_files.append(src) rlet.contents.append(contents) if rlet.source_files: reportlets.append(rlet) if reportlets: sub_report = SubReport( subrep_cfg['name'], reportlets=reportlets, title=subrep_cfg.get('title')) self.sections.append(order_by_run(sub_report)) error_dir = os.path.join(self.out_dir, "fmriprep", subject, 'log', self.run_uuid) if os.path.isdir(error_dir): self.index_error_dir(error_dir)
def inject_skullstripped(subjects_dir, subject_id, skullstripped): import os import nibabel as nib from nilearn.image import resample_to_img, new_img_like from niworkflows.nipype.utils.filemanip import copyfile mridir = os.path.join(subjects_dir, subject_id, 'mri') t1 = os.path.join(mridir, 'T1.mgz') bm_auto = os.path.join(mridir, 'brainmask.auto.mgz') bm = os.path.join(mridir, 'brainmask.mgz') if not os.path.exists(bm_auto): img = nib.load(t1) mask = nib.load(skullstripped) bmask = new_img_like(mask, mask.get_data() > 0) resampled_mask = resample_to_img(bmask, img, 'nearest') masked_image = new_img_like( img, img.get_data() * resampled_mask.get_data()) masked_image.to_filename(bm_auto) if not os.path.exists(bm): copyfile(bm_auto, bm, copy=True, use_hardlink=True) return subjects_dir, subject_id
def _run_interface(self, runtime): # Load images, orient as RAS, collect shape and zoom data in_names = np.array(self.inputs.t1w_list) orig_imgs = np.vectorize(nb.load)(in_names) reoriented = np.vectorize(nb.as_closest_canonical)(orig_imgs) all_zooms = np.array([img.header.get_zooms()[:3] for img in reoriented]) all_shapes = np.array([img.shape for img in reoriented]) # Identify images that would require excessive up-sampling valid = self._prune_zooms(all_zooms, self.inputs.max_scale) dropped_images = in_names[~valid] # Ignore dropped images valid_fnames = in_names[valid] valid_imgs = orig_imgs[valid] reoriented = reoriented[valid] # Set target shape information target_zooms = all_zooms[valid].min(axis=0) target_shape = all_shapes[valid].max(axis=0) target_span = target_shape * target_zooms out_names = [] for img, orig, fname in zip(reoriented, valid_imgs, valid_fnames): zooms = np.array(img.header.get_zooms()[:3]) shape = np.array(img.shape) xyz_unit = img.header.get_xyzt_units()[0] if xyz_unit == 'unknown': # Common assumption; if we're wrong, unlikely to be the only thing that breaks xyz_unit = 'mm' # Set a 0.05mm threshold to performing rescaling atol = {'meter': 5e-5, 'mm': 0.05, 'micron': 50}[xyz_unit] # Rescale => change zooms # Resize => update image dimensions rescale = not np.allclose(zooms, target_zooms, atol=atol) resize = not np.all(shape == target_shape) if rescale or resize: target_affine = np.eye(4, dtype=img.affine.dtype) if rescale: scale_factor = target_zooms / zooms target_affine[:3, :3] = img.affine[:3, :3].dot(np.diag(scale_factor)) else: target_affine[:3, :3] = img.affine[:3, :3] if resize: # The shift is applied after scaling. # Use a proportional shift to maintain relative position in dataset size_factor = target_span / (zooms * shape) # Use integer shifts to avoid unnecessary interpolation offset = (img.affine[:3, 3] * size_factor - img.affine[:3, 3]).astype(int) target_affine[:3, 3] = img.affine[:3, 3] + offset else: target_affine[:3, 3] = img.affine[:3, 3] data = nli.resample_img(img, target_affine, target_shape).get_data() img = img.__class__(data, target_affine, img.header) out_name = fname_presuffix(fname, suffix='_ras', newpath=runtime.cwd) # Image may be reoriented, rescaled, and/or resized if img is not orig: img.to_filename(out_name) else: copyfile(fname, out_name, copy=True, use_hardlink=True) out_names.append(out_name) self._results['t1w_list'] = out_names # Create report segment = self._generate_segment(dropped_images, target_shape, target_zooms) out_report = os.path.join(runtime.cwd, 'report.html') with open(out_report, 'w') as fobj: fobj.write(segment) self._results['out_report'] = out_report return runtime