source: trunk/GSASIIpy3.py @ 933

Last change on this file since 933 was 933, checked in by toby, 8 years ago

Add megawidgets needed for CIF development

  • Property svn:eol-style set to native
File size: 2.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
11# de
12sind = sin = s = lambda x: np.sin(x*np.pi/180.)
13cosd = cos = c = lambda x: np.cos(x*np.pi/180.)
14tand = tan = t = lambda x: np.tan(x*np.pi/180.)
15sqrt = sq = lambda x: np.sqrt(x)
16pi = np.pi
17
18def FormulaEval(string):
19    '''Evaluates a algebraic formula into a float, if possible. Works
20    properly on fractions e.g. 2/3 only with python 3.0+ division.
21
22    Expressions such as 2/3, 3*pi, sin(45)/2, 2*sqrt(2), 2**10 can all
23    be evaluated.
24
25    :param str string: Character string c
26    '''
27    try:
28        val = float(eval(string))
29        if np.isnan(val) or np.isinf(val): return None
30    except:
31        return None
32    return val
33
34def FormatValue(val,maxdigits=10):
35    '''Format a float to fit in maxdigits spaces, showing as much
36    precision as possible, more or less
37    '''
38    # does the standard str() conversion fit?
39    string = str(val)
40    if len(string) <= maxdigits: return string.strip()
41    # negative numbers, leave room for a sign
42    if val < 0: maxdigits -= 1
43    decimals = maxdigits - 2
44    if abs(val) < 1e-99 or abs(val) > 1e99:
45        decimals = maxdigits - 6
46        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" # create format string
47    elif abs(val) < 1e-9 or abs(val) > 1e9:
48        decimals = maxdigits - 5
49        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
50    elif abs(val) < 10**(4-decimals): # make sure at least 4 decimals show
51        decimals = maxdigits - 5
52        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
53    elif abs(val) >= 10**decimals: # deal with large numbers in smaller spaces
54        decimals = maxdigits - 5
55        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
56    elif abs(val) < 1: # use f format for small numbers
57        decimals = maxdigits - 2
58        fmt = "{" + (":{:d}.{:d}f".format(maxdigits,decimals))+"}"
59    else: # in range where g formatting should do what I want
60        decimals = maxdigits - 1
61        fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}"
62    return fmt.format(val).strip()
Note: See TracBrowser for help on using the repository browser.