/
numerical.py
764 lines (539 loc) · 15.9 KB
/
numerical.py
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
# -*- coding: utf-8 -*-
"""Numerical/mathemetical related functions.
.. versionadded:: 2.1.0
"""
from __future__ import absolute_import, division
import math
import operator
import pydash as pyd
from .helpers import NoValue, iterator_with_default, iteriteratee, iterator
from ._compat import _range
__all__ = (
'add',
'ceil',
'clamp',
'divide',
'floor',
'max_',
'max_by',
'mean',
'mean_by',
'median',
'min_',
'min_by',
'moving_mean',
'multiply',
'power',
'round_',
'scale',
'slope',
'std_deviation',
'sum_',
'sum_by',
'subtract',
'transpose',
'variance',
'zscore',
)
INFINITY = float('inf')
def add(a, b):
"""Adds two numbers.
Args:
a (number): First number to add.
b (number): Second number to add.
Returns:
number
Example:
>>> add(10, 5)
15
.. versionadded:: 2.1.0
.. versionchanged:: 3.3.0
Support adding two numbers when passed as positional arguments.
.. versionchanged:: 4.0.0
Only support two argument addition.
"""
return a + b
def sum_(collection):
"""Sum each element in `collection`.
Args:
collection (list|dict|number): Collection to process or first number to
add.
Returns:
number: Result of summation.
Example:
>>> sum_([1, 2, 3, 4])
10
.. versionadded:: 2.1.0
.. versionchanged:: 3.3.0
Support adding two numbers when passed as positional arguments.
.. versionchanged:: 4.0.0
Move iteratee support to :func:`sum_by`. Move two argument addition to
:func:`add`.
"""
return sum_by(collection)
def sum_by(collection, iteratee=None):
"""Sum each element in `collection`. If iteratee is passed, each element of
`collection` is passed through a iteratee before the summation is computed.
Args:
collection (list|dict|number): Collection to process or first number to
add.
iteratee (mixed|number, optional): Iteratee applied per iteration or
second number to add.
Returns:
number: Result of summation.
Example:
>>> sum_by([1, 2, 3, 4], lambda x: x ** 2)
30
.. versionadded:: 4.0.0
"""
return sum(result[0] for result in iteriteratee(collection, iteratee))
def mean(collection):
"""Calculate arithmetic mean of each element in `collection`.
Args:
collection (list|dict): Collection to process.
Returns:
float: Result of mean.
Example:
>>> mean([1, 2, 3, 4])
2.5
.. versionadded:: 2.1.0
.. versionchanged:: 4.0.0
- Removed ``average`` and ``avg`` aliases.
- Moved iteratee functionality to :func:`mean_by`.
"""
return mean_by(collection)
def mean_by(collection, iteratee=None):
"""Calculate arithmetic mean of each element in `collection`. If iteratee
is passed, each element of `collection` is passed through a iteratee before
the mean is computed.
Args:
collection (list|dict): Collection to process.
iteratee (mixed, optional): Iteratee applied per iteration.
Returns:
float: Result of mean.
Example:
>>> mean_by([1, 2, 3, 4], lambda x: x ** 2)
7.5
.. versionadded:: 4.0.0
"""
return sum_by(collection, iteratee) / len(collection)
def ceil(x, precision=0):
"""Round number up to precision.
Args:
x (number): Number to round up.
precision (int, optional): Rounding precision. Defaults to ``0``.
Returns:
int: Number rounded up.
Example:
>>> ceil(3.275) == 4.0
True
>>> ceil(3.215, 1) == 3.3
True
>>> ceil(6.004, 2) == 6.01
True
.. versionadded:: 3.3.0
"""
return rounder(math.ceil, x, precision)
def clamp(x, lower, upper=None):
"""Clamps number within the inclusive lower and upper bounds.
Args:
x (number): Number to clamp.
lower (number, optional): Lower bound.
upper (number): Upper bound
Returns:
number
Example:
>>> clamp(-10, -5, 5)
-5
>>> clamp(10, -5, 5)
5
>>> clamp(10, 5)
5
>>> clamp(-10, 5)
-10
.. versionadded:: 4.0.0
"""
if upper is None:
upper = lower
lower = x
if x < lower:
x = lower
elif x > upper:
x = upper
return x
def divide(dividend, divisor):
"""Divide two numbers.
Args:
dividend (int/float): The first number in a division.
divisor (int/float): The second number in a division.
Returns:
int/float: Returns the quotient.
Example:
>>> divide(20, 5)
4.0
>>> divide(1.5, 3)
0.5
>>> divide(None, None)
1.0
>>> divide(5, None)
5.0
.. versionadded:: 4.0.0
"""
return call_math_operator(dividend, divisor, operator.truediv, 1)
def floor(x, precision=0):
"""Round number down to precision.
Args:
x (number): Number to round down.
precision (int, optional): Rounding precision. Defaults to ``0``.
Returns:
int: Number rounded down.
Example:
>>> floor(3.75) == 3.0
True
>>> floor(3.215, 1) == 3.2
True
>>> floor(0.046, 2) == 0.04
True
.. versionadded:: 3.3.0
"""
return rounder(math.floor, x, precision)
def max_(collection, default=NoValue):
"""Retrieves the maximum value of a `collection`.
Args:
collection (list|dict): Collection to iterate over.
default (mixed, optional): Value to return if `collection` is empty.
Returns:
mixed: Maximum value.
Example:
>>> max_([1, 2, 3, 4])
4
>>> max_([], default=-1)
-1
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.0
Moved iteratee iteratee support to :func:`max_by`.
"""
return max_by(collection, default=default)
def max_by(collection, iteratee=None, default=NoValue):
"""Retrieves the maximum value of a `collection`.
Args:
collection (list|dict): Collection to iterate over.
iteratee (mixed, optional): Iteratee applied per iteration.
default (mixed, optional): Value to return if `collection` is empty.
Returns:
mixed: Maximum value.
Example:
>>> max_by([1.0, 1.5, 1.8], math.floor)
1.0
>>> max_by([{'a': 1}, {'a': 2}, {'a': 3}], 'a')
{'a': 3}
>>> max_by([], default=-1)
-1
.. versionadded:: 4.0.0
"""
if isinstance(collection, dict):
collection = collection.values()
return max(iterator_with_default(collection, default),
key=pyd.iteratee(iteratee))
def median(collection, iteratee=None):
"""Calculate median of each element in `collection`. If iteratee is passed,
each element of `collection` is passed through a iteratee before the
median is computed.
Args:
collection (list|dict): Collection to process.
iteratee (mixed, optional): Iteratee applied per iteration.
Returns:
float: Result of median.
Example:
>>> median([1, 2, 3, 4, 5])
3
>>> median([1, 2, 3, 4])
2.5
.. versionadded:: 2.1.0
"""
length = len(collection)
middle = (length + 1) / 2
collection = sorted(ret[0] for ret in iteriteratee(collection, iteratee))
if pyd.is_odd(length):
result = collection[int(middle - 1)]
else:
left = int(middle - 1.5)
right = int(middle - 0.5)
result = (collection[left] + collection[right]) / 2
return result
def min_(collection, default=NoValue):
"""Retrieves the minimum value of a `collection`.
Args:
collection (list|dict): Collection to iterate over.
default (mixed, optional): Value to return if `collection` is empty.
Returns:
mixed: Minimum value.
Example:
>>> min_([1, 2, 3, 4])
1
>>> min_([], default=100)
100
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.0
Moved iteratee iteratee support to :func:`min_by`.
"""
return min_by(collection, default=default)
def min_by(collection, iteratee=None, default=NoValue):
"""Retrieves the minimum value of a `collection`.
Args:
collection (list|dict): Collection to iterate over.
iteratee (mixed, optional): Iteratee applied per iteration.
default (mixed, optional): Value to return if `collection` is empty.
Returns:
mixed: Minimum value.
Example:
>>> min_by([1.8, 1.5, 1.0], math.floor)
1.8
>>> min_by([{'a': 1}, {'a': 2}, {'a': 3}], 'a')
{'a': 1}
>>> min_by([], default=100)
100
.. versionadded:: 4.0.0
"""
if isinstance(collection, dict):
collection = collection.values()
return min(iterator_with_default(collection, default),
key=pyd.iteratee(iteratee))
def moving_mean(array, size):
"""Calculate moving mean of each element of `array`.
Args:
array (list): List to process.
size (int): Window size.
Returns:
list: Result of moving average.
Example:
>>> moving_mean(range(10), 1)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
>>> moving_mean(range(10), 5)
[2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
>>> moving_mean(range(10), 10)
[4.5]
.. versionadded:: 2.1.0
.. versionchanged:: 4.0.0
Rename to ``moving_mean`` and remove ``moving_average`` and
``moving_avg`` aliases.
"""
result = []
size = int(size)
for i in _range(size - 1, len(array) + 1):
window = array[i - size:i]
if len(window) == size:
result.append(mean(window))
return result
def multiply(multiplier, multiplicand):
"""Multiply two numbers.
Args:
multiplier (int/float): The first number in a multiplication.
multiplicand (int/float): The second number in a multiplication.
Returns:
int/float: Returns the product.
Example:
>>> multiply(4, 5)
20
>>> multiply(10, 4)
40
>>> multiply(None, 10)
10
>>> multiply(None, None)
1
.. versionadded:: 4.0.0
"""
return call_math_operator(multiplier, multiplicand, operator.mul, 1)
def power(x, n):
"""Calculate exponentiation of `x` raised to the `n` power.
Args:
x (number): Base number.
n (number): Exponent.
Returns:
number: Result of calculation.
Example:
>>> power(5, 2)
25
>>> power(12.5, 3)
1953.125
.. versionadded:: 2.1.0
.. versionchanged:: 4.0.0
Removed alias ``pow_``.
"""
if pyd.is_number(x):
result = pow(x, n)
elif pyd.is_list(x):
result = [pow(item, n) for item in x]
else:
result = None
return result
def round_(x, precision=0):
"""Round number to precision.
Args:
x (number): Number to round.
precision (int, optional): Rounding precision. Defaults to ``0``.
Returns:
int: Rounded number.
Example:
>>> round_(3.275) == 3.0
True
>>> round_(3.275, 1) == 3.3
True
.. versionadded:: 2.1.0
.. versionchanged:: 4.0.0
Remove alias ``curve``.
"""
return rounder(round, x, precision)
def scale(array, maximum=1):
"""Scale list of value to a maximum number.
Args:
array (list): Numbers to scale.
maximum (number): Maximum scale value.
Returns:
list: Scaled numbers.
Example:
>>> scale([1, 2, 3, 4])
[0.25, 0.5, 0.75, 1.0]
>>> scale([1, 2, 3, 4], 1)
[0.25, 0.5, 0.75, 1.0]
>>> scale([1, 2, 3, 4], 4)
[1.0, 2.0, 3.0, 4.0]
>>> scale([1, 2, 3, 4], 2)
[0.5, 1.0, 1.5, 2.0]
.. versionadded:: 2.1.0
"""
array_max = max(array)
factor = maximum / array_max
return [item * factor for item in array]
def slope(point1, point2):
"""Calculate the slope between two points.
Args:
point1 (list|tuple): X and Y coordinates of first point.
point2 (list|tuple): X and Y cooredinates of second point.
Returns:
float: Calculated slope.
Example:
>>> slope((1, 2), (4, 8))
2.0
.. versionadded:: 2.1.0
"""
x1, y1 = point1[0], point1[1]
x2, y2 = point2[0], point2[1]
if x1 == x2:
result = INFINITY
else:
result = (y2 - y1) / (x2 - x1)
return result
def std_deviation(array):
"""Calculate standard deviation of list of numbers.
Args:
array (list): List to process.
Returns:
float: Calculated standard deviation.
Example:
>>> round(std_deviation([1, 18, 20, 4]), 2) == 8.35
True
.. versionadded:: 2.1.0
.. versionchanged:: 4.0.0
Remove alias ``sigma``.
"""
return math.sqrt(variance(array))
def subtract(minuend, subtrahend):
"""Subtracts two numbers.
Args:
minuend (int/float): Value passed in by the user.
subtrahend (int/float): Value passed in by the user.
Returns:
int/float: Result of the difference from the given values.
Example:
>>> subtract(10, 5)
5
>>> subtract(-10, 4)
-14
>>> subtract(2, 0.5)
1.5
.. versionadded:: 4.0.0
"""
return call_math_operator(minuend, subtrahend, operator.sub, 0)
def transpose(array):
"""Transpose the elements of `array`.
Args:
array (list): List to process.
Returns:
list: Transposed list.
Example:
>>> transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
.. versionadded:: 2.1.0
"""
trans = []
for y, row in iterator(array):
for x, col in iterator(row):
trans = pyd.set_(trans, [x, y], col)
return trans
def variance(array):
"""Calculate the variance of the elements in `array`.
Args:
array (list): List to process.
Returns:
float: Calculated variance.
Example:
>>> variance([1, 18, 20, 4])
69.6875
.. versionadded:: 2.1.0
"""
avg = mean(array)
def var(x):
return power(x - avg, 2)
return pyd._(array).map_(var).mean().value()
def zscore(collection, iteratee=None):
"""Calculate the standard score assuming normal distribution. If iteratee
is passed, each element of `collection` is passed through a iteratee before
the standard score is computed.
Args:
collection (list|dict): Collection to process.
iteratee (mixed, optional): Iteratee applied per iteration.
Returns:
float: Calculated standard score.
Example:
>>> results = zscore([1, 2, 3])
# [-1.224744871391589, 0.0, 1.224744871391589]
.. versionadded:: 2.1.0
"""
array = pyd.map_(collection, iteratee)
avg = mean(array)
sig = std_deviation(array)
return [(item - avg) / sig for item in array]
#
# Utility methods not a part of the main API
#
def call_math_operator(value1, value2, op, default):
"""Return the result of the math operation on the given values."""
if not value1:
value1 = default
if not value2:
value2 = default
if not pyd.is_number(value1):
try:
value1 = float(value1)
except Exception:
pass
if not pyd.is_number(value2):
try:
value2 = float(value2)
except Exception:
pass
return op(value1, value2)
def rounder(func, x, precision):
precision = pow(10, precision)
def rounder_func(item):
return func(item * precision) / precision
result = None
if pyd.is_number(x):
result = rounder_func(x)
elif pyd.is_iterable(x):
try:
result = [rounder_func(item) for item in x]
except TypeError:
pass
return result