parameter.py 30.9 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
#
# 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/>.
#

Frédéric Escudié's avatar
Frédéric Escudié committed
18
import re
Jerome Mariette's avatar
Jerome Mariette committed
19
import types
Jerome Mariette's avatar
Jerome Mariette committed
20
import datetime
Jerome Mariette's avatar
Jerome Mariette committed
21
import logging
Jerome Mariette's avatar
Jerome Mariette committed
22
import argparse
Jerome Mariette's avatar
Jerome Mariette committed
23
24
import os
import tempfile
25
from argparse import _ensure_value
Jerome Mariette's avatar
Jerome Mariette committed
26
import urllib2
27
import copy as _copy
Jerome Mariette's avatar
Jerome Mariette committed
28
29
30
from urlparse import urlparse
from jflow.config_reader import JFlowConfigReader

Jerome Mariette's avatar
Jerome Mariette committed
31
32
# import custom types
from workflows.types import *
Jerome Mariette's avatar
Jerome Mariette committed
33

Jerome Mariette's avatar
Jerome Mariette committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47

# define all input type available
INPUTFILE_TYPES = ["inputfile", "localfile", "urlfile", "browsefile"]

def browsefile(file):
    # browsefile are not available from command line, considere it as a localfile
    # from the gui, this will not been tested this way
    return localfile(file)

def localfile(file):
    if os.path.isfile(file):
        return os.path.abspath(file)
    else:
        raise argparse.ArgumentTypeError("Local file '" + file + "' does not exists! Please provide a valid file path!")
48

Jerome Mariette's avatar
Jerome Mariette committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def urlfile(file):
    uri_object = urlparse(file)
    try:
        opener = urllib2.urlopen(file)
    except:
        raise argparse.ArgumentTypeError("URL '" + file + "' is invalid!")
    file_name = os.path.basename(uri_object.path)
    if file_name is not None and file_name != "":
        metadata = opener.info()
        file_size = int(metadata.getheaders("Content-Length")[0])
        if file_size == 0:
            raise argparse.ArgumentTypeError("The URL file '" + file + "' is empty!")
        return file
    else:
        raise argparse.ArgumentTypeError("URL '" + file + "' does not contain any file name!")
64

Jerome Mariette's avatar
Jerome Mariette committed
65
66
67
68
69
70
71
72
def inputfile(file):
    # test the format
    uri_object = urlparse(file)
    # check the file
    if uri_object.scheme == '':
        return localfile(file)
    else:
        return urlfile(file)
73
74


Jerome Mariette's avatar
Jerome Mariette committed
75
76
77
78
79
80
81
82
83
84
class Formats(object):
    ANY = "any"
    BAM = "bam"
    FASTQ = "fastq"
    FASTA = "fasta"
    SFF = "sff"
    QUAL = "qual"
    FLOW = "flow"
    HTML = "html"

Jerome Mariette's avatar
Jerome Mariette committed
85

Jerome Mariette's avatar
Jerome Mariette committed
86
class MultipleParameters(object):
87
    def __init__(self, types, required, choices, excludes, default, actions):
Jerome Mariette's avatar
Jerome Mariette committed
88
        self.types = types
89
        self.choices = choices
Jerome Mariette's avatar
Jerome Mariette committed
90
        self.excludes = excludes
91
        self.default = default
92
        self.actions = actions
Jerome Mariette's avatar
Jerome Mariette committed
93
        self.index = None
94
        self.required = required
Jerome Mariette's avatar
Jerome Mariette committed
95
        self.__name__ = "MultipleParameters"
96

Jerome Mariette's avatar
help ok    
Jerome Mariette committed
97
98
99
100
101
    def get_help(self):
        help = " ("
        for flag in self.types.keys():
            help += flag + "=<" + self.types[flag].__name__.upper() + ">, "
        return help[:-2] + ")"
102

103
    def __call__(self, arg):
Jerome Mariette's avatar
Jerome Mariette committed
104
105
106
        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()))
107
108
109
        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]]) + "))")
110

111
112
113
114
115
116
117
        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] + "'")
118

119
            self.index = parts[0]
120
            return (parts[0], value, self.required, self.excludes, self.actions)
Jerome Mariette's avatar
Jerome Mariette committed
121

122
123
class MiltipleAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
124
125
126
127
128
129
130
        # 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
131
132
        given_params = []
        # first check for required parameters
133
134
        try:
            required = _copy.copy(values[0][2])
135
136
137
138
139
140
            # 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)]
141
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
142
                given_params.append(val[0])
143
144
145
146
147
                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
148
149
150
151
152
153
154
155
        # 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
156

157
158
159
160
161
162
163
164
        # 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")
165

Jerome Mariette's avatar
Jerome Mariette committed
166
        # if ok add the value
167
168
169
170
171
172
173
174
175
176
177
        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)
178

179

180
181
class MiltipleAppendAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
182
183
184
185
186
187
188
        # 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
189
190
        given_params = []
        # first check for required parameters
191
192
        try:
            required = _copy.copy(values[0][2])
193
194
195
196
197
198
            # 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)]
199
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
200
                given_params.append(val[0])
201
202
203
204
205
                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
206
207
208
209
210
211
212
213
        # 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
214

215
216
217
218
219
220
221
222
        # 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
223
        # if ok add the value
224
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
225
226
227
228
229
230
231
232
233
234
235
        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)
236
        setattr(namespace, self.dest, items)
237
238
239


class AbstractParameter(object):
240

241
242
    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
243

Jerome Mariette's avatar
Jerome Mariette committed
244
245
        self.name = name
        self.help = help
246
        self.action = action
Jerome Mariette's avatar
Jerome Mariette committed
247
        self.nargs = None
248
249
250
        if sub_parameters:
            self.sub_parameters = sub_parameters
        else: self.sub_parameters = []
Jerome Mariette's avatar
Jerome Mariette committed
251
        self.group = group
252
253
254
        if flag == None:
            self.flag = "--"+name.replace("_", "-")
        else: self.flag = flag
255
        if display_name == None:
256
            self.display_name = name.replace("_", " ").title()
Jerome Mariette's avatar
Jerome Mariette committed
257
        else: self.display_name = display_name
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
258
        self.required = required
259
        self.choices = choices
260
261

        # Set parameter type
Jerome Mariette's avatar
Jerome Mariette committed
262
        if type == "date":
263
            self.type = types.MemberDescriptorType
Jerome Mariette's avatar
Jerome Mariette committed
264
        elif type == "multiple":
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
265
            self.type = "multiple"
Jerome Mariette's avatar
Jerome Mariette committed
266
267
        elif isinstance(type, types.FunctionType):
            self.type = type
268
        elif type in [types.StringType, types.IntType, types.FloatType,  types.BooleanType]:
Jerome Mariette's avatar
Jerome Mariette committed
269
            self.type = type
Jerome Mariette's avatar
Jerome Mariette committed
270
271
272
        else:
            try: self.type = eval(type)
            except: self.type = types.StringType
273
274

        # Set parameter value
Jerome Mariette's avatar
Jerome Mariette committed
275
        self.default = default
276

277
    def export_to_argparse(self):
Jerome Mariette's avatar
Jerome Mariette committed
278
        if self.type == types.BooleanType and str(self.default).lower() in (False, "false",  "f", "0"):
279
280
281
            return {"help": self.help, "required": self.required, "dest": self.name, 
                    "default": False, "action": "store_true"}
        elif self.type == types.BooleanType:
282
            return {"help": self.help, "required": self.required, "dest": self.name, 
283
                    "default": True, "action": "store_false"}
Jerome Mariette's avatar
Jerome Mariette committed
284
285
286
        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
287
                    "action": self.action, "choices": self.choices, "nargs": "+"}
288
289
        else:
            return {"type": self.type, "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
290
                    "dest": self.name, "default": self.default,
291
                    "action": self.action, "choices": self.choices}
292

Jerome Mariette's avatar
Jerome Mariette committed
293
294
    def get_type(self):
        return self.type.__name__
295
296


Jerome Mariette's avatar
Jerome Mariette committed
297
class AbstractIOFile(object):
298

Jerome Mariette's avatar
Jerome Mariette committed
299
300
    def __init__(self, file_format="any"):
        self.file_format = file_format
Jerome Mariette's avatar
Jerome Mariette committed
301
        self.component_nameid = None
Jerome Mariette's avatar
Jerome Mariette committed
302
303
304
305
306
307
308
309
310
311
        self.parent_component_nameid = None


class MultiParameter(dict, AbstractParameter):
    
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, group=group, 
                                   display_name=display_name)
        return dict.__init__(self, {})

Jerome Mariette's avatar
help ok    
Jerome Mariette committed
312
313
314
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
Jerome Mariette's avatar
Jerome Mariette committed
315
316
317
            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
318
319
320
321
322
323
324
325
                                           {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
326
            self.default = {}
Jerome Mariette's avatar
Jerome Mariette committed
327
            self.nargs = "+"
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
328
329
330
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
331
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
332
            self.type.actions[param_flag] = param.action
Jerome Mariette's avatar
Jerome Mariette committed
333
334
            if param.required:
                self.type.required.append(param_flag)
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
335
            self.help = self.global_help + self.type.get_help()
Jerome Mariette's avatar
Jerome Mariette committed
336
        param.flag = param_flag
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
337
        self.sub_parameters.append(param)
338

339
340
341
342

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
343
344
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, 
                                   action="append", group=group, display_name=display_name)
345
        return list.__init__(self, [])
Jerome Mariette's avatar
Jerome Mariette committed
346

Jerome Mariette's avatar
Jerome Mariette committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
            if param.required: req = [param_flag] 
            else: req = []
            self.type = MultipleParameters({param_flag: param.type}, req, 
                                           {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() + ">)"
            self.default = []
            self.nargs = "+"
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
366
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
Jerome Mariette committed
367
368
369
370
371
372
373
            self.type.actions[param_flag] = param.action
            if param.required:
                self.type.required.append(param_flag)
            self.help = self.global_help + self.type.get_help()
        param.flag = param_flag
        self.sub_parameters.append(param)

374

375
376
377
378
379
380
381
def noneException(*args, **kwargs):
    raise Exception( "The parameter value is None." )


class BoolParameter(int, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.BooleanType, choices=None, required=False,
382
                flag=None, sub_parameters=None, group="default", display_name=None):
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        bool_default = False if default == None else bool(default)
        val = int.__new__(self, bool_default)
        val.is_None = False
        if default == None:
            val.is_None = True
            for attr in val.__dict__:
                value = getattr(val, attr)
                if callable(value) and attr not in ["__new__", "__init__", "__int__", "__getattribute__", "__eq__", "__ne__", "__nonzero__"]:
                    setattr(val, attr, noneException)
        return val

    def __init__(self, name, help, default=None, type=types.BooleanType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)
398
399
400

    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
401
402
403
404
405
406
            return self.is_None
        elif self.is_None:
            return False
        else:
            return int(self) == int(other)

407
408
    def __ne__(self, other):
        if other.__class__.__name__ == "NoneType":
409
410
411
412
413
414
            return not self.is_None
        elif self.is_None:
            return True
        else:
            return int(self) != int(other)

415
    def __nonzero__(self):
416
        if self.is_None:
417
            return False
418
419
420
        else:
            return self != 0

421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
class IntParameter(int, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.IntType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        int_default = 0 if default == None else int(default)
        val = int.__new__(self, int_default)
        val.is_None = False
        if default == None:
            val.is_None = True
            for attr in val.__dict__:
                value = getattr(val, attr)
                if callable(value) and attr not in ["__new__", "__init__", "__int__", "__getattribute__", "__eq__", "__ne__", "__nonzero__"]:
                    setattr(val, attr, noneException)
        return val

    def __init__(self, name, help, default=None, type=types.IntType, choices=None, required=False,
438
                 flag=None, sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
439
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
440
441
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return int(self) == int(other)

    def __ne__(self, other):
        if other.__class__.__name__ == "NoneType":
            return not self.is_None
        elif self.is_None:
            return True
        else:
            return int(self) != int(other)

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return self != 0


class FloatParameter(int, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.FloatType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        float_default = 0.0 if default == None else float(default)
        val = int.__new__(self, float_default)
        val.is_None = False
        if default == None:
            val.is_None = True
            for attr in val.__dict__:
                value = getattr(val, attr)
                if callable(value) and attr not in ["__new__", "__init__", "__float__", "__getattribute__", "__eq__", "__ne__", "__nonzero__"]:
                    setattr(val, attr, noneException)
        return val

    def __init__(self, name, help, default=None, type=types.FloatType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)

    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return float(self) == float(other)

    def __ne__(self, other):
        if other.__class__.__name__ == "NoneType":
            return not self.is_None
        elif self.is_None:
            return True
        else:
            return float(self) != float(other)

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return self != 0.0


class StrParameter(str, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        str_default = "" if default == None else str(default)
        val = str.__new__(self, str_default)
        val.is_None = False
        if default == None:
            val.is_None = True
            for attr in val.__dict__:
                value = getattr(val, attr)
                if callable(value) and attr not in ["__new__", "__init__", "__str__", "__getattribute__", "__eq__", "__ne__", "__nonzero__"]:
                    setattr(val, attr, noneException)
        return val

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

    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return str(self) == str(other)

    def __ne__(self, other):
        if other.__class__.__name__ == "NoneType":
            return not self.is_None
        elif self.is_None:
            return True
        else:
            return str(self) != str(other)

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return (True if str(self) else False)


class ParameterFactory(object):
    @staticmethod
    def factory(*args, **kwargs):
        if not kwargs.has_key( "type" ):
            return StrParameter( *args, **kwargs )

        if kwargs["type"] == "int" or kwargs["type"] is types.IntType:
            return IntParameter( *args, **kwargs )
        elif kwargs["type"] == "bool" or kwargs["type"] is types.BooleanType :
            return BoolParameter( *args, **kwargs )
        elif kwargs["type"] == "float" or kwargs["type"] is types.FloatType :
            return FloatParameter( *args, **kwargs )
        else:
            return StrParameter( *args, **kwargs )

Frédéric Escudié's avatar
Frédéric Escudié committed
566
567
568
569
570
571
572

class AbstractOutputFile(AbstractIOFile):
    """
     @summary : Parent of all OutputFile(s) parameters.
    """
    pass

573
574
575

class InputFile(StrParameter, AbstractInputFile):

Jerome Mariette's avatar
Jerome Mariette committed
576
    def __new__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
577
                required=False, flag=None, group="default", display_name=None):
578

Jerome Mariette's avatar
Jerome Mariette committed
579
580
581
        if hasattr(type, '__call__'):
            type2test = type.__name__
        else: type2test = type
582

Jerome Mariette's avatar
Jerome Mariette committed
583
584
585
        if type2test not in INPUTFILE_TYPES:
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
586
587
588
589

        return StrParameter.__new__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
                           required=required, group=group, display_name=display_name)

Jerome Mariette's avatar
Jerome Mariette committed
590
    def __init__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
591
                required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
592
        AbstractIOFile.__init__(self, file_format)
593
        StrParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
594
                           required=required, group=group, display_name=display_name)
Jerome Mariette's avatar
Jerome Mariette committed
595

596
597
class OutputFile(StrParameter, AbstractOutputFile):

Jerome Mariette's avatar
Jerome Mariette committed
598
    def __new__(self, name, help, file_format="any", default="", choices=None, 
599
                required=False, flag=None, group="default", display_name=None):
600
601
602
        return StrParameter.__new__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
                           required=required, group=group, display_name=display_name)

Jerome Mariette's avatar
Jerome Mariette committed
603
    def __init__(self, name, help, file_format="any", default="", choices=None, 
604
                required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
605
        AbstractIOFile.__init__(self, file_format)
606
        StrParameter.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
607
608
                           required=required, group=group, display_name=display_name)

609

610
class ParameterList(list, AbstractParameter):
611

Jerome Mariette's avatar
Jerome Mariette committed
612
    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
613
                 flag=None, sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
614
        if default == None: default = []
Jerome Mariette's avatar
Jerome Mariette committed
615
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
616
617
618
619
620
                                   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)
621

622

Frédéric Escudié's avatar
Frédéric Escudié committed
623
class InputFileList(ParameterList, AbstractInputFile):
624

Jerome Mariette's avatar
Jerome Mariette committed
625
    def __init__(self, name, help, file_format="any", default=None, type="localfile", choices=None, 
626
                 required=False, flag=None, group="default", display_name=None):
627

Jerome Mariette's avatar
Jerome Mariette committed
628
        if default == None: default = []   
Jerome Mariette's avatar
Jerome Mariette committed
629
630
631
        if hasattr(type, '__call__'):
            type2test = type.__name__
        else: type2test = type
632

Jerome Mariette's avatar
Jerome Mariette committed
633
634
635
        if type2test not in INPUTFILE_TYPES:
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
636

Jerome Mariette's avatar
Jerome Mariette committed
637
        AbstractIOFile.__init__(self, file_format)
Jerome Mariette's avatar
Jerome Mariette committed
638
        ParameterList.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
639
                               required=required, group=group, display_name=display_name)
640

641
642
643
644
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
Frédéric Escudié's avatar
Frédéric Escudié committed
645
        elif issubclass( default.__class__, AbstractInputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
646
            return list.__init__(self, default)
Frédéric Escudié's avatar
Frédéric Escudié committed
647
        elif issubclass( default.__class__, AbstractOutputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
648
            return list.__init__(self, default)
649

650

Frédéric Escudié's avatar
Frédéric Escudié committed
651
652
class OutputFileList(ParameterList, AbstractOutputFile):

Jerome Mariette's avatar
Jerome Mariette committed
653
654
655
    def __init__(self, name, help, file_format="any", default=None, choices=None, 
                 required=False, flag=None, group="default", display_name=None):
        if default == None: default = []
Jerome Mariette's avatar
Jerome Mariette committed
656
        AbstractIOFile.__init__(self, file_format)
Jerome Mariette's avatar
Jerome Mariette committed
657
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
658
659
660
661
662
                               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)
Frédéric Escudié's avatar
Frédéric Escudié committed
663

664

Frédéric Escudié's avatar
Frédéric Escudié committed
665
666
667
668
669
670
671
672
673
674
class DynamicOutput(ParameterList, AbstractOutputFile):
    """
     @warning : with this class of output, the component become dynamic.
    """
    def update(self):
        """
         This method is used at the end of component execution to update output list.
        """
        raise NotImplementedError

675

Frédéric Escudié's avatar
Frédéric Escudié committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
class OutputFilesEndsWith(DynamicOutput):

    def __init__(self, name, help, output_directory, end_str, include=True, file_format="any", choices=None, 
                 required=False, flag=None, group="default", display_name=None):
        """
         @warning : with this class of output, the component become dynamic.
         @param output_directory : path to the directory where outputs will be created.
         @param end_str : the end of the files names.
         @param include : if true, the files with name terminated by end_str are added into output files.
                          If false, the files with name not terminated by end_str are added into output files.
        """
        AbstractIOFile.__init__(self, file_format)
        default = []
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
                               required=required, group=group, display_name=display_name)
        self.output_directory = output_directory
        self.end_str = end_str
        self.include = include
        return list.__init__(self, default)

    def update(self):
        output_files = list()
        for file in os.listdir( self.output_directory ):
            if file.endswith( self.end_str ) and self.include :
                output_files.append( os.path.join(self.output_directory, file) )
            elif not file.endswith( self.end_str ) and not self.include:
                output_files.append( os.path.join(self.output_directory, file) )
        list.__init__(self, output_files)

705

Frédéric Escudié's avatar
Frédéric Escudié committed
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
class OutputFilesPattern(DynamicOutput):

    def __init__(self, name, help, output_directory, pattern, include=True, file_format="any", choices=None, 
                  required=False, flag=None, group="default", display_name=None):
        """
         @warning : with this class of output, the component become dynamic.
         @param output_directory : path to the directory where outputs will be created.
         @param pattern : the pattern of (a part) the file names.
         @param include : if true, the files with the pattern in file name are added into output files.
                          If false, the files with the pattern in file name are added into output files.
        """
        AbstractIOFile.__init__(self, file_format)
        default = []
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
                               required=required, group=group, display_name=display_name)
        self.output_directory = output_directory
        self.pattern = pattern
        self.include = include
        return list.__init__(self, default)

    def update(self):
        output_files = list()
        for file in os.listdir( self.output_directory ):
            if self.include and re.search( self.pattern, file ) is not None:
                output_files.append( os.path.join(self.output_directory, file) )
            elif not self.include and re.search( self.pattern, file ) is None:
                output_files.append( os.path.join(self.output_directory, file) )
        return list.__init__(self, output_files)