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