parameter.py 16.5 KB
Newer Older
Jerome Mariette's avatar
Jerome Mariette committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Copyright (C) 2012 INRA
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import types
Jerome Mariette's avatar
Jerome Mariette committed
19
import datetime
Jerome Mariette's avatar
Jerome Mariette committed
20
import argparse
21
22
from argparse import _ensure_value
import copy as _copy
Jerome Mariette's avatar
Jerome Mariette committed
23
24
# import custom types
from workflows.types import *
Jerome Mariette's avatar
Jerome Mariette committed
25
26


Jerome Mariette's avatar
Jerome Mariette committed
27
class MultipleParameters(object):
28
    def __init__(self, types, required, choices, excludes, default, actions):
Jerome Mariette's avatar
Jerome Mariette committed
29
        self.types = types
30
        self.choices = choices
Jerome Mariette's avatar
Jerome Mariette committed
31
        self.excludes = excludes
32
        self.default = default
33
        self.actions = actions
Jerome Mariette's avatar
Jerome Mariette committed
34
        self.index = None
35
        self.required = required
Jerome Mariette's avatar
Jerome Mariette committed
36
        self.__name__ = "MultipleParameters"
37
        
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
38
39
40
41
42
43
    def get_help(self):
        help = " ("
        for flag in self.types.keys():
            help += flag + "=<" + self.types[flag].__name__.upper() + ">, "
        return help[:-2] + ")"
        
44
    def __call__(self, arg):
Jerome Mariette's avatar
Jerome Mariette committed
45
46
47
        parts = arg.split("=")
        if not self.types.has_key(parts[0]):
            raise argparse.ArgumentTypeError(parts[0] + " is an invalid flag! Available ones are: "+", ".join(self.types.keys()))
48
49
50
        if self.choices[parts[0]] != None:
            if parts[1] not in self.choices[parts[0]]:
                raise argparse.ArgumentTypeError("argument " + parts[0] + ": invalid choice: '" + parts[1] + "' (choose from " + ", ".join(self.choices[parts[0]]) + "))")
51
52
53
54
55
56
57
58
59
60
        
        if self.types[parts[0]] == types.BooleanType:
            return (parts[0], not self.default[parts[0]], self.required, self.excludes)
        else:
            try:
                value = self.types[parts[0]](parts[1])
            except:
                raise argparse.ArgumentTypeError("invalid " + self.types[parts[0]].__name__ + " value: '" + parts[1] + "' for sub parameter '" + parts[0] + "'")
        
            self.index = parts[0]
61
            return (parts[0], value, self.required, self.excludes, self.actions)
Jerome Mariette's avatar
Jerome Mariette committed
62

63
64
class MiltipleAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
65
66
67
68
69
70
71
        # what is commun within required and excludes
        exclusif_required = {}
        for exclude_group in values[0][3]:
            exclusif_required[exclude_group] = False
            for param in values[0][3][exclude_group]:
                if param in values[0][2]:
                    exclusif_required[exclude_group] = True
Jerome Mariette's avatar
Jerome Mariette committed
72
73
        given_params = []
        # first check for required parameters
74
75
        try:
            required = _copy.copy(values[0][2])
76
77
78
79
80
81
            # delete required that are exclusive
            for group in exclusif_required:
                if exclusif_required[group]:
                    for val in values[0][3][group]:
                        if val in required:
                            del required[required.index(val)]
82
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
83
                given_params.append(val[0])
84
85
86
87
88
                if val[0] in required:
                    del required[required.index(val[0])]
        except: pass
        if len(required) == 1: parser.error(", ".join(required) + " is a required parameter!")
        elif len(required) > 1: parser.error(", ".join(required) + " are required parameters!")
Jerome Mariette's avatar
Jerome Mariette committed
89
90
91
92
93
94
95
96
        # then for exclude ones    
        for exclude_group in values[0][3]:
            found = None
            for param in values[0][3][exclude_group]:
                if param in given_params and found != None:
                    parser.error("argument '" + found + "': not allowed with argument '" + param + "'")
                    break
                elif param in given_params: found = param
97
98
99
100
101
102
103
104
105
        
        # check for required exclusive if one of them is in
        if len(exclusif_required.keys()) > 0:
            for group in exclusif_required:
                if exclusif_required[group]:
                    rfound = False
                    for param in values[0][3][group]:
                        if param in given_params: rfound = True
            if not rfound: parser.error("one of the arguments: " + ", ".join(values[0][3][group]) + " is required")
106
        
Jerome Mariette's avatar
Jerome Mariette committed
107
        # if ok add the value
108
109
110
111
112
113
114
115
116
117
118
        final_hash, final_values = {}, []
        for value in values:
            if values[0][4][value[0]] == "append" and final_hash.has_key(value[0]):
                final_hash[value[0]].append(value[1])
            elif values[0][4][value[0]] == "append":
                final_hash[value[0]]= [value[1]]
            else:
                final_hash[value[0]]= value[1]
        for param in final_hash:
            final_values.append((param, final_hash[param]))
        setattr(namespace, self.dest, final_values)
119
120
121

class MiltipleAppendAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
122
123
124
125
126
127
128
        # what is commun within required and excludes
        exclusif_required = {}
        for exclude_group in values[0][3]:
            exclusif_required[exclude_group] = False
            for param in values[0][3][exclude_group]:
                if param in values[0][2]:
                    exclusif_required[exclude_group] = True
Jerome Mariette's avatar
Jerome Mariette committed
129
130
        given_params = []
        # first check for required parameters
131
132
        try:
            required = _copy.copy(values[0][2])
133
134
135
136
137
138
            # delete required that are exclusive
            for group in exclusif_required:
                if exclusif_required[group]:
                    for val in values[0][3][group]:
                        if val in required:
                            del required[required.index(val)]
139
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
140
                given_params.append(val[0])
141
142
143
144
145
                if val[0] in required:
                    del required[required.index(val[0])]
        except: pass
        if len(required) == 1: parser.error(", ".join(required) + " is a required parameter!")
        elif len(required) > 1: parser.error(", ".join(required) + " are required parameters!")
Jerome Mariette's avatar
Jerome Mariette committed
146
147
148
149
150
151
152
153
        # then for exclude ones    
        for exclude_group in values[0][3]:
            found = None
            for param in values[0][3][exclude_group]:
                if param in given_params and found != None:
                    parser.error("argument '" + found + "': not allowed with argument '" + param + "'")
                    break
                elif param in given_params: found = param
154
155
156
157
158
159
160
161
162
        
        # check for required exclusive if one of them is in
        if len(exclusif_required.keys()) > 0:
            for group in exclusif_required:
                if exclusif_required[group]:
                    rfound = False
                    for param in values[0][3][group]:
                        if param in given_params: rfound = True
            if not rfound: parser.error("one of the arguments: " + ", ".join(values[0][3][group]) + " is required")
Jerome Mariette's avatar
Jerome Mariette committed
163
        # if ok add the value
164
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
165
166
167
168
169
170
171
172
173
174
175
        final_hash, final_values = {}, []
        for value in values:
            if values[0][4][value[0]] == "append" and final_hash.has_key(value[0]):
                final_hash[value[0]].append(value[1])
            elif values[0][4][value[0]] == "append":
                final_hash[value[0]]= [value[1]]
            else:
                final_hash[value[0]]= value[1]
        for param in final_hash:
            final_values.append((param, final_hash[param]))
        items.append(final_values)
176
        setattr(namespace, self.dest, items)        
177
178
179


class AbstractParameter(object):
Jerome Mariette's avatar
Jerome Mariette committed
180
    
181
182
    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
                 flag=None, action="store", sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
183

Jerome Mariette's avatar
Jerome Mariette committed
184
185
        self.name = name
        self.help = help
186
        self.action = action
Jerome Mariette's avatar
Jerome Mariette committed
187
        self.nargs = None
188
189
190
        if sub_parameters:
            self.sub_parameters = sub_parameters
        else: self.sub_parameters = []
Jerome Mariette's avatar
Jerome Mariette committed
191
        self.group = group
192
193
194
195
196
        if flag == None:
            self.flag = "--"+name.replace("_", "-")
        else: self.flag = flag
        if display_name == None: 
            self.display_name = name.replace("_", " ").title()
Jerome Mariette's avatar
Jerome Mariette committed
197
        else: self.display_name = display_name
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
198
        self.required = required
199
        self.choices = choices
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
200

Jerome Mariette's avatar
Jerome Mariette committed
201
202
        if type == "date":
            self.type = date
Jerome Mariette's avatar
Jerome Mariette committed
203
        elif type == "multiple":
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
204
            self.type = "multiple"
Jerome Mariette's avatar
Jerome Mariette committed
205
206
        elif isinstance(type, types.FunctionType):
            self.type = type
Jerome Mariette's avatar
Jerome Mariette committed
207
208
209
        else:
            try: self.type = eval(type)
            except: self.type = types.StringType
Jerome Mariette's avatar
Jerome Mariette committed
210
                        
Jerome Mariette's avatar
Jerome Mariette committed
211
        self.default = default
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
212
        if self.type == "date" and not self.default:
Jerome Mariette's avatar
Jerome Mariette committed
213
214
            today = datetime.date.today()
            self.default = today.strftime('%d/%m/%Y')
215
        elif self.type == types.BooleanType :
Jerome Mariette's avatar
Jerome Mariette committed
216
217
            if self.default: self.default = str(self.default).lower() in ("true",  "t", "1")
            else: self.default = True
218
    
219
    def export_to_argparse(self):
220
221
222
223
        if self.type == types.BooleanType and str(self.default).lower() in ("false",  "f", "0"):
            return {"help": self.help, "required": self.required, "dest": self.name, 
                    "default": False, "action": "store_true"}
        elif self.type == types.BooleanType:
224
            return {"help": self.help, "required": self.required, "dest": self.name, 
225
                    "default": True, "action": "store_false"}
Jerome Mariette's avatar
Jerome Mariette committed
226
227
228
        elif self.nargs > 1:
            return {"type": self.type, "help": self.help, "required": self.required,
                    "dest": self.name, "default": self.default,
Jerome Mariette's avatar
Jerome Mariette committed
229
                    "action": self.action, "choices": self.choices, "nargs": "+"}
230
231
        else:
            return {"type": self.type, "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
232
                    "dest": self.name, "default": self.default,
233
234
                    "action": self.action, "choices": self.choices}
    
Jerome Mariette's avatar
Jerome Mariette committed
235
236
237
    def get_type(self):
        return self.type.__name__
    
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
238
239
240
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
Jerome Mariette's avatar
Jerome Mariette committed
241
242
243
            if param.required: req = [param_flag] 
            else: req = []
            self.type = MultipleParameters({param_flag: param.type}, req, 
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
244
245
246
247
248
249
250
251
                                           {param_flag: param.choices}, {}, {param_flag: param.default},
                                           {param_flag: param.action})
            if self.action == "append":
                self.action = MiltipleAppendAction
            else:
                self.action = MiltipleAction
            self.global_help = self.help
            self.help = self.global_help + " (" + param_flag + "=<" + param.type.__name__.upper() + ">)"
Jerome Mariette's avatar
Jerome Mariette committed
252
253
            self.default = {param_flag: param.default}
            self.nargs = "+"
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
254
255
256
257
258
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
            self.type.default[param_flag] = param.default
            self.type.actions[param_flag] = param.action
Jerome Mariette's avatar
Jerome Mariette committed
259
260
            if param.required:
                self.type.required.append(param_flag)
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
261
            self.help = self.global_help + self.type.get_help()
Jerome Mariette's avatar
Jerome Mariette committed
262
            self.default[param_flag] = param.default
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
263
264
        self.sub_parameters.append(param)
    
265
266
267
268
269
270
271
272
273
274
    
class AbstractFile(object):
    def __init__(self, file_format="any"):
        self.file_format = file_format
        self.parent_component_nameid = None


class MultiParameter(dict, AbstractParameter):
    
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
275
276
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, group=group, 
                                   display_name=display_name)
277
278
279
280
281
282
        return dict.__init__(self, {})


class MultiParameterList(list, AbstractParameter):
    
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
283
284
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, 
                                   action="append", group=group, display_name=display_name)
285
        return list.__init__(self, [])
Jerome Mariette's avatar
Jerome Mariette committed
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361

class Parameter(str, AbstractParameter):
    
    def __new__(self, name, help, default="", type=types.StringType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        return str.__new__(self, default)
    
    def __init__(self, name, help, default="", type=types.StringType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)
        

class InputFile(Parameter, AbstractFile):
    
    def __new__(self, name, help, file_format="any", default="", type=types.StringType, choices=None, 
                required=False, flag=None, group="default", display_name=None):
        return str.__new__(self, default)
    
    def __init__(self, name, help, file_format="any", default="", type=types.StringType, choices=None, 
                required=False, flag=None, group="default", display_name=None):
        AbstractFile.__init__(self, file_format)
        Parameter.__init__(self, name, help, flag=flag, type=type, choices=choices, 
                           required=required, group=group, display_name=display_name)
    

class OutputFile(Parameter, AbstractFile):
    
    def __new__(self, name, help, file_format="any", default="", type=types.StringType, choices=None, 
                required=False, flag=None, group="default", display_name=None):
        return str.__new__(self, default)
    
    def __init__(self, name, help, file_format="any", default="", type=types.StringType, choices=None, 
                required=False, flag=None, group="default", display_name=None):
        AbstractFile.__init__(self, file_format)
        Parameter.__init__(self, name, help, flag=flag, type=type, choices=choices, 
                           required=required, group=group, display_name=display_name)

        
class ParameterList(list, AbstractParameter):
    
    def __init__(self, name, help, default=[], type=types.StringType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, type=type, choices=choices, required=required, 
                                   action="append", sub_parameters=sub_parameters, group=group, display_name=display_name)
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
        

class InputFileList(ParameterList, AbstractFile):
    
    def __init__(self, name, help, file_format="any", default=[], type=types.StringType, choices=None, 
                 required=False, flag=None, group="default", display_name=None):
        AbstractFile.__init__(self, file_format)
        ParameterList.__init__(self, name, help, flag=flag, type=type, choices=choices, 
                               required=required, group=group, display_name=display_name)
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)


class OutputFileList(ParameterList, AbstractFile):
    
    def __init__(self, name, help, file_format="any", default=[], type=types.StringType, 
                 choices=None, required=False, flag=None, group="default", display_name=None):
        AbstractFile.__init__(self, file_format)
        ParameterList.__init__(self, name, help, flag=flag, type=type, choices=choices, 
                               required=required, group=group, display_name=display_name)
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)