d810d1991875935ce83d8f46d803978a87818340
[hooke.git] / hooke / ui / gui / formatter.py
1 # Copyright
2
3 """A number formatting utilities for Hooke.
4 """
5
6 from matplotlib.ticker import ScalarFormatter
7
8 from . import curve as lhc
9
10
11 class EngrFormatter(ScalarFormatter):
12     """A variation of the standard ScalarFormatter, using only multiples of 
13 three
14 in the mantissa. A fixed number of decimals can be displayed with the optional 
15 parameter `ndec` . If `ndec` is None (default), the number of decimals is 
16 defined
17 from the current ticks.
18     """
19     def __init__(self, ndec=None, useOffset=True, useMathText=False):
20         ScalarFormatter.__init__(self, useOffset, useMathText)
21         if ndec is None or ndec < 0:
22             self.format = None
23         elif ndec == 0:
24             self.format = "%d"
25         else:
26             self.format = "%%1.%if" % ndec
27
28     def _set_orderOfMagnitude(self, mrange):
29             """Sets the order of magnitude."""        
30             locs = numpy.absolute(self.locs)
31             if self.offset: 
32                 oom = numpy.floor(numpy.log10(mrange))
33             else:
34                 if locs[0] > locs[-1]: 
35                     val = locs[0]
36                 else: 
37                     val = locs[-1]
38                 if val == 0: 
39                     oom = 0
40                 else: 
41                     oom = numpy.floor(numpy.log10(val))
42             if oom <= -3:
43                 self.orderOfMagnitude = 3*(oom//3)
44             elif oom <= -1:
45                 self.orderOfMagnitude = -3
46             elif oom >= 4:
47                 self.orderOfMagnitude = 3*(oom//3)
48             else:
49                 self.orderOfMagnitude = 0
50
51     def _set_format(self):
52         """Sets the format string to format all ticklabels."""
53         # set the format string to format all the ticklabels
54         locs = (numpy.array(self.locs)-self.offset) /  10**self.orderOfMagnitude+1e-15
55         sigfigs = [len(str('%1.3f'% loc).split('.')[1].rstrip('0')) \
56                    for loc in locs]
57         sigfigs.sort()
58         if self.format is None:
59             self.format = '%1.' + str(sigfigs[-1]) + 'f'
60         if self._usetex or self._useMathText: self.format = '$%s$'%self.format