本文整理汇总了Python中nipype.utils.misc.package_check函数的典型用法代码示例。如果您正苦于以下问题:Python package_check函数的具体用法?Python package_check怎么用?Python package_check使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了package_check函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nlmeans_proxy
def nlmeans_proxy(in_file, settings,
noise_mask=None, out_file=None):
"""
Uses non-local means to denoise 4D datasets
"""
package_check('dipy', version='0.8.0.dev')
from dipy.denoise.nlmeans import nlmeans
if out_file is None:
fname, fext = op.splitext(op.basename(in_file))
if fext == '.gz':
fname, fext2 = op.splitext(fname)
fext = fext2 + fext
out_file = op.abspath('./%s_denoise%s' % (fname, fext))
img = nb.load(in_file)
hdr = img.get_header()
data = img.get_data()
aff = img.get_affine()
nmask = data[..., 0] > 80
if noise_mask is not None:
nmask = noise_mask > 0
sigma = np.std(data[nmask == 1])
den = nlmeans(data, sigma, **settings)
nb.Nifti1Image(den.astype(hdr.get_data_dtype()), aff,
hdr).to_filename(out_file)
return out_file, sigma
示例2: skip_if_no_package
def skip_if_no_package(*args, **kwargs):
"""Raise SkipTest if package_check fails
Parameters
----------
*args Positional parameters passed to `package_check`
*kwargs Keyword parameters passed to `package_check`
"""
package_check(exc_failed_import=SkipTest, exc_failed_check=SkipTest, *args, **kwargs)
示例3: verify_packages
def verify_packages(application='AutoWorkup'):
package_version = [
('nipype', '0.9'),
('numpy', '1.8'),
('scipy', '0.13'),
('networkx', '1.8'),
# ('IPython', '1.2'),
# ('SimpleITK', '0.7')
]
for item in package_version:
package_check(*item, app=application)
示例4: verify_packages
def verify_packages(application="AutoWorkup"):
"""
This function...
:param application:
:return:
"""
package_version = [
("nipype", "0.9"),
("numpy", "1.8"),
("scipy", "0.13"),
("networkx", "1.8"),
# ('IPython', '1.2'),
# ('SimpleITK', '0.7')
]
for item in package_version:
package_check(*item, app=application)
示例5: package_check
import nipype.interfaces.freesurfer as fs # freesurfer
import nipype.interfaces.mrtrix as mrtrix
import nipype.algorithms.misc as misc
import nipype.interfaces.cmtk as cmtk
import nipype.interfaces.dipy as dipy
import inspect
import os, os.path as op # system functions
from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline
from nipype.workflows.dmri.camino.connectivity_mapping import select_aparc_annot
from nipype.utils.misc import package_check
import warnings
from nipype.workflows.dmri.connectivity.nx import create_networkx_pipeline, create_cmats_to_csv_pipeline
from nipype.workflows.smri.freesurfer import create_tessellation_flow
try:
package_check("cmp")
except Exception, e:
warnings.warn("cmp not installed")
else:
import cmp
"""
This needs to point to the freesurfer subjects directory (Recon-all must have been run on subj1 from the FSL course data)
Alternatively, the reconstructed subject data can be downloaded from:
* http://dl.dropbox.com/u/315714/subj1.zip
"""
subjects_dir = op.abspath(op.join(op.curdir, "./subjects"))
fs.FSCommand.set_default_subjects_dir(subjects_dir)
示例6: import
# vi: set ft=python sts=4 ts=4 sw=4 et:
from nipype.interfaces.base import (BaseInterface, BaseInterfaceInputSpec, traits,
File, TraitedSpec, InputMultiPath,
OutputMultiPath, isdefined)
import os.path as op
import numpy as np
import networkx as nx
from nipype.utils.misc import package_check
import warnings
from ... import logging
iflogger = logging.getLogger('interface')
have_cv = True
try:
package_check('cviewer')
except Exception, e:
have_cv = False
else:
import cviewer.libs.pyconto.groupstatistics.nbs as nbs
def ntwks_to_matrices(in_files, edge_key):
first = nx.read_gpickle(in_files[0])
files = len(in_files)
nodes = len(first.nodes())
matrix = np.zeros((nodes, nodes, files))
for idx, name in enumerate(in_files):
graph = nx.read_gpickle(name)
for u, v, d in graph.edges(data=True):
graph[u][v]['weight'] = d[edge_key] # Setting the edge requested edge value as weight value
示例7: MasterProcessingController
def MasterProcessingController(argv=None):
import argparse
import configparser
import csv
import string
if argv == None:
argv = sys.argv
# Create and parse input arguments
parser = argparse.ArgumentParser(description='Runs a mini version of BRAINSAutoWorkup')
group = parser.add_argument_group('Required')
group.add_argument('-pe', action="store", dest='processingEnvironment', required=True,
help='The name of the processing environment to use from the config file')
group.add_argument('-wfrun', action="store", dest='wfrun', required=True,
help='The name of the workflow running plugin to use')
group.add_argument('-subject', action="store", dest='subject', required=True,
help='The name of the subject to process')
group.add_argument('-ExperimentConfig', action="store", dest='ExperimentConfig', required=True,
help='The path to the file that describes the entire experiment')
parser.add_argument('-rewrite_datasinks', action='store_true', default=False,
help='Use if the datasinks should be forced rerun.\nDefault: value in configuration file')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
args = parser.parse_args()
config = configparser.ConfigParser(allow_no_value=True)
config.read(args.ExperimentConfig)
# Pipeline-specific information
GLOBAL_DATA_SINK_REWRITE = setDataSinkRewriteValue(args.rewrite_datasinks,
config.getboolean('NIPYPE', 'GLOBAL_DATA_SINK_REWRITE'))
experiment = get_experiment_settings(config)
# Platform specific information
environment = get_environment_settings(config)
if environment['cluster']:
cluster = get_cluster_settings(config)
sys.path = environment('PYTHONPATH')
os.environ['PATH'] = ':'.join(environment['PATH'])
# Virtualenv
if not environment['virtualenv_dir'] is None:
print("Loading virtualenv_dir...")
execfile(environment['virtualenv_dir'], dict(__file__=environment['virtualenv_dir']))
###### Now ensure that all the required packages can be read in from this custom path
# \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
# print sys.path
## Check to ensure that SimpleITK can be found
import SimpleITK as sitk
from nipype import config # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
config.enable_debug_mode() # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
# config.enable_provenance()
##############################################################################
from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory
from nipype.interfaces.base import traits, isdefined, BaseInterface
from nipype.interfaces.utility import Merge, Split, Function, Rename, IdentityInterface
import nipype.interfaces.io as nio # Data i/o
import nipype.pipeline.engine as pe # pypeline engine
from nipype.interfaces.freesurfer import ReconAll
from nipype.utils.misc import package_check
# package_check('nipype', '5.4', 'tutorial1') ## HACK: Check nipype version
package_check('numpy', '1.3', 'tutorial1')
package_check('scipy', '0.7', 'tutorial1')
package_check('networkx', '1.0', 'tutorial1')
package_check('IPython', '0.10', 'tutorial1')
try:
verify_empty_freesurfer_env()
except EnvironmentError:
raise
# Define platform specific output write paths
if not os.path.exists(experiment['output_cache']):
os.makedirs(experiment['output_cache'])
if not os.path.exists(experiment['output_results']):
os.makedirs(experiment['output_results'])
if 'input_results' in list(experiment.keys()):
assert os.path.exists(
experiment['input_results']), "The previous experiment directory does not exist: {0}".format(
experiment['input_results'])
# \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
# Define platform specific output write paths
mountPrefix = expConfig.get(input_arguments.processingEnvironment, 'MOUNTPREFIX')
BASEOUTPUTDIR = expConfig.get(input_arguments.processingEnvironment, 'BASEOUTPUTDIR')
ExperimentBaseDirectoryPrefix = os.path.realpath(os.path.join(BASEOUTPUTDIR, ExperimentName))
ExperimentBaseDirectoryCache = ExperimentBaseDirectoryPrefix + "_CACHE"
ExperimentBaseDirectoryResults = ExperimentBaseDirectoryPrefix + "_Results"
if not os.path.exists(ExperimentBaseDirectoryCache):
os.makedirs(ExperimentBaseDirectoryCache)
if not os.path.exists(ExperimentBaseDirectoryResults):
os.makedirs(ExperimentBaseDirectoryResults)
if not PreviousExperimentName is None:
PreviousBaseDirectoryPrefix = os.path.realpath(os.path.join(BASEOUTPUTDIR, PreviousExperimentName))
PreviousBaseDirectoryResults = PreviousBaseDirectoryPrefix + "_Results"
assert os.path.exists(
PreviousBaseDirectoryResults), "The previous experiment directory does not exist: {0}".format(
PreviousBaseDirectoryResults)
else:
PreviousBaseDirectoryResults = None
#.........这里部分代码省略.........
示例8: package_check
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Utility routines for workflow graphs
"""
from copy import deepcopy
from glob import glob
import logging
import os
import re
import numpy as np
from nipype.utils.misc import package_check
package_check('networkx', '1.3')
import networkx as nx
from nipype.interfaces.base import CommandLine, isdefined, Undefined
from nipype.utils.filemanip import fname_presuffix, FileNotFoundError,\
filename_to_list
from nipype.utils.config import config
from nipype.utils.misc import create_function_from_source
from nipype.interfaces.utility import IdentityInterface
logger = logging.getLogger('workflow')
try:
dfs_preorder = nx.dfs_preorder
except AttributeError:
dfs_preorder = nx.dfs_preorder_nodes
logger.debug('networkx 1.4 dev or higher detected')
示例9: package_check
import os
import nibabel as nb
import numpy as np
from nipype.utils.misc import package_check
package_check('nipy')
from nipy.labs.mask import compute_mask
from nipype.interfaces.base import (TraitedSpec, BaseInterface, traits,
BaseInterfaceInputSpec, isdefined, File)
class ComputeMaskInputSpec(BaseInterfaceInputSpec):
mean_volume = File(exists=True, mandatory=True, desc="mean EPI image, used to compute the threshold for the mask")
reference_volume = File(exists=True, desc="reference volume used to compute the mask. If none is give, the \
mean volume is used.")
m = traits.Float(desc="lower fraction of the histogram to be discarded")
M = traits.Float(desc="upper fraction of the histogram to be discarded")
cc = traits.Bool(desc="if True, only the largest connect component is kept")
class ComputeMaskOutputSpec(TraitedSpec):
brain_mask = File(exists=True)
class ComputeMask(BaseInterface):
input_spec = ComputeMaskInputSpec
output_spec = ComputeMaskOutputSpec
def _run_interface(self, runtime):
args = {}
for key in [k for k,_ in self.inputs.items() if k not in BaseInterfaceInputSpec().trait_names()]:
示例10: package_check
import nipype.interfaces.freesurfer as fs # freesurfer
import nipype.interfaces.mrtrix as mrtrix
import nipype.algorithms.misc as misc
import nipype.interfaces.cmtk as cmtk
import nipype.interfaces.dipy as dipy
import inspect
import os, os.path as op # system functions
from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline
from nipype.workflows.dmri.camino.connectivity_mapping import select_aparc_annot
from nipype.utils.misc import package_check
import warnings
from nipype.workflows.dmri.connectivity.nx import create_networkx_pipeline, create_cmats_to_csv_pipeline
from nipype.workflows.smri.freesurfer import create_tessellation_flow
try:
package_check('cmp')
except Exception, e:
warnings.warn('cmp not installed')
else:
import cmp
"""
This needs to point to the freesurfer subjects directory (Recon-all must have been run on subj1 from the FSL course data)
Alternatively, the reconstructed subject data can be downloaded from:
* http://dl.dropbox.com/u/315714/subj1.zip
"""
subjects_dir = op.abspath(op.join(op.curdir,'./subjects'))
fs.FSCommand.set_default_subjects_dir(subjects_dir)
示例11: package_check
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Utility routines for workflow graphs
"""
from copy import deepcopy
from glob import glob
from collections import defaultdict
import os
import re
import numpy as np
from nipype.utils.misc import package_check
from nipype.external import six
package_check("networkx", "1.3")
import networkx as nx
from ..utils.filemanip import fname_presuffix, FileNotFoundError, filename_to_list, get_related_files
from ..utils.misc import create_function_from_source, str2bool
from ..interfaces.base import CommandLine, isdefined, Undefined, InterfaceResult
from ..interfaces.utility import IdentityInterface
from ..utils.provenance import ProvStore, pm, nipype_ns, get_id
from .. import logging, config
logger = logging.getLogger("workflow")
try:
dfs_preorder = nx.dfs_preorder
示例12: import
from nipype.interfaces.base import (
BaseInterface,
BaseInterfaceInputSpec,
traits,
File,
TraitedSpec,
InputMultiPath,
isdefined,
)
from nipype.utils.filemanip import split_filename
from nipype.utils.misc import package_check
have_cfflib = True
try:
package_check("cfflib")
except Exception as e:
have_cfflib = False
else:
import cfflib as cf
class CFFConverterInputSpec(BaseInterfaceInputSpec):
graphml_networks = InputMultiPath(File(exists=True), desc="list of graphML networks")
gpickled_networks = InputMultiPath(File(exists=True), desc="list of gpickled Networkx graphs")
gifti_surfaces = InputMultiPath(File(exists=True), desc="list of GIFTI surfaces")
gifti_labels = InputMultiPath(File(exists=True), desc="list of GIFTI labels")
nifti_volumes = InputMultiPath(File(exists=True), desc="list of NIFTI volumes")
tract_files = InputMultiPath(File(exists=True), desc="list of Trackvis fiber files")
示例13: MasterProcessingController
def MasterProcessingController(argv=None):
import argparse
import ConfigParser
import csv
import string
if argv == None:
argv = sys.argv
# Create and parse input arguments
parser = argparse.ArgumentParser(description='Runs a mini version of BRAINSAutoWorkup')
group = parser.add_argument_group('Required')
group.add_argument('-pe', action="store", dest='processingEnvironment', required=True,
help='The name of the processing environment to use from the config file')
group.add_argument('-wfrun', action="store", dest='wfrun', required=True,
help='The name of the workflow running plugin to use')
group.add_argument('-subject', action="store", dest='subject', required=True,
help='The name of the subject to process')
group.add_argument('-ExperimentConfig', action="store", dest='ExperimentConfig', required=True,
help='The path to the file that describes the entire experiment')
parser.add_argument('-rewrite_datasinks', action='store_true', default=False,
help='Use if the datasinks should be forced rerun.\nDefault: value in configuration file')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
input_arguments = parser.parse_args()
expConfig = ConfigParser.ConfigParser()
expConfig.read(input_arguments.ExperimentConfig)
# Pipeline-specific information
GLOBAL_DATA_SINK_REWRITE_FROM_CONFIG = expConfig.getboolean('PIPELINE', 'GLOBAL_DATA_SINK_REWRITE')
GLOBAL_DATA_SINK_REWRITE = setDataSinkRewriteValue(input_arguments.rewrite_datasinks, GLOBAL_DATA_SINK_REWRITE_FROM_CONFIG)
# Experiment specific information
subject_data_file = expConfig.get('EXPERIMENT_DATA', 'SESSION_DB')
ExperimentName = expConfig.get('EXPERIMENT_DATA', 'EXPERIMENTNAME')
if expConfig.has_option('EXPERIMENT_DATA', 'PREVIOUSEXPERIMENTNAME'):
PreviousExperimentName = expConfig.get('EXPERIMENT_DATA', 'PREVIOUSEXPERIMENTNAME')
else:
PreviousExperimentName = None
# Platform specific information
# Prepend the python search paths
PYTHON_AUX_PATHS = expConfig.get(input_arguments.processingEnvironment, 'PYTHON_AUX_PATHS')
PYTHON_AUX_PATHS = PYTHON_AUX_PATHS.split(':')
PYTHON_AUX_PATHS.extend(sys.path)
sys.path = PYTHON_AUX_PATHS
#####################################################################################
# Prepend the shell environment search paths
PROGRAM_PATHS = expConfig.get(input_arguments.processingEnvironment, 'PROGRAM_PATHS')
PROGRAM_PATHS = PROGRAM_PATHS.split(':')
PROGRAM_PATHS.extend(os.environ['PATH'].split(':'))
PROGRAM_PATHS = [os.path.dirname(__file__)] + PROGRAM_PATHS
print "Adding directory {0} to PATH...".format(os.path.dirname(__file__))
os.environ['PATH'] = ':'.join(PROGRAM_PATHS)
######################################################################################
# Get virtualenv source file
if expConfig.has_option(input_arguments.processingEnvironment, 'VIRTUALENV'):
print "Loading virtualenv..."
VIRTUALENV = expConfig.get(input_arguments.processingEnvironment, 'VIRTUALENV')
activate_this = os.path.join(VIRTUALENV, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
###### Now ensure that all the required packages can be read in from this custom path
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
# print sys.path
from nipype import config # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
config.enable_debug_mode() # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
##############################################################################
from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory
from nipype.interfaces.base import traits, isdefined, BaseInterface
from nipype.interfaces.utility import Merge, Split, Function, Rename, IdentityInterface
import nipype.interfaces.io as nio # Data i/o
import nipype.pipeline.engine as pe # pypeline engine
from nipype.interfaces.freesurfer import ReconAll
from nipype.utils.misc import package_check
# package_check('nipype', '5.4', 'tutorial1') ## HACK: Check nipype version
package_check('numpy', '1.3', 'tutorial1')
package_check('scipy', '0.7', 'tutorial1')
package_check('networkx', '1.0', 'tutorial1')
package_check('IPython', '0.10', 'tutorial1')
## Check to ensure that SimpleITK can be found
import SimpleITK as sitk
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
#####################################################################################
# FreeSurfer is extraordinarly finicky and is easily confused and incorrect.
# Force that all the FREESURFER env vars are set in subsequent scripts by
# ensuring that rough versions of these environmental variables are not
# set internal to this script.
prohibited_env_var_exists = False
for ENVVAR_TO_CHECK in ['FREESURFER_HOME', 'FSFAST_HOME', 'FSF_OUTPUT_FORMAT', 'SUBJECTS_DIR', 'MNI_DIR', 'FSL_DIR']:
if ENVVAR_TO_CHECK in os.environ:
prohibited_env_var_exists = True
print("ERROR: Environmental Variable {0}={1} exists. Please unset before continuing.".format(ENVVAR_TO_CHECK, os.environ[ENVVAR_TO_CHECK]))
if prohibited_env_var_exists:
sys.exit(-1)
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
# Define platform specific output write paths
mountPrefix = expConfig.get(input_arguments.processingEnvironment, 'MOUNTPREFIX')
#.........这里部分代码省略.........
示例14: main
def main(argv=None):
import argparse
import ConfigParser
import csv
import string
if argv == None:
argv = sys.argv
# Create and parse input arguments
parser = argparse.ArgumentParser(description='Runs a mini version of BRAINSAutoWorkup')
group = parser.add_argument_group('Required')
group.add_argument('-pe', action="store", dest='processingEnvironment', required=True,
help='The name of the processing environment to use from the config file')
group.add_argument('-wfrun', action="store", dest='wfrun', required=True,
help='The name of the workflow running plugin to use')
group.add_argument('-subject', action="store", dest='subject', required=True,
help='The name of the subject to process')
group.add_argument('-ExperimentConfig', action="store", dest='ExperimentConfig', required=True,
help='The path to the file that describes the entire experiment')
parser.add_argument('-doshort', action='store', dest='doshort', default=False, help='If not present, do long')
parser.add_argument('-rewrite_datasinks', action='store_true', default=False,
help='Use if the datasinks should be forced rerun.\nDefault: value in configuration file')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
input_arguments = parser.parse_args()
expConfig = ConfigParser.ConfigParser()
expConfig.read(input_arguments.ExperimentConfig)
# Pipeline-specific information
GLOBAL_DATA_SINK_REWRITE_FROM_CONFIG = expConfig.getboolean('PIPELINE', 'GLOBAL_DATA_SINK_REWRITE')
GLOBAL_DATA_SINK_REWRITE=setDataSinkRewriteValue(input_arguments.rewrite_datasinks, GLOBAL_DATA_SINK_REWRITE_FROM_CONFIG)
# Experiment specific information
subject_data_file = expConfig.get('EXPERIMENT_DATA', 'SESSION_DB')
ExperimentName = expConfig.get('EXPERIMENT_DATA', 'EXPERIMENTNAME')
WORKFLOW_COMPONENTS_STRING = expConfig.get('EXPERIMENT_DATA', 'WORKFLOW_COMPONENTS')
WORKFLOW_COMPONENTS = eval(WORKFLOW_COMPONENTS_STRING)
# Platform specific information
# Prepend the python search paths
PYTHON_AUX_PATHS = expConfig.get(input_arguments.processingEnvironment, 'PYTHON_AUX_PATHS')
PYTHON_AUX_PATHS = PYTHON_AUX_PATHS.split(':')
PYTHON_AUX_PATHS.extend(sys.path)
sys.path = PYTHON_AUX_PATHS
######################################################################################
###### Now ensure that all the required packages can be read in from this custom path
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
# print sys.path
from nipype import config # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
config.enable_debug_mode() # NOTE: This needs to occur AFTER the PYTHON_AUX_PATHS has been modified
##############################################################################
from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory
from nipype.interfaces.base import traits, isdefined, BaseInterface
from nipype.interfaces.utility import Merge, Split, Function, Rename, IdentityInterface
import nipype.interfaces.io as nio # Data i/o
import nipype.pipeline.engine as pe # pypeline engine
from nipype.interfaces.freesurfer import ReconAll
from nipype.utils.misc import package_check
# package_check('nipype', '5.4', 'tutorial1') ## HACK: Check nipype version
package_check('numpy', '1.3', 'tutorial1')
package_check('scipy', '0.7', 'tutorial1')
package_check('networkx', '1.0', 'tutorial1')
package_check('IPython', '0.10', 'tutorial1')
## Check to ensure that SimpleITK can be found
import SimpleITK as sitk
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
#####################################################################################
# FreeSurfer is extraordinarly finicky and is easily confused and incorrect.
# Force that all the FREESURFER env vars are set in subsequent scripts by
# ensuring that rough versions of these environmental variables are not
# set internal to this script.
prohibited_env_var_exists = False
for ENVVAR_TO_CHECK in ['FREESURFER_HOME','FSFAST_HOME','FSF_OUTPUT_FORMAT','SUBJECTS_DIR','MNI_DIR','FSL_DIR']:
if os.environ.has_key(ENVVAR_TO_CHECK):
prohibited_env_var_exists = True
print( "ERROR: Environmental Variable {0}={1} exists. Please unset before continuing.".format(ENVVAR_TO_CHECK,os.environ[ENVVAR_TO_CHECK]) )
if prohibited_env_var_exists:
sys.exit(-1)
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
#####################################################################################
# Prepend the shell environment search paths
PROGRAM_PATHS = expConfig.get(input_arguments.processingEnvironment, 'PROGRAM_PATHS')
PROGRAM_PATHS = PROGRAM_PATHS.split(':')
PROGRAM_PATHS.extend(os.environ['PATH'].split(':'))
os.environ['PATH'] = ':'.join(PROGRAM_PATHS)
# Define platform specific output write paths
mountPrefix = expConfig.get(input_arguments.processingEnvironment, 'MOUNTPREFIX')
BASEOUTPUTDIR = expConfig.get(input_arguments.processingEnvironment, 'BASEOUTPUTDIR')
ExperimentBaseDirectoryPrefix = os.path.realpath(os.path.join(BASEOUTPUTDIR, ExperimentName))
ExperimentBaseDirectoryCache = ExperimentBaseDirectoryPrefix + "_CACHE"
ExperimentBaseDirectoryResults = ExperimentBaseDirectoryPrefix + "_Results"
if not os.path.exists(ExperimentBaseDirectoryCache):
os.makedirs(ExperimentBaseDirectoryCache)
if not os.path.exists(ExperimentBaseDirectoryResults):
os.makedirs(ExperimentBaseDirectoryResults)
# Define workup common reference data sets
#.........这里部分代码省略.........
示例15: package_check
import os
import nibabel as nb
import numpy as np
from nipype.utils.misc import package_check
package_check("nipy")
from nipy.labs.mask import compute_mask
from nipype.interfaces.base import TraitedSpec, BaseInterface, traits, BaseInterfaceInputSpec
from nipype.interfaces.traits import File
from nipype.utils.misc import isdefined
class ComputeMaskInputSpec(BaseInterfaceInputSpec):
mean_volume = File(exists=True, mandatory=True, desc="mean EPI image, used to compute the threshold for the mask")
reference_volume = File(
exists=True,
desc="reference volume used to compute the mask. If none is give, the \
mean volume is used.",
)
m = traits.Float(desc="lower fraction of the histogram to be discarded")
M = traits.Float(desc="upper fraction of the histogram to be discarded")
cc = traits.Bool(desc="if True, only the largest connect component is kept")
class ComputeMaskOutputSpec(TraitedSpec):
brain_mask = File(exists=True)