File: tick.py

package info (click to toggle)
pyx3 0.17-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,328 kB
  • sloc: python: 27,656; makefile: 225; ansic: 130; sh: 17
file content (276 lines) | stat: -rw-r--r-- 10,003 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2002-2004 Jörg Lehmann <joerg@pyx-project.org>
# Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
# Copyright (C) 2002-2005 André Wobst <wobsta@pyx-project.org>
#
# This file is part of PyX (https://pyx-project.org/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PyX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyX; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA


import sys, functools

# test automatic long conversion
try:
    sys.maxsize+1
    autolong = 1
except OverflowError:
    autolong = 0


@functools.total_ordering
class rational:
    """rational class performing some basic rational arithmetics
    the axis partitioning uses rational arithmetics (with infinite accuracy)
    basically it contains self.num and self.denom"""

    def initfromstring(self, s):
        "converts a string 0.123 into a rational"
        expparts = s.strip().replace("E", "e").split("e")
        if len(expparts) > 2:
            raise ValueError("multiple 'e' found in '%s'" % s)
        commaparts = expparts[0].split(".")
        if len(commaparts) > 2:
            raise ValueError("multiple '.' found in '%s'" % expparts[0])
        if len(commaparts) == 1:
            commaparts = [commaparts[0], ""]
        self.num = 1
        if autolong:
            self.denom = 10 ** len(commaparts[1])
        else:
            self.denom = 10 ** len(commaparts[1])
        neg = len(commaparts[0]) and commaparts[0][0] == "-"
        if neg:
            commaparts[0] = commaparts[0][1:]
        elif len(commaparts[0]) and commaparts[0][0] == "+":
            commaparts[0] = commaparts[0][1:]
        if len(commaparts[0]):
            if not commaparts[0].isdigit():
                raise ValueError("unrecognized characters in '%s'" % s)
            try:
                x = int(commaparts[0])
            except Exception:
                x = int(commaparts[0])
        else:
            x = 0
        if len(commaparts[1]):
            if not commaparts[1].isdigit():
                raise ValueError("unrecognized characters in '%s'" % s)
            try:
                y = int(commaparts[1])
            except Exception:
                y = int(commaparts[1])
        else:
            y = 0
        self.num = x*self.denom + y
        if neg:
            self.num = -self.num
        if len(expparts) == 2:
            neg = expparts[1][0] == "-"
            if neg:
                expparts[1] = expparts[1][1:]
            elif expparts[1][0] == "+":
                expparts[1] = expparts[1][1:]
            if not expparts[1].isdigit():
                raise ValueError("unrecognized characters in '%s'" % s)
            if neg:
                if autolong:
                    self.denom *= 10 ** int(expparts[1])
                else:
                    self.denom *= 10 ** int(expparts[1])
            else:
                if autolong:
                    self.num *= 10 ** int(expparts[1])
                else:
                    self.num *= 10 ** int(expparts[1])

    def initfromfloat(self, x, floatprecision):
        "converts a float into a rational with finite resolution"
        if floatprecision < 0:
            raise RuntimeError("float resolution must be non-negative")
        self.initfromstring(("%%.%ig" % floatprecision) % x)

    def __init__(self, x, power=1, floatprecision=10):
        """initializes a rational
        - rational=(num/denom)**power
        - x must be one of:
          - a string (like "1.2", "1.2e3", "1.2/3.4", etc.)
          - a float (converted using floatprecision)
          - a sequence of two integers
          - a rational instance"""
        if power == 0:
            self.num = 1
            self.denom = 1
            return
        try:
            # does x behave like a number
            x + 0
        except Exception:
            try:
                # does x behave like a string
                x + ""
            except Exception:
                try:
                    # x might be a tuple
                    self.num, self.denom = x
                except Exception:
                    # otherwise it should have a num and denom
                    self.num, self.denom = x.num, x.denom
            else:
                # x is a string
                fraction = x.split("/")
                if len(fraction) > 2:
                    raise ValueError("multiple '/' found in '%s'" % x)
                self.initfromstring(fraction[0])
                if len(fraction) == 2:
                    self /= rational(fraction[1])
        else:
            # x is a number
            self.initfromfloat(x, floatprecision)
        if not self.denom: raise ZeroDivisionError("zero denominator")
        if power == -1:
            self.num, self.denom = self.denom, self.num
        elif power < -1:
            if autolong:
                self.num, self.denom = self.denom ** (-power), self.num ** (-power)
            else:
                self.num, self.denom = int(self.denom) ** (-power), int(self.num) ** (-power)
        elif power > 1:
            if autolong:
                self.num = self.num ** power
                self.denom = self.denom ** power
            else:
                self.num = int(self.num) ** power
                self.denom = int(self.denom) ** power

    def __lt__(self, other):
        try:
            return self.num * other.denom < other.num * self.denom
        except Exception:
            return float(self) < other

    def __eq__(self, other):
        try:
            return self.num * other.denom == other.num * self.denom
        except Exception:
            return float(self) == other

    def __abs__(self):
        return rational((abs(self.num), abs(self.denom)))

    def __add__(self, other):
        assert abs(other) < 1e-10
        return float(self)

    def __mul__(self, other):
        return rational((self.num * other.num, self.denom * other.denom))

    def __imul__(self, other):
        self.num *= other.num
        self.denom *= other.denom
        return self

    def __div__(self, other):
        return rational((self.num * other.denom, self.denom * other.num))

    __truediv__ = __div__

    def __idiv__(self, other):
        self.num *= other.denom
        self.denom *= other.num
        return self

    __itruediv__ = __idiv__

    def __float__(self):
        "caution: avoid final precision of floats"
        return float(self.num) / self.denom

    def __str__(self):
        return "%i/%i" % (self.num, self.denom)


class tick(rational):
    """tick class
    a tick is a rational enhanced by
    - self.ticklevel (0 = tick, 1 = subtick, etc.)
    - self.labellevel (0 = label, 1 = sublabel, etc.)
    - self.label (a string) and self.labelattrs (a list, defaults to [])
    When ticklevel or labellevel is None, no tick or label is present at that value.
    When label is None, it should be automatically created (and stored), once the
    an axis painter needs it. Classes, which implement _Itexter do precisely that."""

    def __init__(self, x, ticklevel=0, labellevel=0, label=None, labelattrs=[], **kwargs):
        """initializes the instance
        - see class description for the parameter description
        - **kwargs are passed to the rational constructor"""
        rational.__init__(self, x, **kwargs)
        self.ticklevel = ticklevel
        self.labellevel = labellevel
        self.label = label
        self.labelattrs = labelattrs

    def merge(self, other):
        """merges two ticks together:
          - the lower ticklevel/labellevel wins
          - the ticks should be at the same position (otherwise it doesn't make sense)
            -> this is NOT checked"""
        if self.ticklevel is None or (other.ticklevel is not None and other.ticklevel < self.ticklevel):
            self.ticklevel = other.ticklevel
        if self.labellevel is None or (other.labellevel is not None and other.labellevel < self.labellevel):
            self.labellevel = other.labellevel
        if self.label is None:
            self.label = other.label


def mergeticklists(list1, list2, mergeequal=1):
    """helper function to merge tick lists
    - return a merged list of ticks out of list1 and list2
    - CAUTION: original lists have to be ordered
      (the returned list is also ordered)"""
    # TODO: improve along the lines of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269

    # do not destroy original lists
    list1 = list1[:]
    i = 0
    j = 0
    try:
        while True: # we keep on going until we reach an index error
            while list2[j] < list1[i]: # insert tick
               list1.insert(i, list2[j])
               i += 1
               j += 1
            if list2[j] == list1[i]: # merge tick
               if mergeequal:
                   list1[i].merge(list2[j])
               j += 1
            i += 1
    except IndexError:
        if j < len(list2):
            list1 += list2[j:]
    return list1


def maxlevels(ticks):
    "returns a tuple maxticklevel, maxlabellevel from a list of tick instances"
    maxticklevel = maxlabellevel = 0
    for tick in ticks:
        if tick.ticklevel is not None and tick.ticklevel >= maxticklevel:
            maxticklevel = tick.ticklevel + 1
        if tick.labellevel is not None and tick.labellevel >= maxlabellevel:
            maxlabellevel = tick.labellevel + 1
    return maxticklevel, maxlabellevel