forked from BoPeng/simuPOP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simuOpt.py
executable file
·2050 lines (1911 loc) · 89.4 KB
/
simuOpt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
705
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# $File: simuOpt.py $
# $LastChangedDate$
# $Rev$
#
# This file is part of simuPOP, a forward-time population genetics
# simulation environment. Please visit http://simupop.sourceforge.net
# for details.
#
# Copyright (C) 2004 - 2010 Bo Peng ([email protected])
#
# 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/>.
#
'''
Module ``simuOpt`` provides a function ``simuOpt.setOptions`` to control which
simuPOP module to load, and how it is loaded, and a class ``simuOpt.Params``
that helps users manage simulation parameters.
When simuPOP is loaded, it checkes a few environmental variables
(``SIMUOPTIMIZED``, ``SIMUALLELETYPE``, and ``SIMUDEBUG``) to determine which
simuPOP module to load, and how to load it. More options can be set using the
``simuOpt.setOptions`` function. For example, you can suppress the banner
message when simuPOP is loaded and require a minimal version of simuPOP for
your script. simuPOP recognize the following commandline arguments
``--optimized``
Load the optimized version of a simuPOP module.
``--gui=None|batch|interactive|True|wxPython|Tkinter``
Whether or not use a graphical toolkit and which one to use.
``--gui=batch`` is usually used to run a script in batch mode (do not start
a parameter input dialog and use all default values unless a parameter is
specified from command line or a configuraiton file. If
``--gui=interactive``, an interactive shell will be used to solicit input
from users. Otherwise, simuPOP will try to use a graphical parameter input
dialog, and falls to an interactive mode when no graphical Toolkit is
available. Please refer to parameter ``gui`` for ``simuOpt.setOptions``
for details.
class ``params.Params`` provides a powerful way to handle commandline
arguments. Briefly speaking, a ``Params`` object can be created from a list
of parameter specification dictionaries. The parameters are then become
attributes of this object. A number of functions are provided to determine
values of these parameters using commandline arguments, a configuration
file, or a parameter input dialog (using ``Tkinter`` or ``wxPython``).
Values of these parameters can be accessed as attributes, or extracted
as a list or a dictionary. Note that the ``Params.getParam`` function
automatically handles the following commandline arguments.
``-h`` or ``--help``
Print usage message.
``--config=configFile``
Read parameters from a configuration file *configFile*.
'''
__all__ = [
'simuOptions',
'setOptions',
'valueNot',
'valueOr',
'valueAnd',
'valueOneOf',
'valueTrueFalse',
'valueBetween',
'valueGT',
'valueGE',
'valueLT',
'valueLE',
'valueEqual',
'valueNotEqual',
'valueIsInteger',
'valueIsNum',
'valueIsList',
'valueValidDir',
'valueValidFile',
'valueListOf',
'valueSumTo',
'Params',
'param',
]
import os, sys, re, time, textwrap
#
# simuOptions that will be checked when simuPOP is loaded. This structure
# can be changed by function setOptions
#
simuOptions = {
'Optimized': False,
'AlleleType': 'short',
'Debug': [],
'Quiet': False,
'Version': None,
'Revision': None,
'GUI': True,
'Plotter': None,
'NumThreads': 1,
}
# Optimized: command line option --optimized or environmental variable SIMUOPTIMIZED
if '--optimized' in sys.argv or os.getenv('SIMUOPTIMIZED') is not None:
simuOptions['Optimized'] = True
# AlleleType: from environmental variable SIMUALLELETYPE
if os.getenv('SIMUALLELETYPE') in ['short', 'long', 'binary', 'mutant', 'lineage']:
simuOptions['AlleleType'] = os.getenv('SIMUALLELETYPE')
elif os.getenv('SIMUALLELETYPE') is not None:
print('Environmental variable SIMUALLELETYPE can only be short, long, binary, mutant, or lineage.')
# Debug: from environmental variable SIMUDEBUG
if os.getenv('SIMUDEBUG') is not None:
simuOptions['Debug'].extend(os.getenv('SIMUDEBUG').split(','))
# openMP number of threads
if os.getenv('OMP_NUM_THREADS') is not None:
try:
simuOptions['NumThreads'] = int(os.getenv('OMP_NUM_THREADS'))
except:
print('Ignoring invalid value for environmental variable OMP_NUM_THREADS')
# GUI: from environmental variable SIMUGUI
if os.getenv('SIMUGUI') is not None:
_gui = os.getenv('SIMUGUI')
elif '--gui' in sys.argv:
if sys.argv[-1] == '--gui':
raise ValueError('An value is expected for command line option --gui')
_gui = sys.argv[sys.argv.index('--gui') + 1]
elif True in [x.startswith('--gui=') for x in sys.argv]:
_gui = sys.argv[[x.startswith('--gui=') for x in sys.argv].index(True)][len('--gui='):]
else:
_gui = None
if _gui in ['True', 'true', '1']:
simuOptions['GUI'] = True
elif _gui in ['False', 'false', '0']:
simuOptions['GUI'] = False
elif _gui in ['wxPython', 'Tkinter', 'batch', 'interactive']:
simuOptions['GUI'] = _gui
elif _gui is not None:
print("Invalid value '%s' for environmental variable SIMUGUI or commandline option --gui." % _gui)
def setOptions(alleleType=None, optimized=None, gui=None, quiet=None,
debug=None, version=None, revision=None, numThreads=None, plotter=None):
'''Set options before simuPOP is loaded to control which simuPOP module to
load, and how the module should be loaded.
alleleType
Use the standard, binary,long or mutant allele version of the simuPOP
module if ``alleleType`` is set to 'short', 'binary', 'long', 'mutant',
or 'lineage' respectively. If this parameter is not set, this function
will try to get its value from environmental variable ``SIMUALLELETYPE``.
The standard (short) module will be used if the environmental variable
is not defined.
optimized
Load the optimized version of a module if this parameter is set to
``True`` and the standard version if it is set to ``False``. If this
parameter is not set (``None``), the optimized version will be used
if environmental variable ``SIMUOPTIMIZED`` is defined. The standard
version will be used otherwise.
gui
Whether or not use graphical user interfaces, which graphical toolkit
to use and how to process parameters in non-GUI mode. If this parameter
is ``None`` (default), this function will check environmental variable
``SIMUGUI`` or commandline option ``--gui`` for a value, and assume
``True`` if such an option is unavailable. If ``gui=True``, simuPOP
will use ``wxPython``-based dialogs if ``wxPython`` is available, and
use ``Tkinter``-based dialogs if ``Tkinter`` is available and use an
interactive shell if no graphical toolkit is available.
``gui='Tkinter'`` or ``'wxPython'`` can be used to specify the
graphical toolkit to use. If ``gui='interactive'``, a simuPOP script
prompt users to input values of parameters. If ``gui='batch'``,
default values of unspecified parameters will be used. In any case,
commandline arguments and a configuration file specified by parameter
--config will be processed. This option is usually left to ``None`` so
that the same script can be run in both GUI and batch mode using
commandline option ``--gui``.
plotter
(Deprecated)
quiet
If set to ``True``, suppress the banner message when a simuPOP module
is loaded.
debug
A list of debug code (as string) that will be turned on when simuPOP
is loaded. If this parameter is not set, a list of comma separated
debug code specified in environmental variable ``SIMUDEBUG``, if
available, will be used. Note that setting ``debug=[]`` will remove
any debug code that might have been by variable ``SIMUDEBUG``.
version
A version string (e.g. 1.0.0) indicating the required version number
for the simuPOP module to be loaded. simuPOP will fail to load if the
installed version is older than the required version.
revision
Obsolete with the introduction of parameter version.
numThreads
Number of Threads that will be used to execute a simuPOP script. The
values can be a positive number (number of threads) or 0 (all available
cores of the computer, or whatever number set by environmental variable
``OMP_NUM_THREADS``). If this parameter is not set, the number of
threads will be set to 1, or a value set by environmental variable
``OMP_NUM_THREADS``.
'''
# if the module has already been imported, check which module
# was imported
try:
_imported = sys.modules['simuPOP'].moduleInfo()
except Exception as e:
_imported = {}
# Allele type
if alleleType in ['long', 'binary', 'short', 'mutant', 'lineage']:
# if simuPOP has been imported and re-imported with a different module name
# the existing module will be used so moduleInfo() will return a different
# module type from what is specified in simuOptions.
if _imported and _imported['alleleType'] != alleleType:
raise ImportError(('simuPOP has already been imported with allele type %s (%s) and cannot be '
're-imported with allele type %s. Please make sure you import module simuOpt before '
'any simuPOP module is imported.') % (
_imported['alleleType'], ('optimized' if _imported['optimized'] else 'standard'),
alleleType))
simuOptions['AlleleType'] = alleleType
elif alleleType is not None:
raise TypeError('Parameter alleleType can be either short, long, binary, mutant or lineage.')
# Optimized
if optimized in [True, False]:
# if simuPOP has been imported and re-imported with a different module name
# the existing module will be used so moduleInfo() will return a different
# module type from what is specified in simuOptions.
if _imported and _imported['optimized'] != optimized:
raise ImportError(('simuPOP has already been imported with allele type %s (%s) and cannot be '
're-imported in %s mode. Please make sure you import module simuOpt before '
'any simuPOP module is imported.') % (
_imported['alleleType'], ('optimized' if _imported['optimized'] else 'standard'),
'optimized' if optimized else 'standard'))
simuOptions['Optimized'] = optimized
elif optimized is not None:
raise TypeError('Parameter optimized can be either True or False.')
# Graphical toolkit
if gui in [True, False, 'wxPython', 'Tkinter', 'batch']:
simuOptions['GUI'] = gui
elif gui is not None:
raise TypeError('Parameter gui can be True/False, wxPython or Tkinter.')
# Quiet
if quiet in [True, False]:
simuOptions['Quiet'] = quiet
elif quiet is not None:
raise TypeError('Parameter quiet can be either True or False.')
# Debug
if debug is not None:
if type(debug) == str:
simuOptions['Debug'] = [debug]
else:
simuOptions['Debug'] = debug
# Version
if type(version) == str:
try:
major, minor, release = [int(x) for x in re.sub('\D', ' ', version).split()]
except:
print('Invalid version string %s' % simuOptions['Version'])
simuOptions['Version'] = version
elif version is not None:
raise TypeError('A version string is expected for parameter version.')
# Revision
if type(revision) == int:
simuOptions['Revision'] = revision
elif revision is not None:
raise TypeError('A revision number is expected for parameter revision.')
# NumThreads
if type(numThreads) == int:
simuOptions['NumThreads'] = numThreads
elif numThreads is not None:
raise TypeError('An integer number is expected for parameter numThreads.')
if plotter is not None:
sys.stderr.write('WARNING: plotter option is deprecated because of the removal of rpy/rpy2 support\n')
#
# define some validataion functions
#
def valueNot(t):
'''Return a function that returns true if passed option does not equal t,
or does not passes validator t'''
def func(val):
if callable(t):
return not t(val)
else:
return val != t
return func
def valueOr(t1, t2):
'''Return a function that returns true if passed option passes validator
t1 or t2'''
def func(val):
if callable(t1) and callable(t2):
return t1(val) or t2(val)
else:
raise ValueError("We expect a function valueXXX")
return func
def valueAnd(t1, t2):
'''Return a function that returns true if passed option passes validator
t1 and t2'''
def func(val):
if callable(t1) and callable(t2):
return t1(val) and t2(val)
else:
raise ValueError("We expect a function valueXXX")
return func
def valueOneOf(*args):
'''Return a function that returns true if passed option is one of the
parameters, or one of the values in the only parameter'''
if len(args) == 1:
t = args[0]
else:
t = args
if not type(t) in [list, tuple]:
raise ValueError('argument of valueOneOf should be a list')
def func(val):
yes = False
for item in t:
if item == val: # equal value
return True
if callable(item): # a test function
if item(val):
return True
return False
return func
def valueTrueFalse():
'''Return a function that returns true if passed option is True or False'''
return valueOneOf([True, False])
def valueBetween(a,b):
'''Return a function that returns true if passed option is between value a and b
(a and b included)
'''
def func(val):
return val >= a and val <=b
return func
def valueGT(a):
'''Return a function that returns true if passed option is greater than a'''
def func(val):
return val > a
return func
def valueGE(a):
'''Return a function that returns true if passed option is greater than or
equal to a'''
def func(val):
return val >= a
return func
def valueLT(a):
'''Return a function that returns true if passed option is less than a'''
def func(val):
return val < a
return func
def valueLE(a):
'''Return a function that returns true if passed option is less than or
equal to a'''
def func(val):
return val <= a
return func
def valueEqual(a):
'Return a function that returns true if passed option equals a'
def func(val):
return val == a
return func
def valueNotEqual(a):
'Return a function that returns true if passed option does not equal a'
def func(val):
return val != a
return func
def valueIsInteger():
'Return a function that returns true if passed option is an integer (int, long)'
def func(val):
return isinstance(val, (int, long))
return func
def valueIsNum():
'Return a function that returns true if passed option is a number (int, long or float)'
def func(val):
return isinstance(val, (int, long, float))
return func
def valueIsList(size=None):
'''Return a function that returns true if passed option is a sequence.
If a ``size`` is given, the sequence must have the specified size (e.g.
``size=3``), or within the range of sizes (e.g. ``size=[1, 5]``). A ``None``
can be used as unspecified lower or upper bound.'''
def func(val):
if not hasattr(val, '__iter__'):
return False
if size is not None:
if isinstance(size, (int, long)):
return len(val) == size
elif hasattr(size, '___iter__') and len(size) == 2:
if size[0] is not None and size[1] is not None:
return len(val) >= size[0] and len(val) <= size[1]
elif size[0] is None:
return len(val) <= size[1]
else:
return len(val) >= size[0]
else:
raise ValueError('Invalid size specification for simuOpt.valueIsList')
return True
return func
def valueSumTo(a, eps=1e-7):
'''Return a function that returns true if passed option sum up to a.
An eps value can be specified to allowed for numerical error.'''
def func(val):
return abs(sum(val) - a) < eps
return func
def valueValidDir():
'''Return a function that returns true if passed option val if a valid
directory'''
def func(val):
'''Params.valueValidDir'''
return os.path.isdir(val)
return func
def valueValidFile():
'''Return a function that returns true if passed option val if a valid
file'''
def func(val):
'''Params.valueValidFile'''
return os.path.isfile(val)
return func
def valueListOf(t, size=None):
'''Return a function that returns true if passed option val is a list of
type ``t`` if ``t`` is a type, if ``v`` is one of ``t`` if ``t`` is a list,
or if ``v`` passes test ``t`` if ``t`` is a validator (a function). If a
``size`` is given, the sequence must have the specified size (e.g.
``size=3``), or within the range of sizes (e.g. ``size=[1, 5]``). A ``None``
can be used as unspecified lower or upper bound.'''
def func(val):
if not hasattr(val, '__iter__'):
return False
if type(t) in [list, tuple]:
for i in val:
if not i in t:
return False
elif callable(t):
for i in val:
if not t(i):
return False
else:
for i in val:
if type(i) != t:
return False
if size is not None:
if isinstance(size, (int, long)):
return len(val) == size
elif hasattr(size, '___iter__') and len(size) == 2:
if size[0] is not None and size[1] is not None:
return len(val) >= size[0] and len(val) <= size[1]
elif size[0] is None:
return len(val) <= size[1]
else:
return len(val) >= size[0]
else:
raise ValueError('Invalid size specification for simuOpt.valueIsList')
return True
return func
def _prettyString(value, quoted=False, outer=True):
'''Return a value in good format, the main purpose is to
avoid [0.90000001, 0.2].
'''
def quote(txt):
if not quoted:
return txt
if not "'" in txt:
return "'%s'" % txt
elif not '"' in txt:
return '"%s"' % txt
elif not "'''" in txt:
return "'''%s'''" % txt
elif not '"""' in txt:
return '"""%s"""' % txt
else:
return "'%s'" % txt.replace("'", "\\'")
#
if type(value) in [list, tuple]:
txt = '[' + ', '.join([_prettyString(x, True, False) for x in value]) + ']'
if outer:
return quote(txt)
else:
return txt
elif type(value) == str:
return quote(value)
elif outer:
return quote(str(value))
else:
return str(value)
def _prettyDesc(text, indent='', width=80):
'''Reformat description of options. All lines are joined and all extra
spaces are removed before the text is wrapped with specified *indent*.
An exception is that lines with '|' as the first non-space/tab character
will be outputed as is without the leading '|' symbol**.
'''
blocks = []
for line in text.split('\n'):
txt = line.strip()
if txt.startswith('|'):
blocks.append(txt)
continue
txt = re.sub('\s+', ' ', txt)
if len(blocks) == 0 or blocks[-1].startswith('!'):
blocks.append(txt)
else:
blocks[-1] += ' ' + txt
txt = []
for blk in blocks:
if blk == '|':
txt.append('')
elif blk.startswith('|'):
blk_indent = ''
for c in blk[1:]:
if c not in [' ', '\t']:
break
blk_indent += c
txt.extend(textwrap.wrap(blk[1:], width=width,
initial_indent=indent + blk_indent, # keep spaces after | character
subsequent_indent=indent))
else:
txt.extend(textwrap.wrap(blk, width=width, initial_indent=indent,
subsequent_indent=indent))
return '\n'.join(txt)
def _paramType(opt):
'''Determine the type of an option'''
def _validate(value, opt, options=[]):
'''validate an option against other options'''
# if no validator is specified
if not opt.has_key('validator'):
return True
# if a function is given, easy
if callable(opt['validator']):
return opt['validator'](value)
# we need a dictionary
env = {}
for o in options:
if o.has_key('separator'):
continue
name = o['name']
env[name] = o['value']
env[opt['name']] = value
return eval(opt['validator'], globals(), env) is True
def _usage(options, msg='', details='', usage='usage: %prog [--opt[=arg]] ...'):
'Return a usage message.'
if msg != '':
message = _prettyDesc(msg, width=80) + '\n\n' + _prettyDesc(details, width=80) + '\n'
else:
message = _prettyDesc(details, width=80) + '\n'
#
message += '''\n%s
options:
-h, --help
Display this help message and exit.
--config=ARG (default: None)
Load parameters from a configuration file ARG.
--optimized
Run the script using an optimized simuPOP module.
--gui=[batch|interactive|True|Tkinter|wxPython] (default: None)
Run the script in batch, interactive or GUI mode.
''' % usage.replace('%prog', os.path.basename(sys.argv[0]))
for opt in options:
if opt.has_key('separator'):
continue
if opt.has_key('separator'):
continue
name = ''
# this is obsolete
if opt.has_key('arg'):
if opt['gui_type'] != 'boolean':
name += '-%s=ARG, ' % opt['arg']
else:
name += '-%s, ' % opt['arg']
#
if opt['gui_type'] != 'boolean':
name += '--%s=ARG' % opt['name']
else:
name += '--%s' % opt['name']
#
if isinstance(opt['default'], str):
defaultVal = "'%s'" % opt['default']
elif opt['default'] is None:
defaultVal = 'None'
else:
defaultVal = _prettyString(opt['default'])
#
message += ' %s (default: %s)\n' % (name, defaultVal)
if opt.has_key('description'):
message += _prettyDesc(opt['description'], indent=' '*8) + '\n'
elif opt.has_key('label'):
message += _prettyDesc(opt['label'], indent=' '*8) + '\n'
message += '\n'
return message.strip()
def _getParamValue(p, val, options):
''' try to get a value from value, raise exception if error happens. '''
if p['gui_type'] == 'separator':
raise ValueError('Cannot get a value for separator')
# if we are giving a unicode string, convert!
if type(val) == unicode:
val = str(val)
# remove quotes from string?
if p.has_key('allowedTypes') and str in p['allowedTypes'] and str == type(val):
for quote in ['"', "'", '"""', "'''"]:
if val.startswith(quote) and val.endswith(quote):
val = val[len(quote):-len(quote)]
break
if (not p.has_key('allowedTypes')) or type(val) in p['allowedTypes']:
if not _validate(val, p, options):
raise ValueError("Value '%s' is not allowed for parameter %s" % \
(str(val), p['name']))
return val
# handle another 'auto-boolean' case
elif p['gui_type'] == 'boolean':
if val in ['1', 'true', 'True']:
return True
elif val in ['0', 'false', 'False']:
return False
else:
raise ValueError('Expect 0/1, true/false for boolean values for parameter %s ' % p['name'])
# other wise, need conversion
if type(val) in [str, unicode]:
try:
val = eval(val)
except:
# may be we have a list of string?
items = val.split(',')
if len(items) > 1: # is actually a list
val = []
for i in items:
val.append(i.strip())
# evaluated type is OK now.
if type(val) in p['allowedTypes']:
if not _validate(val, p, options):
raise ValueError("Default value '" + str(val) + "' for option '" + p['name'] + "' does not pass validation.")
return val
elif list in p['allowedTypes'] or tuple in p['allowedTypes']:
if not _validate([val], p, options):
raise ValueError("Value "+str([val])+' does not pass validation')
return [val]
elif type(val) == bool and int in p['allowedTypes']: # compatibility problem
return val
elif type(val) == unicode and str in p['allowedTypes']:
return str(val)
else:
raise ValueError('Type of input parameter "' + str(val) + '" is disallowed for option ' +
p['name'])
#print(p, val)
class _paramDialog:
def __init__(self, options, title = '', description='', details='', nCol=1):
#
# now, initialize variables
self.options = options
self.title = title
if nCol is None:
self.nCol = len(self.options)//20 + 1
else:
self.nCol = nCol
self.description = _prettyDesc(description, indent='', width=55*self.nCol)
self.details = details
def setLayout(self, useTk=False):
'''Design a layout for the parameter dialog. Currently only used by wxPython'''
row = 0
for opt in self.options:
if not (opt.has_key('label') or opt.has_key('separator')):
continue
if opt.has_key('separator'):
row += 2
continue
elif opt.has_key('label'):
row += 1
if opt.has_key('chooseFrom'):
if len(opt['chooseFrom']) <= 3 or useTk:
rspan = len(opt['chooseFrom'])
else:
rspan = len(opt['chooseFrom']) * 4 / 5
row += rspan - 1
elif opt.has_key('chooseOneOf') and useTk:
rspan = len(opt['chooseOneOf'])
row += rspan - 1
nRow = row
if nRow // self.nCol * self.nCol == nRow:
nRow = nRow // self.nCol
else:
nRow = nRow // self.nCol + 1
# set row and col for each item.
headerRow = 0
r = 0
c = 0
for opt in self.options:
if not (opt.has_key('label') or opt.has_key('separator')):
continue
if opt.has_key('separator'):
# start of a column
if r == 0:
opt['layout'] = r, c, 1
r += 1
else:
r += 1
# middle, the last one?
if r == nRow - 1:
if c + 1 == self.nCol:
opt['layout'] = r - 1, c, 1
else:
c += 1
opt['layout'] = 0, c, 1
r = 1
else:
opt['layout'] = r, c, 1
r += 1
continue
if opt.has_key('chooseFrom'):
if len(opt['chooseFrom']) <= 3 or useTk:
rspan = len(opt['chooseFrom'])
else:
rspan = len(opt['chooseFrom']) * 4 / 5
opt['layout'] = r, c, rspan
r += rspan
if r >= nRow and c + 1 < self.nCol:
nRow = r
r = 0
c += 1
elif opt.has_key('chooseOneOf') and useTk:
rspan = len(opt['chooseOneOf'])
opt['layout'] = r, c, rspan
r += rspan
if r >= nRow and c + 1 < self.nCol:
nRow = r
r = 0
c += 1
else:
opt['layout'] = r, c, 1
r += 1
if r >= nRow and c + 1 < self.nCol:
nRow = r
r = 0
c += 1
return nRow, self.nCol
def createDialog(self):
raise SystemError('Please define createDialog')
def runDialog(self):
raise SystemError('Please define runDialog')
def getParam(self):
'''Create, run a dialog, return result'''
self.createDialog()
self.runDialog()
#
# after the run has completed
return not self.cancelled
class _tkParamDialog(_paramDialog):
def __init__(self, options, title = '', description='', details='', nCol=1):
''' get options from a given options structure '''
_paramDialog.__init__(self, options, title, description, details, nCol)
# style wise, this seems to be very bad
import Tkinter
import tkFont
if sys.version_info[0] < 3:
globals()['Tkinter'] = Tkinter
globals()['tkFont'] = tkFont
else:
globals()['tkinter'] = tkinter
def denyWindowManagerClose(self):
'''Don't allow WindowManager close'''
x = Tkinter.Tk()
x.withdraw()
x.bell()
x.destroy()
def onHelpOK(self, event):
self.helpDlg.destroy()
def onOpen(self, event):
widget = event.widget
opt = self.options[self.entryWidgets.index(widget)]
import tkFileDialog as fileDlg
if opt['gui_type'] == 'browseFile':
filename = fileDlg.askopenfilename(title=opt['label'])
if filename is not None:
# only available in Python 2.6
widget.delete(0, Tkinter.END)
if 'relpath' in dir(os.path):
widget.insert(0, os.path.relpath(filename))
else:
widget.insert(0, filename)
else:
dirname = fileDlg.askdirectory(title=opt['label'])
if dirname is not None:
widget.delete(0, Tkinter.END)
if 'relpath' in dir(os.path):
widget.insert(0, os.path.relpath(dirname))
else:
widget.insert(0, dirname)
def createHelpDialog(self):
self.helpDlg = Tkinter.Toplevel(self.app)
self.helpDlg.title('Help for ' + self.title)
#
msg = Tkinter.Text(self.helpDlg, wrap=Tkinter.WORD)
msg.insert(Tkinter.END, _usage(self.options, '', self.details))
msg.grid(column=0, row=0, pady=10, padx=10,
sticky = Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
# scrollbar
sb = Tkinter.Scrollbar(self.helpDlg)
sb.config(command=msg.yview)
sb.grid(column=1, row=0, sticky=Tkinter.N + Tkinter.S,
padx=0, pady=10)
msg["yscrollcommand"] = sb.set
self.helpDlg.columnconfigure(0, weight=1)
self.helpDlg.rowconfigure(0, weight=1)
self.helpDlg.rowconfigure(1, weight=0)
okButton = Tkinter.Button(self.helpDlg, takefocus=1, text="OK")
okButton.grid(column=0, row=1, columnspan=2, pady=10, padx=10)
# bind the keyboard events to the widget
okButton.bind("<Return>", self.onHelpOK)
okButton.bind("<Button-1>", self.onHelpOK)
self.helpDlg.bind("<Escape>", self.onHelpOK)
def onHelp(self, event):
self.createHelpDialog()
self.app.wait_window(self.helpDlg)
def onCancel(self, event):
'''When ESC is pressed cancel'''
self.cancelled = True
self.app.quit()
def onOK(self, event):
''' get result and convert values '''
for g in range(len(self.entryWidgets)):
if self.entryWidgets[g] == None:
# for the case of non-GUI default parameter that do not pass validation (e.g. 5 for [5])
if self.options[g].has_key('value'):
self.options[g]['value'] = _getParamValue(self.options[g], self.options[g]['value'], self.options)
continue
try:
if self.options[g]['gui_type'] == 'boolean':
# gets 0/1 for false/true
var = self.options[g]['value'].get()
val = _getParamValue(self.options[g], var == 1, self.options)
elif self.options[g]['gui_type'] == 'chooseOneOf':
sel = self.entryWidgets[g].curselection()
items = self.options[g]['chooseOneOf'][int(sel[0])]
val = _getParamValue(self.options[g], items, self.options)
elif self.options[g]['gui_type'] == 'chooseFrom':
sel = self.entryWidgets[g].curselection()
items = [self.options[g]['chooseFrom'][int(x)] for x in sel]
val = _getParamValue(self.options[g], items, self.options)
else:
val = _getParamValue(self.options[g], self.entryWidgets[g].get(), self.options)
except Exception,e:
for lab in self.labelWidgets:
if lab is not None:
lab.configure(fg='black')
# set this one to red
print('Error handling paramter %s: %s' % (self.options[g]['name'], e))
self.labelWidgets[g].configure(fg='red')
self.entryWidgets[g].focus_force()
return
else:
# convert to values
self.options[g]['value'] = val
# get all results and return
self.cancelled = False
self.app.quit()
def createDialog(self):
self.app = Tkinter.Tk()
self.app.protocol('WM_DELETE_WINDOW', self.denyWindowManagerClose)
self.app.title(self.title)
#
# the main window
self.entryWidgets = [None]*len(self.options)
self.labelWidgets = [None]*len(self.options)
# all use grid management
# top message
topMsg = Tkinter.Label(self.app, text=self.description.strip(), justify=Tkinter.LEFT)
topMsg.grid(row=0, column=0, columnspan = 2 * self.nCol, sticky=Tkinter.W,
padx=10, pady=10)
# find out number of items etc
numRows, numCols = self.setLayout(True)
# all entries
for g,opt in enumerate(self.options):
if not (opt.has_key('label') or opt.has_key('separator')):
continue
r, c, rspan = opt['layout']
# skip the top label...
r += 1
# use different entry method for different types
if opt['gui_type'] == 'separator':
self.labelWidgets[g] = Tkinter.Label(self.app, text=opt['separator'])
f = tkFont.Font(font=self.labelWidgets[g]["font"]).copy()
f.config(weight='bold')
self.labelWidgets[g].config(font=f)
self.labelWidgets[g].grid(column=c*2, row= r,
columnspan=2, ipadx=0, padx=10, sticky=Tkinter.W + Tkinter.N + Tkinter.S)
self.entryWidgets[g] = None
continue
value = self.options[g]['value']
if value is None:
value = self.options[g]['default']
if opt['gui_type'] == 'chooseOneOf': # single choice
self.labelWidgets[g] = Tkinter.Label(self.app, text=opt['label'])
self.labelWidgets[g].grid(column=c*2, row= r,
padx=10, rowspan = 1, sticky=Tkinter.W, pady=2)
self.entryWidgets[g] = Tkinter.Listbox(self.app, selectmode=Tkinter.SINGLE,
exportselection=0, height = rspan)
self.entryWidgets[g].grid(column=c*2+1, row=r,
padx=10, rowspan = rspan, pady=2)
for entry in opt['chooseOneOf']:
self.entryWidgets[g].insert(Tkinter.END, str(entry))
if value is not None:
self.entryWidgets[g].select_set(opt['chooseOneOf'].index(value))
elif opt['gui_type'] == 'chooseFrom': # multiple choice
self.labelWidgets[g] = Tkinter.Label(self.app, text=opt['label'])
self.labelWidgets[g].grid(column=c*2, row=r,
padx=10, sticky=Tkinter.W, pady=2)
self.entryWidgets[g] = Tkinter.Listbox(self.app, selectmode=Tkinter.EXTENDED,
exportselection=0, height = rspan)
self.entryWidgets[g].grid(column=c*2+1, row=r,
padx=10, rowspan = rspan, pady=2)
for entry in opt['chooseFrom']:
self.entryWidgets[g].insert(Tkinter.END, str(entry))
if value is not None:
if type(value) in [tuple, list]:
for val in value:
self.entryWidgets[g].select_set( opt['chooseFrom'].index(val))
else:
self.entryWidgets[g].select_set( opt['chooseFrom'].index( value ))