plotille 6.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of plotille might be problematic. Click here for more details.

@@ -0,0 +1,251 @@
1
+ # The MIT License
2
+
3
+ # Copyright (c) 2017 - 2025 Tammo Ippen, tammo.ippen@posteo.de
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+ import math
24
+ from collections import OrderedDict
25
+ from collections.abc import Callable
26
+ from datetime import date, datetime, time, timedelta
27
+ from typing import Any, Protocol
28
+
29
+ from ._util import roundeven
30
+
31
+
32
+ def _numpy_to_native(x: Any) -> Any:
33
+ # cf. https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html
34
+ if (
35
+ "<class 'numpy." in str(type(x)) or "<type 'numpy." in str(type(x))
36
+ ) and callable(x.item):
37
+ return x.item()
38
+ return x
39
+
40
+
41
+ class Formatter(Protocol):
42
+ def __call__(self, val: Any, chars: int, delta: Any, left: bool) -> str: ...
43
+
44
+
45
+ Converter = Callable[[Any], int | float | datetime]
46
+
47
+
48
+ class InputFormatter:
49
+ def __init__(self) -> None:
50
+ self.formatters: OrderedDict[type, Formatter] = OrderedDict()
51
+
52
+ self.formatters[float] = _num_formatter
53
+ self.formatters[int] = _num_formatter
54
+
55
+ self.formatters[date] = _date_formatter
56
+ self.formatters[datetime] = _datetime_formatter
57
+
58
+ self.formatters[str] = _text_formatter
59
+
60
+ self.converters: OrderedDict[type, Converter] = OrderedDict()
61
+ self.converters[float] = _convert_numbers
62
+ self.converters[int] = _convert_numbers
63
+
64
+ self.converters[date] = _convert_date
65
+ self.converters[datetime] = _convert_datetime
66
+
67
+ try:
68
+ import numpy as np
69
+
70
+ self.converters[np.datetime64] = _convert_np_datetime
71
+ self.formatters[np.datetime64] = _np_datetime_formatter
72
+ except ImportError: # pragma: nocover
73
+ pass
74
+
75
+ def register_formatter(self, t: type, f: Formatter) -> None:
76
+ self.formatters[t] = f
77
+
78
+ def register_converter(self, t: type, f: Converter) -> None:
79
+ self.converters[t] = f
80
+
81
+ def fmt(self, val: Any, delta: Any, left: bool = False, chars: int = 9) -> str:
82
+ val = _numpy_to_native(val)
83
+ for t, f in reversed(self.formatters.items()):
84
+ if isinstance(val, t):
85
+ return f(val, chars=chars, delta=delta, left=left)
86
+
87
+ return str(val)
88
+
89
+ def convert(self, val: Any) -> Any:
90
+ for t, f in reversed(self.converters.items()):
91
+ if isinstance(val, t):
92
+ return f(val)
93
+
94
+ return val
95
+
96
+
97
+ def _np_datetime_formatter(val: Any, chars: int, delta: Any, left: bool = False) -> str:
98
+ # assert isinstance(val, np.datetime64)
99
+ # assert isinstance(delta, np.timedelta64)
100
+
101
+ return _datetime_formatter(val.item(), chars, delta.item(), left)
102
+
103
+
104
+ def _date_formatter(val: date, chars: int, delta: timedelta, left: bool = False) -> str:
105
+ assert isinstance(val, date)
106
+ assert isinstance(delta, timedelta)
107
+
108
+ val_dt = datetime.combine(val, time.min)
109
+ return _datetime_formatter(val_dt, chars, delta, left)
110
+
111
+
112
+ def _datetime_formatter(
113
+ val: datetime, chars: int, delta: timedelta, left: bool = False
114
+ ) -> str:
115
+ assert isinstance(val, datetime)
116
+ assert isinstance(delta, timedelta)
117
+
118
+ if chars < 8:
119
+ raise ValueError(
120
+ f'Not possible to display value "{val}" with {chars} characters!'
121
+ )
122
+
123
+ res = ""
124
+
125
+ if delta.days <= 0:
126
+ # make time representation
127
+ if chars < 15:
128
+ res = f"{val.hour:02d}:{val.minute:02d}:{val.second:02d}"
129
+ else:
130
+ res = f"{val.hour:02d}:{val.minute:02d}:{val.second:02d}.{val.microsecond:06d}"
131
+ elif 1 <= delta.days <= 10:
132
+ # make day / time representation
133
+ if chars < 11:
134
+ res = f"{val.day:02d}T{val.hour:02d}:{val.minute:02d}"
135
+ else:
136
+ res = f"{val.day:02d}T{val.hour:02d}:{val.minute:02d}:{val.second:02d}"
137
+ # make date representation
138
+ elif chars < 10:
139
+ res = f"{val.year % 100:02d}-{val.month:02d}-{val.day:02d}"
140
+ else:
141
+ res = f"{val.year:04d}-{val.month:02d}-{val.day:02d}"
142
+
143
+ if left:
144
+ return res.ljust(chars)
145
+ else:
146
+ return res.rjust(chars)
147
+
148
+
149
+ def _num_formatter(
150
+ val: int | float, chars: int, delta: int | float, left: bool = False
151
+ ) -> str:
152
+ if not isinstance(val, (int, float)):
153
+ raise TypeError(
154
+ "Only accepting numeric (int/long/float) "
155
+ f'types, not "{val}" of type: {type(val)}'
156
+ )
157
+
158
+ # about float (f32) machine precision
159
+ if abs(val - roundeven(val)) < 1e-8:
160
+ val = int(roundeven(val))
161
+
162
+ if isinstance(val, int):
163
+ return _int_formatter(val, chars, left)
164
+ elif isinstance(val, float):
165
+ return _float_formatter(val, chars, left)
166
+ # unreachable
167
+
168
+
169
+ def _float_formatter(val: float, chars: int, left: bool = False) -> str:
170
+ assert isinstance(val, float)
171
+ if math.isinf(val):
172
+ return str(val).ljust(chars) if left else str(val).rjust(chars)
173
+ sign = 1 if val < 0 else 0
174
+ order = 0 if val == 0 else math.log10(abs(val))
175
+ align = "<" if left else ""
176
+
177
+ if order >= 0:
178
+ # larger than 1 values or smaller than -1
179
+ digits = math.ceil(order)
180
+ fractionals = int(max(0, chars - 1 - digits - sign))
181
+ if digits + sign > chars:
182
+ return _large_pos(val, chars, left, digits, sign)
183
+
184
+ return "{:{}{}.{}f}".format(val, align, chars, fractionals)
185
+ else:
186
+ # between -1 and 1 values
187
+ order = abs(math.floor(order))
188
+
189
+ if order > 4: # e-04 4 digits
190
+ exp_digits = int(max(2, math.ceil(math.log10(order))))
191
+ exp_digits += 2 # the - sign and the e
192
+
193
+ return "{:{}{}.{}e}".format(
194
+ val, align, chars, chars - exp_digits - 2 - sign
195
+ )
196
+ else:
197
+ return "{:{}{}.{}f}".format(val, align, chars, chars - 2 - sign)
198
+
199
+
200
+ def _int_formatter(val: int, chars: int, left: bool = False) -> str:
201
+ assert isinstance(val, int)
202
+ if val != 0:
203
+ sign = 1 if val < 0 else 0
204
+ digits = math.ceil(math.log10(abs(val)))
205
+ if digits + sign > chars:
206
+ return _large_pos(val, chars, left, digits, sign)
207
+ align = "<" if left else ""
208
+ return "{:{}{}d}".format(val, align, chars)
209
+
210
+
211
+ def _large_pos(val: float | int, chars: int, left: bool, digits: int, sign: int) -> str:
212
+ align = "<" if left else ""
213
+ # exponent is always + and has at least two digits (1.3e+06)
214
+ exp_digits = max(2, math.ceil(math.log10(digits)))
215
+ exp_digits += 2 # the + sign and the e
216
+ front_digits = chars - exp_digits - sign
217
+ residual_digits = int(max(0, front_digits - 2))
218
+ if front_digits < 1:
219
+ raise ValueError(
220
+ f'Not possible to display value "{val}" with {chars} characters!'
221
+ )
222
+ return "{:{}{}.{}e}".format(val, align, chars, residual_digits)
223
+
224
+
225
+ def _text_formatter(val: str, chars: int, delta: str, left: bool = False) -> str:
226
+ if left:
227
+ return val[:chars].ljust(chars)
228
+ else:
229
+ return val[:chars].rjust(chars)
230
+
231
+
232
+ def _convert_numbers(v: float | int) -> float:
233
+ assert isinstance(v, float) or isinstance(v, int)
234
+ return v
235
+
236
+
237
+ def _convert_np_datetime(v: Any) -> float:
238
+ # assert isinstance(v, np.datetime64)
239
+ v = v.item().timestamp()
240
+ assert isinstance(v, float)
241
+ return v
242
+
243
+
244
+ def _convert_date(v: date) -> int:
245
+ assert isinstance(v, date)
246
+ return (v - date.min).days
247
+
248
+
249
+ def _convert_datetime(v: datetime) -> float:
250
+ assert isinstance(v, datetime)
251
+ return v.timestamp()
plotille/_util.py ADDED
@@ -0,0 +1,92 @@
1
+ # The MIT License
2
+
3
+ # Copyright (c) 2017 - 2025 Tammo Ippen, tammo.ippen@posteo.de
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+ import math
24
+ from collections.abc import Sequence
25
+ from datetime import datetime
26
+
27
+ DataValue = float | int | datetime
28
+ """Basically any datetime like value and any numeric value.
29
+
30
+ Eventually, you have to add a float_converter for the type, e.g. with Decimal see
31
+ test `test_timeseries_decimals`.
32
+
33
+ There are already converters for numpy numeric and datetime data.
34
+ """
35
+ DataValues = Sequence[float | int] | Sequence[datetime]
36
+ """Either a list of numeric data or a list of datetime like data."""
37
+
38
+
39
+ def roundeven(x: float) -> float:
40
+ """Round to next even integer number in case of `X.5`
41
+
42
+ Parameters:
43
+ x: float The number to round.
44
+
45
+ Returns:
46
+ int: floor(x) if x - floor(x) < 0.5
47
+ ceil(x) if x - floor(x) > 0.5
48
+ next even of x if x - floor(x) == 0.5
49
+ """
50
+ if math.isinf(x) or math.isnan(x):
51
+ return x # same behaviour as in python2
52
+ return round(x)
53
+
54
+
55
+ def hist(X: Sequence[float], bins: int) -> tuple[list[int], list[float]]:
56
+ """Create histogram similar to `numpy.hist()`
57
+
58
+ NOTE: This function expects X to be already normalized to numeric.
59
+
60
+ Parameters:
61
+ X: Sequence[float] Already normalized to float (timestamps if datetime)
62
+ bins: int The number of bins to put X entries in.
63
+
64
+ Returns:
65
+ (counts, bins):
66
+ counts: list[int] The counts for all bins.
67
+ bins: list[float] The range for each bin:
68
+ bin `i` is in [bins[i], bins[i+1])
69
+ """
70
+ assert bins > 0
71
+
72
+ if len(X) == 0:
73
+ xmin = 0.0
74
+ xmax = 1.0
75
+ else:
76
+ xmin = float(min(X))
77
+ xmax = float(max(X))
78
+
79
+ if xmin == xmax:
80
+ xmin -= 0.5
81
+ xmax += 0.5
82
+
83
+ delta = xmax - xmin
84
+ xwidth = delta / bins
85
+
86
+ y = [0] * bins
87
+ for x in X:
88
+ delta_x = x - xmin
89
+ x_idx = min(bins - 1, int(delta_x // xwidth))
90
+ y[x_idx] += 1
91
+
92
+ return y, [i * xwidth + xmin for i in range(bins + 1)]
plotille/data.py ADDED
@@ -0,0 +1,100 @@
1
+ # The MIT License
2
+
3
+ # Copyright (c) 2017 - 2025 Tammo Ippen, tammo.ippen@posteo.de
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+ from math import cos, pi, sin
24
+ from typing import Union
25
+
26
+
27
+ def ellipse(
28
+ x_center: Union[float, int],
29
+ y_center: Union[float, int],
30
+ angle: Union[float, int] = 0,
31
+ x_amplitude: Union[float, int] = 1,
32
+ y_amplitude: Union[float, int] = 1,
33
+ n: int = 20,
34
+ ) -> tuple[list[float], list[float]]:
35
+ r"""Create X and Y values for an ellipse.
36
+
37
+ Parameters:
38
+ x_center: float X-coordinate of the center of the ellipse.
39
+ y_center: float Y-coordinate of the center of the ellipse.
40
+ angle: float Rotation angle of the ellipse \in [0 .. 2pi] .
41
+ x_amplitude: float The radius in X-direction before rotation.
42
+ y_amplitude: float The radius in Y-direction before rotation.
43
+ n: int The number of points to return. The ellipse is
44
+ closed, hence the function actually return n+1 points.
45
+
46
+ Returns:
47
+ X, Y: Tuple[List[float], List[float]]
48
+ The X and Y values for the ellipse.
49
+ """
50
+ # see https://en.wikipedia.org/wiki/Ellipse#Parametric_representation
51
+ assert isinstance(n, int)
52
+ assert n > 0
53
+ assert isinstance(x_amplitude, (int, float))
54
+ assert x_amplitude > 0
55
+ assert isinstance(y_amplitude, (int, float))
56
+ assert y_amplitude > 0
57
+
58
+ max_ = 2 * pi
59
+ step = max_ / n
60
+ ell_x = []
61
+ ell_y = []
62
+ # rename just to conform to the formula in wiki.
63
+ a = x_amplitude
64
+ b = y_amplitude
65
+ cos_angle = cos(angle)
66
+ sin_angle = sin(angle)
67
+
68
+ for i in range(n + 1):
69
+ t = step * i
70
+ x = a * cos_angle * cos(t) - b * sin_angle * sin(t)
71
+ y = a * sin_angle * cos(t) + b * cos_angle * sin(t)
72
+
73
+ ell_x.append(x + x_center)
74
+ ell_y.append(y + y_center)
75
+
76
+ return ell_x, ell_y
77
+
78
+
79
+ def circle(
80
+ x_center: Union[float, int],
81
+ y_center: Union[float, int],
82
+ radius: Union[float, int],
83
+ n: int = 20,
84
+ ) -> tuple[list[float], list[float]]:
85
+ """Create X and Y values for a circle.
86
+
87
+ Parameters:
88
+ x_center: float X-coordinate of the center of the circle.
89
+ y_center: float Y-coordinate of the center of the circle.
90
+ radius: float The radius of the circle.
91
+ n: int The number of points to return. The circle is
92
+ closed, hence the function actually return n+1 points.
93
+
94
+ Returns:
95
+ X, Y: Tuple[List[float], List[float]]
96
+ The X and Y values for the circle.
97
+ """
98
+ assert isinstance(radius, (int, float))
99
+ assert radius > 0
100
+ return ellipse(x_center, y_center, x_amplitude=radius, y_amplitude=radius, n=n)