本文整理汇总了Python中nipype.utils.filemanip.fname_presuffix函数的典型用法代码示例。如果您正苦于以下问题:Python fname_presuffix函数的具体用法?Python fname_presuffix怎么用?Python fname_presuffix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fname_presuffix函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _list_outputs
def _list_outputs(self):
outputs = self.output_spec().get()
#if isdefined(self.inputs.output_csv_file):
#write to a csv file and assign a value to self.coherence_file (a
#file name + path)
#Always defined (the arrays):
outputs['coherence_array']=self.coherence
outputs['timedelay_array']=self.delay
#Conditional
if isdefined(self.inputs.output_csv_file) and hasattr(self,'coherence'):
# we need to make a function that we call here that writes the
# coherence values to this file "coherence_csv" and makes the
# time_delay csv file??
self._make_output_files()
outputs['coherence_csv']=fname_presuffix(self.inputs.output_csv_file,suffix='_coherence')
outputs['timedelay_csv']=fname_presuffix(self.inputs.output_csv_file,suffix='_delay')
if isdefined(self.inputs.output_figure_file) and hasattr(self,
'coherence'):
self._make_output_figures()
outputs['coherence_fig'] = fname_presuffix(self.inputs.output_figure_file,suffix='_coherence')
outputs['timedelay_fig'] = fname_presuffix(self.inputs.output_figure_file,suffix='_delay')
return outputs
示例2: fieldmap_prepare_files
def fieldmap_prepare_files(converted_files, rwv_rescale_intercept=0, rwv_rescale_slope=1):
if len(converted_files) == 0:
return "", ""
import nibabel as nb, numpy as np, os, re
from nipype.utils.filemanip import fname_presuffix
in_pattern = "(?P<data>\d{8})_(?P<time>\d{6})(?P<site>\d{3})S(?P<subj>\d{4})"
m = re.search(in_pattern, converted_files[0])
out_file = "./%(site)s_S_%(subj)s_%(data)s_%(time)s.nii.gz" % m.groupdict()
niis = [nb.load(f) for f in converted_files]
if not (rwv_rescale_intercept == 0 and rwv_rescale_intercept == 1):
datas = [nii.get_data() * rwv_rescale_slope + rwv_rescale_intercept for nii in niis]
else:
datas = [nii.get_data() for nii in niis]
if len(datas) == 2 and datas[0].ndim == 4 and datas[0].shape[3] == 2:
# pair of complex data
cplx1 = datas[0][..., 0] + 1j * datas[0][..., 1]
cplx2 = datas[1][..., 0] + 1j * datas[1][..., 1]
else:
return
phase_diff = np.mod(np.angle(cplx2) - np.angle(cplx1) + np.pi * 2, np.pi * 2)
# append a zero image for FUGUE
phase_diff = np.concatenate((phase_diff[..., np.newaxis], np.zeros(phase_diff.shape + (1,))), 3)
phase_diff = phase_diff.astype(np.float32)
mag1 = np.abs(cplx1).astype(np.float32)
phasediff_name = fname_presuffix(out_file, suffix="_phasediff", newpath=os.getcwd())
mag_name = fname_presuffix(out_file, suffix="_mag", newpath=os.getcwd())
nb.save(nb.Nifti1Image(phase_diff, niis[0].get_affine()), phasediff_name)
nb.save(nb.Nifti1Image(mag1, niis[0].get_affine()), mag_name)
return phasediff_name, mag_name
示例3: _list_outputs
def _list_outputs(self):
outputs = self._outputs().get()
jobtype = self.inputs.jobtype
if jobtype.startswith('est'):
outputs['normalization_parameters'] = []
for imgf in filename_to_list(self.inputs.source):
outputs['normalization_parameters'].append(fname_presuffix(imgf, suffix='_sn.mat', use_ext=False))
outputs['normalization_parameters'] = list_to_filename(outputs['normalization_parameters'])
if self.inputs.jobtype == "estimate":
if isdefined(self.inputs.apply_to_files):
outputs['normalized_files'] = self.inputs.apply_to_files
outputs['normalized_source'] = self.inputs.source
elif 'write' in self.inputs.jobtype:
outputs['normalized_files'] = []
if isdefined(self.inputs.apply_to_files):
filelist = filename_to_list(self.inputs.apply_to_files)
for f in filelist:
if isinstance(f, list):
run = [fname_presuffix(in_f, prefix=self.inputs.out_prefix) for in_f in f]
else:
run = [fname_presuffix(f, prefix=self.inputs.out_prefix)]
outputs['normalized_files'].extend(run)
if isdefined(self.inputs.source):
outputs['normalized_source'] = fname_presuffix(self.inputs.source, prefix=self.inputs.out_prefix)
return outputs
示例4: _list_outputs
def _list_outputs(self):
outputs = self._outputs().get()
if isdefined(self.inputs.in_files):
outputs["realignment_parameters"] = []
for imgf in self.inputs.in_files:
if isinstance(imgf, list):
tmp_imgf = imgf[0]
else:
tmp_imgf = imgf
outputs["realignment_parameters"].append(
fname_presuffix(tmp_imgf, prefix="rp_", suffix=".txt", use_ext=False)
)
if not isinstance(imgf, list) and func_is_3d(imgf):
break
if self.inputs.jobtype == "write" or self.inputs.jobtype == "estwrite":
if isinstance(self.inputs.in_files[0], list):
first_image = self.inputs.in_files[0][0]
else:
first_image = self.inputs.in_files[0]
outputs["mean_image"] = fname_presuffix(first_image, prefix="mean")
outputs["realigned_files"] = []
for imgf in filename_to_list(self.inputs.in_files):
realigned_run = []
if isinstance(imgf, list):
for inner_imgf in filename_to_list(imgf):
realigned_run.append(fname_presuffix(inner_imgf, prefix="r"))
else:
realigned_run = fname_presuffix(imgf, prefix="r")
outputs["realigned_files"].append(realigned_run)
return outputs
示例5: _list_outputs
def _list_outputs(self):
outputs = self._outputs().get()
jobtype = self.inputs.jobtype
if jobtype.startswith('est'):
outputs['normalization_parameters'] = []
for imgf in filename_to_list(self.inputs.source):
outputs['normalization_parameters'].append(fname_presuffix(imgf, suffix='_sn.mat', use_ext=False))
outputs['normalization_parameters'] = list_to_filename(outputs['normalization_parameters'])
if self.inputs.jobtype == "estimate":
if isdefined(self.inputs.apply_to_files):
outputs['normalized_files'] = self.inputs.apply_to_files
outputs['normalized_source'] = self.inputs.source
elif 'write' in self.inputs.jobtype:
outputs['normalized_files'] = []
if isdefined(self.inputs.apply_to_files):
for imgf in filename_to_list(self.inputs.apply_to_files):
outputs['normalized_files'].append(fname_presuffix(imgf, prefix='w'))
if isdefined(self.inputs.source):
outputs['normalized_source'] = []
for imgf in filename_to_list(self.inputs.source):
outputs['normalized_source'].append(fname_presuffix(imgf, prefix='w'))
return outputs
示例6: _list_outputs
def _list_outputs(self):
outputs = self.output_spec().get()
outfile = self.inputs.binary_file
if not isdefined(outfile):
if isdefined(self.inputs.out_type):
outfile = fname_presuffix(self.inputs.in_file,
newpath=os.getcwd(),
suffix='.'.join(('_thresh',
self.inputs.out_type)),
use_ext=False)
else:
outfile = fname_presuffix(self.inputs.in_file,
newpath=os.getcwd(),
suffix='_thresh')
outputs['binary_file'] = outfile
value = self.inputs.count_file
if isdefined(value):
if isinstance(value, bool):
if value:
outputs['count_file'] = fname_presuffix(self.inputs.in_file,
suffix='_count.txt',
newpath=os.getcwd(),
use_ext=False)
else:
outputs['count_file'] = value
return outputs
示例7: _list_outputs
def _list_outputs(self):
outputs = self.output_spec().get()
_in = self.inputs
if isdefined(_in.out_reg_file):
outputs["out_reg_file"] = op.abspath(_in.out_reg_file)
elif _in.source_file:
suffix = "_bbreg_%s.dat" % _in.subject_id
outputs["out_reg_file"] = fname_presuffix(_in.source_file, suffix=suffix, use_ext=False)
if isdefined(_in.registered_file):
if isinstance(_in.registered_file, bool):
outputs["registered_file"] = fname_presuffix(_in.source_file, suffix="_bbreg")
else:
outputs["registered_file"] = op.abspath(_in.registered_file)
if isdefined(_in.out_fsl_file):
if isinstance(_in.out_fsl_file, bool):
suffix = "_bbreg_%s.mat" % _in.subject_id
out_fsl_file = fname_presuffix(_in.source_file, suffix=suffix, use_ext=False)
outputs["out_fsl_file"] = out_fsl_file
else:
outputs["out_fsl_file"] = op.abspath(_in.out_fsl_file)
outputs["min_cost_file"] = outputs["out_reg_file"] + ".mincost"
return outputs
示例8: _list_outputs
def _list_outputs(self):
outputs = self._outputs().get()
if isdefined(self.inputs.in_files):
outputs['realignment_parameters'] = []
for imgf in self.inputs.in_files:
if isinstance(imgf,list):
tmp_imgf = imgf[0]
else:
tmp_imgf = imgf
outputs['realignment_parameters'].append(fname_presuffix(tmp_imgf,
prefix='rp_',
suffix='.txt',
use_ext=False))
if not isinstance(imgf,list) and func_is_3d(imgf):
break;
#if self.inputs.jobtype == "write" or self.inputs.jobtype == "estwrite":
if isinstance(self.inputs.in_files[0], list):
first_image = self.inputs.in_files[0][0]
else:
first_image = self.inputs.in_files[0]
outputs['mean_image'] = fname_presuffix(first_image, prefix='meanu')
outputs['realigned_files'] = []
# get prefix for new files, or default 'u'
file_prefix = self.inputs.write_prefix or 'u'
for imgf in filename_to_list(self.inputs.in_files):
realigned_run = []
if isinstance(imgf,list):
for inner_imgf in filename_to_list(imgf):
realigned_run.append(fname_presuffix(inner_imgf, prefix=file_prefix))
else:
realigned_run = fname_presuffix(imgf, prefix=file_prefix)
outputs['realigned_files'].append(realigned_run)
return outputs
示例9: _make_output_figures
def _make_output_figures(self):
"""
Generate the desired figure and save the files according to
self.inputs.output_figure_file
"""
if self.inputs.figure_type == 'matrix':
fig_coh = viz.drawmatrix_channels(self.coherence,
channel_names=self.ROIs,
color_anchor=0)
fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
suffix='_coherence'))
fig_dt = viz.drawmatrix_channels(self.delay,
channel_names=self.ROIs,
color_anchor=0)
fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
suffix='_delay'))
else:
fig_coh = viz.drawgraph_channels(self.coherence,
channel_names=self.ROIs)
fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
suffix='_coherence'))
fig_dt = viz.drawgraph_channels(self.delay,
channel_names=self.ROIs)
fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
suffix='_delay'))
示例10: export_graph
def export_graph(graph_in, base_dir=None, show=False, use_execgraph=False,
show_connectinfo=False, dotfilename='graph.dot', format='png',
simple_form=True):
""" Displays the graph layout of the pipeline
This function requires that pygraphviz and matplotlib are available on
the system.
Parameters
----------
show : boolean
Indicate whether to generate pygraphviz output fromn
networkx. default [False]
use_execgraph : boolean
Indicates whether to use the specification graph or the
execution graph. default [False]
show_connectioninfo : boolean
Indicates whether to show the edge data on the graph. This
makes the graph rather cluttered. default [False]
"""
graph = deepcopy(graph_in)
if use_execgraph:
graph = generate_expanded_graph(graph)
logger.debug('using execgraph')
else:
logger.debug('using input graph')
if base_dir is None:
base_dir = os.getcwd()
if not os.path.exists(base_dir):
os.makedirs(base_dir)
outfname = fname_presuffix(dotfilename,
suffix='_detailed.dot',
use_ext=False,
newpath=base_dir)
logger.info('Creating detailed dot file: %s' % outfname)
_write_detailed_dot(graph, outfname)
cmd = 'dot -T%s -O %s' % (format, outfname)
res = CommandLine(cmd).run()
if res.runtime.returncode:
logger.warn('dot2png: %s', res.runtime.stderr)
pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form)
outfname = fname_presuffix(dotfilename,
suffix='.dot',
use_ext=False,
newpath=base_dir)
nx.write_dot(pklgraph, outfname)
logger.info('Creating dot file: %s' % outfname)
cmd = 'dot -T%s -O %s' % (format, outfname)
res = CommandLine(cmd).run()
if res.runtime.returncode:
logger.warn('dot2png: %s', res.runtime.stderr)
if show:
pos = nx.graphviz_layout(pklgraph, prog='dot')
nx.draw(pklgraph, pos)
if show_connectinfo:
nx.draw_networkx_edge_labels(pklgraph, pos)
示例11: test_fname_presuffix
def test_fname_presuffix():
fname = 'foo.nii'
pth = fname_presuffix(fname, 'pre_', '_post', '/tmp')
yield assert_equal, pth, '/tmp/pre_foo_post.nii'
fname += '.gz'
pth = fname_presuffix(fname, 'pre_', '_post', '/tmp')
yield assert_equal, pth, '/tmp/pre_foo_post.nii.gz'
pth = fname_presuffix(fname, 'pre_', '_post', '/tmp', use_ext=False)
yield assert_equal, pth, '/tmp/pre_foo_post'
示例12: _run_interface
def _run_interface(self, runtime):
in_files = self.inputs.in_files
if not isinstance(in_files, list):
in_files = [self.inputs.in_files]
# Generate output average name early
self._results['out_avg'] = fname_presuffix(self.inputs.in_files[0],
suffix='_avg', newpath=runtime.cwd)
if self.inputs.to_ras:
in_files = [reorient(inf, newpath=runtime.cwd)
for inf in in_files]
if len(in_files) == 1:
filenii = nb.load(in_files[0])
filedata = filenii.get_data()
# magnitude files can have an extra dimension empty
if filedata.ndim == 5:
sqdata = np.squeeze(filedata)
if sqdata.ndim == 5:
raise RuntimeError('Input image (%s) is 5D' % in_files[0])
else:
in_files = [fname_presuffix(in_files[0], suffix='_squeezed',
newpath=runtime.cwd)]
nb.Nifti1Image(sqdata, filenii.get_affine(),
filenii.get_header()).to_filename(in_files[0])
if np.squeeze(nb.load(in_files[0]).get_data()).ndim < 4:
self._results['out_file'] = in_files[0]
self._results['out_avg'] = in_files[0]
# TODO: generate identity out_mats and zero-filled out_movpar
return runtime
in_files = in_files[0]
else:
magmrg = fsl.Merge(dimension='t', in_files=self.inputs.in_files)
in_files = magmrg.run().outputs.merged_file
mcflirt = fsl.MCFLIRT(cost='normcorr', save_mats=True, save_plots=True,
ref_vol=0, in_file=in_files)
mcres = mcflirt.run()
self._results['out_mats'] = mcres.outputs.mat_file
self._results['out_movpar'] = mcres.outputs.par_file
self._results['out_file'] = mcres.outputs.out_file
hmcnii = nb.load(mcres.outputs.out_file)
hmcdat = hmcnii.get_data().mean(axis=3)
if self.inputs.zero_based_avg:
hmcdat -= hmcdat.min()
nb.Nifti1Image(
hmcdat, hmcnii.get_affine(), hmcnii.get_header()).to_filename(
self._results['out_avg'])
return runtime
示例13: _list_outputs
def _list_outputs(self):
outputs = self.output_spec().get()
outputs['out_reg_file'] = self.inputs.out_reg_file
if not isdefined(self.inputs.out_reg_file) and self.inputs.source_file:
outputs['out_reg_file'] = fname_presuffix(self.inputs.source_file,
suffix='_bbreg_%s.dat'%self.inputs.subject_id,
use_ext=False)
if isdefined(self.inputs.registered_file):
outputs['registered_file'] = self.inputs.registered_file
if isinstance(self.inputs.registered_file, bool):
outputs['registered_file'] = fname_presuffix(self.inputs.source_file,suffix='_bbreg')
return outputs
示例14: _tpm2roi
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 from a tissue probability map
"""
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_presuffix(in_mask, suffix='_eroded',
newpath=newpath)
mask_img = nb.load(in_mask)
mask_data = mask_img.get_data().astype(np.uint8)
if mask_erosion_mm:
iter_n = max(int(mask_erosion_mm / max(mask_img.header.get_zooms())), 1)
mask_data = nd.binary_erosion(mask_data, iterations=iter_n)
else:
orig_vol = np.sum(mask_data > 0)
while np.sum(mask_data > 0) / orig_vol > mask_erosion_prop:
mask_data = nd.binary_erosion(mask_data, iterations=1)
# Store mask
eroded = nb.Nifti1Image(mask_data, mask_img.affine, mask_img.header)
eroded.set_data_dtype(np.uint8)
eroded.to_filename(eroded_mask_file)
# Mask TPM data (no effect if not eroded)
roi_mask[~mask_data] = 0
# shrinking
erode_out = (erosion_mm is not None and erosion_mm > 0 or
erosion_prop is not None and erosion_prop < 1)
if erode_out:
if erosion_mm:
iter_n = max(int(erosion_mm / max(tpm_img.header.get_zooms())), 1)
iter_n = int(erosion_mm / max(tpm_img.header.get_zooms()))
roi_mask = nd.binary_erosion(roi_mask, iterations=iter_n)
else:
orig_vol = np.sum(roi_mask > 0)
while np.sum(roi_mask > 0) / orig_vol > erosion_prop:
roi_mask = nd.binary_erosion(roi_mask, iterations=1)
# Create image to resample
roi_fname = fname_presuffix(in_tpm, suffix='_roi', newpath=newpath)
roi_img = nb.Nifti1Image(roi_mask, tpm_img.affine, tpm_img.header)
roi_img.set_data_dtype(np.uint8)
roi_img.to_filename(roi_fname)
return roi_fname, eroded_mask_file or in_mask
示例15: _list_outputs
def _list_outputs(self):
out_prefix = self.inputs.out_prefix
output_type = self.inputs.output_type
outputs = self.output_spec().get()
outputs['B0'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_b0.'+ output_type))
outputs['DWI'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_dwi.'+ output_type))
outputs['max'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_max.'+ output_type))
outputs['ODF'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_odf.'+ output_type))
if isdefined(self.inputs.output_entropy):
outputs['entropy'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_entropy.'+ output_type))
return outputs