Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / eng_option.py
1 #
2 # Copyright 2004 Free Software Foundation, Inc.
3
4 # This file is part of GNU Radio
5
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20
21
22 '''Add support for engineering notation to optparse.OptionParser'''
23
24 from copy import copy
25 from optparse import Option, OptionValueError
26
27 scale_factor = {}
28 scale_factor['E'] = 1e18
29 scale_factor['P'] = 1e15
30 scale_factor['T'] = 1e12
31 scale_factor['G'] = 1e9
32 scale_factor['M'] = 1e6
33 scale_factor['k'] = 1e3
34 scale_factor['m'] = 1e-3
35 scale_factor['u'] = 1e-6
36 scale_factor['n'] = 1e-9
37 scale_factor['p'] = 1e-12
38 scale_factor['f'] = 1e-15
39 scale_factor['a'] = 1e-18
40
41
42 def check_eng_float (option, opt, value):
43     try:
44         scale = 1.0
45         suffix = value[-1]
46         if scale_factor.has_key (suffix):
47             return float (value[0:-1]) * scale_factor[suffix]
48         return float (value)
49     except:
50         raise OptionValueError (
51             "option %s: invalid engineering notation value: %r" % (opt, value))
52
53 def check_intx (option, opt, value):
54     try:
55         return int (value, 0)
56     except:
57         raise OptionValueError (
58             "option %s: invalid integer value: %r" % (opt, value))
59
60 def check_subdev (option, opt, value):
61     """
62     Value has the form: (A|B)(:0|1)?
63
64     @returns a 2-tuple (0|1, 0|1)
65     """
66     d = { 'A' : (0, 0), 'A:0' : (0, 0), 'A:1' : (0, 1), 'A:2' : (0, 2),
67           'B' : (1, 0), 'B:0' : (1, 0), 'B:1' : (1, 1), 'B:2' : (1, 2) }
68     try:
69         return d[value.upper()]
70     except:
71         raise OptionValueError(
72             "option %s: invalid subdev: '%r', must be one of %s" % (opt, value, ', '.join(sorted(d.keys()))))
73
74 class eng_option (Option):
75     TYPES = Option.TYPES + ("eng_float", "intx", "subdev")
76     TYPE_CHECKER = copy (Option.TYPE_CHECKER)
77     TYPE_CHECKER["eng_float"] = check_eng_float
78     TYPE_CHECKER["intx"] = check_intx
79     TYPE_CHECKER["subdev"] = check_subdev
80