Package mvpa :: Package misc :: Module cmdline
[hide private]
[frames] | no frames]

Source Code for Module mvpa.misc.cmdline

  1  #emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- 
  2  #ex: set sts=4 ts=4 sw=4 et: 
  3  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## 
  4  # 
  5  #   See COPYING file distributed along with the PyMVPA package for the 
  6  #   copyright and license terms. 
  7  # 
  8  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## 
  9  """Common functions and options definitions for command line 
 10   
 11  __docformat__ = 'restructuredtext' 
 12   
 13  Conventions: 
 14  Every option (instance of optparse.Option) has prefix "opt". Lists of options 
 15  has prefix opts (e.g. `opts.common`). 
 16   
 17  Option name should be camelbacked version of .dest for the option. 
 18  """ 
 19   
 20  # TODO? all options (opt*) might migrate to respective module? discuss 
 21  from optparse import OptionParser, Option, OptionGroup, OptionConflictError 
 22   
 23  # needed for verboseCallback 
 24  from mvpa.base import verbose, externals 
 25   
 26  # we need to make copies of the options if we place them into the 
 27  # groups, since otherwise it is impossible to use them without using 
 28  # the whole group. May be we should make some late creation of the 
 29  # groups -- ie only if user requests a group, options are added to it. 
 30  from mvpa.misc import copy 
 31   
32 -class Options(object):
33 """Just a convinience placeholder for all available options 34 """ 35 pass
36
37 -class OptionGroups(object):
38 """Group creation is delayed until instance is requested. 39 40 This allows to overcome the problem of poluting handled cmdline options 41 """ 42
43 - def __init__(self, parser):
44 self._d = {} 45 self._parser = parser
46
47 - def add(self, name, l, doc):
48 self._d[name] = (doc, l)
49
50 - def _getGroup(self, name):
51 try: 52 doc, l = self._d[name] 53 except KeyError: 54 raise ValueError, "No group with name %s" % name 55 opts = OptionGroup(self._parser, doc) 56 #opts.add_options(copy.deepcopy(l)) # may be copy? 57 try: 58 opts.add_options(l) 59 except OptionConflictError: 60 print "Problem addition options to the group '%s'. Most probably" \ 61 " the option was independently added already." % name 62 raise 63 return opts
64
65 - def __getattribute__(self, index):
66 if index[0] == '_': 67 return object.__getattribute__(self, index) 68 if self._d.has_key(index): 69 return self._getGroup(index) 70 return object.__getattribute__(self, index)
71 72 73 # TODO: try to make groups definition somewhat lazy, since now 74 # whenever a group is created, those parameters are already known by 75 # parser, although might not be listed in the list of used and not by 76 # --help. But their specification on cmdline doesn't lead to 77 # error/help msg. 78 # 79 # Conflict hanlder to resolve situation that we have the same option added 80 # to some group and also available 'freely' 81 # 82 parser = OptionParser(add_help_option=False, 83 conflict_handler="error") 84 85 86 opt = Options() 87 opts = OptionGroups(parser) 88 89 # 90 # Verbosity options 91 #
92 -def _verboseCallback(option, optstr, value, parser):
93 """Callback for -v|--verbose cmdline option 94 """ 95 verbose.level = value 96 optstr = optstr # pylint shut up 97 setattr(parser.values, option.dest, value)
98 99 opt.help = \ 100 Option("-h", "--help", "--sos", 101 action="help", 102 help="Show this help message and exit") 103 104 opt.verbose = \ 105 Option("-v", "--verbose", "--verbosity", 106 action="callback", callback=_verboseCallback, nargs=1, 107 type="int", dest="verbose", default=0, 108 help="Verbosity level of output") 109 """Pre-cooked `optparse`'s option to specify verbose level""" 110 111 commonopts_list = [opt.verbose, opt.help] 112 113 if __debug__: 114 from mvpa.base import debug 115
116 - def _debugCallback(option, optstr, value, parser):
117 """Callback for -d|--debug cmdline option 118 """ 119 if value == "list": 120 print "Registered debug IDs:" 121 keys = debug.registered.keys() 122 keys.sort() 123 for k in keys: 124 print "%-7s: %s" % (k, debug.registered[k]) 125 print "Use ALL: to enable all of the debug IDs listed above." 126 print "Use python regular expressions to select group. CLF.* will" \ 127 " enable all debug entries starting with CLF (e.g. CLFBIN, CLFMC)" 128 raise SystemExit, 0 129 130 optstr = optstr # pylint shut up 131 debug.setActiveFromString(value) 132 133 setattr(parser.values, option.dest, value)
134 135 136 optDebug = Option("-d", "--debug", 137 action="callback", callback=_debugCallback, 138 nargs=1, 139 type="string", dest="debug", default="", 140 help="Debug entries to report. " + 141 "Run with '-d list' to get a list of " + 142 "registered entries") 143 144 commonopts_list.append(optDebug) 145 146 opts.add("common", commonopts_list, "Common generic options") 147 148 # 149 # Classifiers options 150 # 151 opt.clf = \ 152 Option("--clf", 153 type="choice", dest="clf", 154 choices=['knn', 'svm', 'ridge', 'gpr', 'smlr'], default='svm', 155 help="Type of classifier to be used. Default: svm") 156 157 opt.radius = \ 158 Option("-r", "--radius", 159 action="store", type="float", dest="radius", 160 default=5.0, 161 help="Radius to be used (eg for the searchlight). Default: 5.0") 162 163 164 opt.knearestdegree = \ 165 Option("-k", "--k-nearest", 166 action="store", type="int", dest="knearestdegree", default=3, 167 help="Degree of k-nearest classifier. Default: 3") 168 169 opts.add('KNN', [opt.radius, opt.knearestdegree], "Specification of kNN") 170 171 172 opt.svm_C = \ 173 Option("-C", "--svm-C", 174 action="store", type="float", dest="svm_C", default=1.0, 175 help="C parameter for soft-margin C-SVM classification. " \ 176 "Default: 1.0") 177 178 opt.svm_nu = \ 179 Option("--nu", "--svm-nu", 180 action="store", type="float", dest="svm_nu", default=0.1, 181 help="nu parameter for soft-margin nu-SVM classification. " \ 182 "Default: 0.1") 183 184 opt.svm_gamma = \ 185 Option("--gamma", "--svm-gamma", 186 action="store", type="float", dest="svm_gamma", default=1.0, 187 help="gamma parameter for Gaussian kernel of RBF SVM. " \ 188 "Default: 1.0") 189 190 opts.add('SVM', [opt.svm_nu, opt.svm_C, opt.svm_gamma], "SVM specification") 191 192 opt.do_sweep = \ 193 Option("--sweep", 194 action="store_true", dest="do_sweep", 195 default=False, 196 help="Sweep through various classifiers") 197 198 # Crossvalidation options 199 200 opt.crossfolddegree = \ 201 Option("-c", "--crossfold", 202 action="store", type="int", dest="crossfolddegree", default=1, 203 help="Degree of N-fold crossfold. Default: 1") 204 205 opts.add('general', [opt.crossfolddegree], "Generalization estimates") 206 207 208 # preprocess options 209 210 opt.zscore = \ 211 Option("--zscore", 212 action="store_true", dest="zscore", default=0, 213 help="Enable zscoring of dataset samples. Default: Off") 214 215 opt.tr = \ 216 Option("--tr", 217 action="store", dest="tr", default=2.0, type='float', 218 help="fMRI volume repetition time. Default: 2.0") 219 220 opt.detrend = \ 221 Option("--detrend", 222 action="store_true", dest="detrend", default=0, 223 help="Do linear detrending. Default: Off") 224 225 opts.add('preproc', [opt.zscore, opt.tr, opt.detrend], "Preprocessing options") 226 227 228 # Wavelets options 229 if externals.exists('pywt'): 230 import pywt
231 - def _waveletFamilyCallback(option, optstr, value, parser):
232 """Callback for -w|--wavelet-family cmdline option 233 """ 234 wl_list = pywt.wavelist() 235 wl_list_str = ", ".join( 236 ['-1: None'] + ['%d:%s' % w for w in enumerate(wl_list)]) 237 if value == "list": 238 print "Available wavelet families: " + wl_list_str 239 raise SystemExit, 0 240 241 wl_family = value 242 try: 243 # may be int? ;-) 244 wl_family_index = int(value) 245 if wl_family_index >= 0: 246 try: 247 wl_family = wl_list[wl_family_index] 248 except IndexError: 249 print "Index is out of range. " + \ 250 "Following indexes with names are known: " + \ 251 wl_list_str 252 raise SystemExit, -1 253 else: 254 wl_family = 'None' 255 except ValueError: 256 pass 257 # Check the value 258 wl_family = wl_family.lower() 259 if wl_family == 'none': 260 wl_family = None 261 elif not wl_family in wl_list: 262 print "Uknown family '%s'. Known are %s" % (wl_family, ', '.join(wl_list)) 263 raise SystemExit, -1 264 # Store it in the parser 265 setattr(parser.values, option.dest, wl_family)
266 267 268 opt.wavelet_family = \ 269 Option("-w", "--wavelet-family", callback=_waveletFamilyCallback, 270 action="callback", type="string", dest="wavelet_family", 271 default='-1', 272 help="Wavelet family: string or index among the available. " + 273 "Run with '-w list' to see available families") 274 275 opt.wavelet_decomposition = \ 276 Option("-W", "--wavelet-decomposition", 277 action="store", type="choice", dest="wavelet_decomposition", 278 default='dwt', choices=['dwt', 'dwp'], 279 help="Wavelet decomposition: discrete wavelet transform "+ 280 "(dwt) or packet (dwp)") 281 282 opts.add('wavelet', [opt.wavelet_family, opt.wavelet_decomposition], 283 "Wavelets mappers") 284 285 286 # Box options 287 288 opt.boxlength = \ 289 Option("--boxlength", 290 action="store", dest="boxlength", default=1, type='int', 291 help="Length of the box in volumes (integer). Default: 1") 292 293 opt.boxoffset = \ 294 Option("--boxoffset", 295 action="store", dest="boxoffset", default=0, type='int', 296 help="Offset of the box from the event onset in volumes. Default: 0") 297 298 opts.add('box', [opt.boxlength, opt.boxoffset], "Box options") 299 300 301 # sample attributes 302 303 opt.chunk = \ 304 Option("--chunk", 305 action="store", dest="chunk", default='0', 306 help="Id of the data chunk. Default: 0") 307 308 opt.chunkLimits = \ 309 Option("--chunklimits", 310 action="store", dest="chunklimits", default=None, 311 help="Limit processing to a certain chunk of data given by start " \ 312 "and end volume number (including lower, excluding upper " \ 313 "limit). Numbering starts with zero.") 314 315 opts.add('chunk', [opt.chunk, opt.chunkLimits], "Chunk options AKA Sample attributes XXX") 316