source: trunk/GSASIIpy3.py @ 2569

Last change on this file since 2569 was 2569, checked in by vondreele, 5 years ago

add 'f' or 'g' to maxdigits in FormatValue? in G2py3 - should be revised some more
do a lot of TextCtrl? --> ValidatedTextCtrl? replacements
note that ValidatedTextCtrl? only checks val <= max & not val < max
added tc.event to ValidatedTextCtrl? as some things needed that
G2imgGui - mostly done
G2restrGUI - done
G2pwdGUI - started

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 7.2 KB
Line 
1'''
2*GSASIIpy3: Python 3.x Routines*
3================================
4
5Module to hold python 3-compatible code, to keep it separate from
6code that will break with __future__ options.
7
8'''
9from __future__ import division
10import numpy as np
11import GSASIIpath
12GSASIIpath.SetVersionNumber("$Revision: 2569 $")
13# declare symbol (pi) and functions allowed in expressions
14sind = sin = s = lambda x: np.sin(x*np.pi/180.)
15cosd = cos = c = lambda x: np.cos(x*np.pi/180.)
16tand = tan = t = lambda x: np.tan(x*np.pi/180.)
17sqrt = sq = lambda x: np.sqrt(x)
18pi = np.pi
19
20def FormulaEval(string):
21    '''Evaluates a algebraic formula into a float, if possible. Works
22    properly on fractions e.g. 2/3 only with python 3.0+ division.
23
24    Expressions such as 2/3, 3*pi, sin(45)/2, 2*sqrt(2), 2**10 can all
25    be evaluated.
26
27    :param str string: Character string containing a Python expression
28      to be evaluated.
29
30    :returns: the value for the expression as a float or None if the expression does not
31      evaluate to a valid number.
32   
33    '''
34    try:
35        val = float(eval(string))
36        if np.isnan(val) or np.isinf(val): return None
37    except:
38        return None
39    return val
40
41def FormatPadValue(val,maxdigits=None):
42    '''Format a float to fit in ``maxdigits[0]`` spaces with maxdigits[1] after decimal.
43
44    :param float val: number to be formatted.
45
46    :param list maxdigits: the number of digits & places after decimal to be used for display of the
47      number (defaults to [10,2]).
48
49    :returns: a string with exactly maxdigits[0] characters (except under error conditions),
50      but last character will always be a space
51    '''
52    if maxdigits is None:
53        digits = [10,2]
54    else:
55        digits = list(maxdigits)
56    fmt = '{:'+str(digits[0])+'}'
57    s = fmt.format(FormatValue(val,digits))
58    if s[-1] == ' ':
59        return s
60    else:
61        return s+' '
62   
63
64def FormatValue(val,maxdigits=None):
65    '''Format a float to fit in at most ``maxdigits[0]`` spaces with maxdigits[1] after decimal.
66    Note that this code has been hacked from FormatSigFigs and may have unused sections.
67
68    :param float val: number to be formatted.
69
70    :param list maxdigits: the number of digits, places after decimal and 'f' or 'g' to be used for display of the
71      number (defaults to [10,2,'f']).
72
73    :returns: a string with <= maxdigits characters (usually). 
74    '''
75    if 'str' in str(type(val)) and (val == '?' or val == '.'):
76        return val       
77    if maxdigits is None:
78        digits = [10,2,'f']
79    else:
80        digits = list(maxdigits)
81    if len(digits) == 2:
82        digits.append('g')
83    if not val:
84        digits[2] = 'f'
85    fmt="{:"+str(digits[0])+"."+str(digits[1])+digits[2]+"}"
86    string = fmt.format(float(val)).strip() # will standard .f formatting work?
87    if len(string) <= digits[0]:
88        if ':' in string: # deal with weird bug where a colon pops up in a number when formatting (EPD 7.3.2!)
89            string = str(val)
90        if digits[1] > 0: # strip off extra zeros on right side
91            string = string.rstrip('0')
92            if string[-1] == '.': string += "0"
93        return string
94    if val < 0: digits[0] -= 1 # negative numbers, reserve space for the sign
95    decimals = digits[0] - digits[1]
96    if abs(val) > 1e99: # for very large numbers, use scientific notation and use all digits
97        fmt = "{" + (":{:d}.{:d}g".format(digits[0],digits[0]-6))+"}"
98    elif abs(val) > 1e9:
99        fmt = "{" + (":{:d}.{:d}g".format(digits[0],digits[0]-5))+"}"
100    elif abs(val) < 10**(4-decimals): # make sure at least 4 decimals show
101        # this clause is probably no longer needed since the number probably shows as 0.0
102        decimals = min(digits[0]-5,digits[1])
103        fmt = "{" + (":{:d}.{:d}g".format(digits[0],decimals))+"}"
104    elif abs(val) >= 10**(decimals-1): # deal with large numbers in smaller spaces
105        decimals = max(0,digits[0]-5)
106        fmt = "{" + (":{:d}.{:d}g".format(digits[0],decimals))+"}"
107    elif abs(val) < 1: # use f format for small numbers
108        # this clause is probably no longer needed since the number probably shows as 0.0
109        decimals = min(digits[0]-3,digits[1])
110        fmt = "{" + (":{:d}.{:d}f".format(digits[0],decimals))+"}"
111    else: # in range where g formatting should do what I want
112        # used?
113        decimals = digits[0] - 1
114        fmt = "{" + (":{:d}.{:d}g".format(digits[0],decimals))+"}"
115    try:
116        return fmt.format(float(val)).strip()
117    except ValueError:
118        print 'FormatValue Error with val,maxdigits,fmt=',val,maxdigits,fmt
119        return str(val)
120
121def FormatSigFigs(val, maxdigits=10, sigfigs=5, treatAsZero=1e-20):
122    '''Format a float to use ``maxdigits`` or fewer digits with ``sigfigs``
123    significant digits showing (if room allows).
124
125    :param float val: number to be formatted.
126
127    :param int maxdigits: the number of digits to be used for display of the
128       number (defaults to 10).
129
130    :param int sigfigs: the number of significant figures to use, if room allows
131
132    :param float treatAsZero: numbers that are less than this in magnitude
133      are treated as zero. Defaults to 1.0e-20, but this can be disabled
134      if set to None.
135
136    :returns: a string with <= maxdigits characters (I hope). 
137    '''
138    if 'str' in str(type(val)) and (val == '?' or val == '.'):
139        return val       
140    if treatAsZero is not None:
141        if abs(val) < treatAsZero:
142            return '0.0'
143    # negative numbers, leave room for a sign
144    if val < 0: maxdigits -= 1
145    if abs(val) < 1e-99 or abs(val) > 9.999e99:
146        decimals = min(maxdigits-6,sigfigs)
147        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" # create format string
148    elif abs(val) < 1e-9 or abs(val) > 9.999e9:
149        decimals = min(maxdigits-5,sigfigs)
150        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
151    elif abs(val) < 9.9999999*10**(sigfigs-maxdigits):
152        decimals = min(maxdigits-5,sigfigs)
153        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
154    elif abs(val) >= 10**sigfigs: # deal with large numbers in smaller spaces
155        decimals = min(maxdigits-5,sigfigs)
156        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
157    elif abs(val) < 1: # small numbers, add to decimal places
158        decimals = sigfigs - int(np.log10(abs(val)))
159        fmt = "{" + (":{:d}.{:d}f".format(maxdigits,decimals))+"}"
160    else: # larger numbers, remove decimal places
161        decimals = sigfigs - 1 - int(np.log10(abs(val)))
162        if decimals <= 0: 
163            fmt = "{" + (":{:d}.0f".format(maxdigits))+"}."
164        else:
165            fmt = "{" + (":{:d}.{:d}f".format(maxdigits,decimals))+"}"
166    try:
167        return fmt.format(float(val)).strip()
168    except ValueError:
169        print 'FormatValue Error with val,maxdigits, sigfigs, fmt=',val, maxdigits,sigfigs, fmt
170        return str(val)
171
172if __name__ == '__main__':
173    for i in (1.23456789e-129,1.23456789e129,1.23456789e-99,1.23456789e99,-1.23456789e-99,-1.23456789e99):
174        print FormatSigFigs(i),i
175    for i in (1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000):
176        print FormatSigFigs(1.23456789e-9*i),1.23456789e-9*i
177    for i in (1,10,100,1000,10000,100000,1000000,10000000,100000000):
178        print FormatSigFigs(1.23456789e9/i),1.23456789e9/i
179
180    print FormatSigFigs(200,10,3)
Note: See TracBrowser for help on using the repository browser.