-
Notifications
You must be signed in to change notification settings - Fork 24
/
__init__.py
1823 lines (1353 loc) · 47.8 KB
/
__init__.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division, absolute_import, print_function
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import operator
import sys
from pytools.decorator import decorator
import six
from six.moves import range, zip, intern, input
from functools import reduce
try:
decorator_module = __import__("decorator", level=0)
except TypeError:
# this must be Python 2.4
my_decorator = decorator
except ImportError:
my_decorator = decorator
else:
my_decorator = decorator_module.decorator
# {{{ math --------------------------------------------------------------------
def delta(x, y):
if x == y:
return 1
else:
return 0
def levi_civita(tup):
"""Compute an entry of the Levi-Civita tensor for the indices *tuple*."""
if len(tup) == 2:
i, j = tup
return j-i
if len(tup) == 3:
i, j, k = tup
return (j-i)*(k-i)*(k-j)/2
else:
raise NotImplementedError
def factorial(n):
from operator import mul
assert n == int(n)
return reduce(mul, (i for i in range(1, n+1)), 1)
def perm(n, k):
"""Return P(n, k), the number of permutations of length k drawn from n
choices.
"""
result = 1
assert k > 0
while k:
result *= n
n -= 1
k -= 1
return result
def comb(n, k):
"""Return C(n, k), the number of combinations (subsets)
of length k drawn from n choices.
"""
return perm(n, k)//factorial(k)
def norm_1(iterable):
return sum(abs(x) for x in iterable)
def norm_2(iterable):
return sum(x**2 for x in iterable)**0.5
def norm_inf(iterable):
return max(abs(x) for x in iterable)
def norm_p(iterable, p):
return sum(i**p for i in iterable)**(1/p)
class Norm(object):
def __init__(self, p):
self.p = p
def __call__(self, iterable):
return sum(i**self.p for i in iterable)**(1/self.p)
# }}}
# {{{ data structures
# {{{ record
class RecordWithoutPickling(object):
"""An aggregate of named sub-variables. Assumes that each record sub-type
will be individually derived from this class.
"""
__slots__ = []
def __init__(self, valuedict=None, exclude=["self"], **kwargs):
assert self.__class__ is not Record
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
if valuedict is not None:
kwargs.update(valuedict)
for key, value in six.iteritems(kwargs):
if key not in exclude:
fields.add(key)
setattr(self, key, value)
def get_copy_kwargs(self, **kwargs):
for f in self.__class__.fields:
if f not in kwargs:
try:
kwargs[f] = getattr(self, f)
except AttributeError:
pass
return kwargs
def copy(self, **kwargs):
return self.__class__(**self.get_copy_kwargs(**kwargs))
def __repr__(self):
return "%s(%s)" % (
self.__class__.__name__,
", ".join("%s=%r" % (fld, getattr(self, fld))
for fld in self.__class__.fields
if hasattr(self, fld)))
def register_fields(self, new_fields):
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
fields.update(new_fields)
class Record(RecordWithoutPickling):
__slots__ = []
def __getstate__(self):
return dict(
(key, getattr(self, key))
for key in self.__class__.fields
if hasattr(self, key))
def __setstate__(self, valuedict):
try:
fields = self.__class__.fields
except AttributeError:
self.__class__.fields = fields = set()
for key, value in six.iteritems(valuedict):
fields.add(key)
setattr(self, key, value)
def __eq__(self, other):
return (self.__class__ == other.__class__
and self.__getstate__() == other.__getstate__())
def __ne__(self, other):
return not self.__eq__(other)
# }}}
class Reference(object):
def __init__(self, value):
self.value = value
def get(self):
from warnings import warn
warn("Reference.get() is deprecated -- use ref.value instead")
return self.value
def set(self, value):
self.value = value
# {{{ dictionary with default
class DictionaryWithDefault(object):
def __init__(self, default_value_generator, start={}):
self._Dictionary = dict(start)
self._DefaultGenerator = default_value_generator
def __getitem__(self, index):
try:
return self._Dictionary[index]
except KeyError:
value = self._DefaultGenerator(index)
self._Dictionary[index] = value
return value
def __setitem__(self, index, value):
self._Dictionary[index] = value
def __contains__(self, item):
return True
def iterkeys(self):
return six.iterkeys(self._Dictionary)
def __iter__(self):
return self._Dictionary.__iter__()
def iteritems(self):
return six.iteritems(self._Dictionary)
# }}}
class FakeList(object):
def __init__(self, f, length):
self._Length = length
self._Function = f
def __len__(self):
return self._Length
def __getitem__(self, index):
try:
return [self._Function(i)
for i in range(*index.indices(self._Length))]
except AttributeError:
return self._Function(index)
# {{{ dependent dictionary ----------------------------------------------------
class DependentDictionary(object):
def __init__(self, f, start={}):
self._Function = f
self._Dictionary = start.copy()
def copy(self):
return DependentDictionary(self._Function, self._Dictionary)
def __contains__(self, key):
try:
self[key]
return True
except KeyError:
return False
def __getitem__(self, key):
try:
return self._Dictionary[key]
except KeyError:
return self._Function(self._Dictionary, key)
def __setitem__(self, key, value):
self._Dictionary[key] = value
def genuineKeys(self): # noqa
return list(self._Dictionary.keys())
def iteritems(self):
return six.iteritems(self._Dictionary)
def iterkeys(self):
return six.iterkeys(self._Dictionary)
def itervalues(self):
return six.itervalues(self._Dictionary)
# }}}
# }}}
# {{{ assertive accessors
def one(iterable):
"""Return the first entry of *iterable*. Assert that *iterable* has only
that one entry.
"""
it = iter(iterable)
try:
v = next(it)
except StopIteration:
raise ValueError("empty iterable passed to 'one()'")
def no_more():
try:
next(it)
raise ValueError("iterable with more than one entry passed to 'one()'")
except StopIteration:
return True
assert no_more()
return v
def is_single_valued(iterable, equality_pred=operator.eq):
it = iter(iterable)
try:
first_item = next(it)
except StopIteration:
raise ValueError("empty iterable passed to 'single_valued()'")
for other_item in it:
if not equality_pred(other_item, first_item):
return False
return True
all_equal = is_single_valued
def all_roughly_equal(iterable, threshold):
return is_single_valued(iterable,
equality_pred=lambda a, b: abs(a-b) < threshold)
def single_valued(iterable, equality_pred=operator.eq):
"""Return the first entry of *iterable*; Assert that other entries
are the same with the first entry of *iterable*.
"""
it = iter(iterable)
try:
first_item = next(it)
except StopIteration:
raise ValueError("empty iterable passed to 'single_valued()'")
def others_same():
for other_item in it:
if not equality_pred(other_item, first_item):
return False
return True
assert others_same()
return first_item
# }}}
# {{{ memoization / attribute storage
def memoize(*args, **kwargs):
"""Stores previously computed function values in a cache.
Two keyword-only arguments are supported:
:arg use_kwargs: Allows the caller to use keyword arguments. Defaults to
``False``. Setting this to ``True`` has a non-negligible performance
impact.
:arg key: A function receiving the same arguments as the decorated function
which computes and returns the cache key.
"""
use_kw = bool(kwargs.pop('use_kwargs', False))
if use_kw:
def default_key_func(*inner_args, **inner_kwargs):
return inner_args, frozenset(six.iteritems(inner_kwargs))
else:
default_key_func = None
key_func = kwargs.pop("key", default_key_func)
if kwargs:
raise TypeError(
"memoize received unexpected keyword arguments: %s"
% ", ".join(list(kwargs.keys())))
if key_func is not None:
@my_decorator
def _deco(func, *args, **kwargs):
# by Michele Simionato
# http://www.phyast.pitt.edu/~micheles/python/
key = key_func(*args, **kwargs)
try:
return func._memoize_dic[key]
except AttributeError:
# _memoize_dic doesn't exist yet.
result = func(*args, **kwargs)
func._memoize_dic = {key: result}
return result
except KeyError:
result = func(*args, **kwargs)
func._memoize_dic[key] = result
return result
else:
@my_decorator
def _deco(func, *args):
# by Michele Simionato
# http://www.phyast.pitt.edu/~micheles/python/
try:
return func._memoize_dic[args]
except AttributeError:
# _memoize_dic doesn't exist yet.
result = func(*args)
func._memoize_dic = {args: result}
return result
except KeyError:
result = func(*args)
func._memoize_dic[args] = result
return result
if not args:
return _deco
if callable(args[0]) and len(args) == 1:
return _deco(args[0])
raise TypeError(
"memoize received unexpected position arguments: %s" % args)
FunctionValueCache = memoize
class _HasKwargs(object):
pass
def memoize_method(method):
"""Supports cache deletion via ``method_name.clear_cache(self)``.
.. note::
*clear_cache* support requires Python 2.5 or newer.
"""
cache_dict_name = intern("_memoize_dic_"+method.__name__)
def wrapper(self, *args, **kwargs):
if kwargs:
key = (_HasKwargs, frozenset(six.iteritems(kwargs))) + args
else:
key = args
try:
return getattr(self, cache_dict_name)[key]
except AttributeError:
result = method(self, *args, **kwargs)
setattr(self, cache_dict_name, {key: result})
return result
except KeyError:
result = method(self, *args, **kwargs)
getattr(self, cache_dict_name)[key] = result
return result
def clear_cache(self):
delattr(self, cache_dict_name)
if sys.version_info >= (2, 5):
from functools import update_wrapper
new_wrapper = update_wrapper(wrapper, method)
new_wrapper.clear_cache = clear_cache
return new_wrapper
def memoize_on_first_arg(function):
"""Like :func:`memoize_method`, but for functions that take the object
to do memoization as first argument.
Supports cache deletion via ``function_name.clear_cache(self)``.
.. note::
*clear_cache* support requires Python 2.5 or newer.
"""
cache_dict_name = intern("_memoize_dic_"
+ function.__module__ + function.__name__)
def wrapper(obj, *args, **kwargs):
if kwargs:
key = (_HasKwargs, frozenset(six.iteritems(kwargs))) + args
else:
key = args
try:
return getattr(obj, cache_dict_name)[key]
except AttributeError:
result = function(obj, *args, **kwargs)
setattr(obj, cache_dict_name, {key: result})
return result
except KeyError:
result = function(obj, *args, **kwargs)
getattr(obj, cache_dict_name)[key] = result
return result
def clear_cache(obj):
delattr(obj, cache_dict_name)
if sys.version_info >= (2, 5):
from functools import update_wrapper
new_wrapper = update_wrapper(wrapper, function)
new_wrapper.clear_cache = clear_cache
return new_wrapper
def memoize_method_with_uncached(uncached_args=[], uncached_kwargs=set()):
"""Supports cache deletion via ``method_name.clear_cache(self)``.
:arg uncached_args: a list of argument numbers
(0-based, not counting 'self' argument)
"""
# delete starting from the end
uncached_args = sorted(uncached_args, reverse=True)
uncached_kwargs = list(uncached_kwargs)
def parametrized_decorator(method):
cache_dict_name = intern("_memoize_dic_"+method.__name__)
def wrapper(self, *args, **kwargs):
cache_args = list(args)
cache_kwargs = kwargs.copy()
for i in uncached_args:
if i < len(cache_args):
cache_args.pop(i)
cache_args = tuple(cache_args)
if kwargs:
for name in uncached_kwargs:
cache_kwargs.pop(name, None)
key = (
(_HasKwargs, frozenset(six.iteritems(cache_kwargs)))
+ cache_args)
else:
key = cache_args
try:
return getattr(self, cache_dict_name)[key]
except AttributeError:
result = method(self, *args, **kwargs)
setattr(self, cache_dict_name, {key: result})
return result
except KeyError:
result = method(self, *args, **kwargs)
getattr(self, cache_dict_name)[key] = result
return result
def clear_cache(self):
delattr(self, cache_dict_name)
if sys.version_info >= (2, 5):
from functools import update_wrapper
new_wrapper = update_wrapper(wrapper, method)
new_wrapper.clear_cache = clear_cache
return new_wrapper
return parametrized_decorator
def memoize_method_nested(inner):
"""Adds a cache to a function nested inside a method. The cache is attached
to *memoize_cache_context* (if it exists) or *self* in the outer (method)
namespace.
Requires Python 2.5 or newer.
"""
from warnings import warn
warn("memoize_method_nested is deprecated. Use @memoize_in(self, 'identifier') "
"instead", DeprecationWarning, stacklevel=2)
from functools import wraps
cache_dict_name = intern("_memoize_inner_dic_%s_%s_%d"
% (inner.__name__, inner.__code__.co_filename,
inner.__code__.co_firstlineno))
from inspect import currentframe
outer_frame = currentframe().f_back
cache_context = outer_frame.f_locals.get("memoize_cache_context")
if cache_context is None:
cache_context = outer_frame.f_locals.get("self")
try:
cache_dict = getattr(cache_context, cache_dict_name)
except AttributeError:
cache_dict = {}
setattr(cache_context, cache_dict_name, cache_dict)
@wraps(inner)
def new_inner(*args):
try:
return cache_dict[args]
except KeyError:
result = inner(*args)
cache_dict[args] = result
return result
return new_inner
class memoize_in(object): # noqa
"""Adds a cache to a function nested inside a method. The cache is attached
to *memoize_cache_context* (if it exists) or *self* in the outer (method)
namespace.
Requires Python 2.5 or newer.
"""
def __init__(self, container, identifier):
key = "_pytools_memoize_in_dict_for_"+identifier
try:
self.cache_dict = getattr(container, key)
except AttributeError:
self.cache_dict = {}
setattr(container, key, self.cache_dict)
def __call__(self, inner):
from functools import wraps
@wraps(inner)
def new_inner(*args):
try:
return self.cache_dict[args]
except KeyError:
result = inner(*args)
self.cache_dict[args] = result
return result
return new_inner
# }}}
# {{{ syntactical sugar
class InfixOperator:
"""Pseudo-infix operators that allow syntax of the kind `op1 <<operator>> op2'.
Following a recipe from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
"""
def __init__(self, function):
self.function = function
def __rlshift__(self, other):
return InfixOperator(lambda x: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def call(self, a, b):
return self.function(a, b)
def monkeypatch_method(cls):
# from GvR, http://mail.python.org/pipermail/python-dev/2008-January/076194.html
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def monkeypatch_class(name, bases, namespace):
# from GvR, http://mail.python.org/pipermail/python-dev/2008-January/076194.html
assert len(bases) == 1, "Exactly one base class required"
base = bases[0]
for name, value in six.iteritems(namespace):
if name != "__metaclass__":
setattr(base, name, value)
return base
# }}}
# {{{ generic utilities
def add_tuples(t1, t2):
return tuple([t1v + t2v for t1v, t2v in zip(t1, t2)])
def negate_tuple(t1):
return tuple([-t1v for t1v in t1])
def shift(vec, dist):
"""Return a copy of C{vec} shifted by C{dist}.
@postcondition: C{shift(a, i)[j] == a[(i+j) % len(a)]}
"""
result = vec[:]
N = len(vec) # noqa
dist = dist % N
# modulo only returns positive distances!
if dist > 0:
result[dist:] = vec[:N-dist]
result[:dist] = vec[N-dist:]
return result
def len_iterable(iterable):
return sum(1 for i in iterable)
def flatten(list):
"""For an iterable of sub-iterables, generate each member of each
sub-iterable in turn, i.e. a flattened version of that super-iterable.
Example: Turn [[a,b,c],[d,e,f]] into [a,b,c,d,e,f].
"""
for sublist in list:
for j in sublist:
yield j
def general_sum(sequence):
return reduce(operator.add, sequence)
def linear_combination(coefficients, vectors):
result = coefficients[0] * vectors[0]
for c, v in zip(coefficients, vectors)[1:]:
result += c*v
return result
def common_prefix(iterable, empty=None):
it = iter(iterable)
try:
pfx = next(it)
except StopIteration:
return empty
for v in it:
for j in range(len(pfx)):
if pfx[j] != v[j]:
pfx = pfx[:j]
if j == 0:
return pfx
break
return pfx
def decorate(function, list):
return [(x, function(x)) for x in list]
def partition(criterion, list):
part_true = []
part_false = []
for i in list:
if criterion(i):
part_true.append(i)
else:
part_false.append(i)
return part_true, part_false
def partition2(iterable):
part_true = []
part_false = []
for pred, i in iterable:
if pred:
part_true.append(i)
else:
part_false.append(i)
return part_true, part_false
def product(iterable):
from operator import mul
return reduce(mul, iterable, 1)
try:
all = __builtins__.all
any = __builtins__.any
except AttributeError:
def all(iterable):
for i in iterable:
if not i:
return False
return True
def any(iterable):
for i in iterable:
if i:
return True
return False
def reverse_dictionary(the_dict):
result = {}
for key, value in six.iteritems(the_dict):
if value in result:
raise RuntimeError(
"non-reversible mapping, duplicate key '%s'" % value)
result[value] = key
return result
def set_sum(set_iterable):
from operator import or_
return reduce(or_, set_iterable, set())
def div_ceil(nr, dr):
return -(-nr // dr)
def uniform_interval_splitting(n, granularity, max_intervals):
""" Return *(interval_size, num_intervals)* such that::
num_intervals * interval_size >= n
and::
(num_intervals - 1) * interval_size < n
and *interval_size* is a multiple of *granularity*.
"""
# ported from Thrust
grains = div_ceil(n, granularity)
# one grain per interval
if grains <= max_intervals:
return granularity, grains
grains_per_interval = div_ceil(grains, max_intervals)
interval_size = grains_per_interval * granularity
num_intervals = div_ceil(n, interval_size)
return interval_size, num_intervals
def find_max_where(predicate, prec=1e-5, initial_guess=1, fail_bound=1e38):
"""Find the largest value for which a predicate is true,
along a half-line. 0 is assumed to be the lower bound."""
# {{{ establish bracket
mag = 1
if predicate(mag):
mag *= 2
while predicate(mag):
mag *= 2
if mag > fail_bound:
raise RuntimeError("predicate appears to be true "
"everywhere, up to %g" % fail_bound)
lower_true = mag/2
upper_false = mag
else:
mag /= 2
while not predicate(mag):
mag /= 2
if mag < prec:
return mag
lower_true = mag
upper_false = mag*2
# }}}
# {{{ refine
# Refine a bracket between *lower_true*, where the predicate is true,
# and *upper_false*, where it is false, until *prec* is satisfied.
assert predicate(lower_true)
assert not predicate(upper_false)
while abs(lower_true-upper_false) > prec:
mid = (lower_true+upper_false)/2
if predicate(mid):
lower_true = mid
else:
upper_false = mid
else:
return lower_true
# }}}
# }}}
# {{{ argmin, argmax
def argmin2(iterable, return_value=False):
it = iter(iterable)
try:
current_argmin, current_min = next(it)
except StopIteration:
raise ValueError("argmin of empty iterable")
for arg, item in it:
if item < current_min:
current_argmin = arg
current_min = item
if return_value:
return current_argmin, current_min
else:
return current_argmin
def argmax2(iterable, return_value=False):
it = iter(iterable)
try:
current_argmax, current_max = next(it)
except StopIteration:
raise ValueError("argmax of empty iterable")
for arg, item in it:
if item > current_max:
current_argmax = arg
current_max = item
if return_value:
return current_argmax, current_max
else:
return current_argmax
def argmin(iterable):
return argmin2(enumerate(iterable))
def argmax(iterable):
return argmax2(enumerate(iterable))
# }}}
# {{{ cartesian products etc.
def cartesian_product(list1, list2):
for i in list1:
for j in list2:
yield (i, j)
def distinct_pairs(list1, list2):
for i, xi in enumerate(list1):
for j, yj in enumerate(list2):
if i != j:
yield (xi, yj)
def cartesian_product_sum(list1, list2):
"""This routine returns a list of sums of each element of
list1 with each element of list2. Also works with lists.
"""
for i in list1:
for j in list2:
yield i+j
# }}}
# {{{ elementary statistics
def average(iterable):