This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
cachefunc.pyx
3636 lines (3057 loc) · 120 KB
/
cachefunc.pyx
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
r"""
Cached Functions and Methods
AUTHORS:
- William Stein: initial version, (inspired by conversation with Justin Walker)
- Mike Hansen: added doctests and made it work with class methods.
- Willem Jan Palenstijn: add CachedMethodCaller for binding cached methods to
instances.
- Tom Boothby: added DiskCachedFunction.
- Simon King: improved performance, more doctests, cython version,
CachedMethodCallerNoArgs, weak cached function, cached special methods.
- Julian Rueth (2014-03-19, 2014-05-09): added ``key`` parameter, allow caching
for unhashable elements
EXAMPLES:
By :trac:`11115`, cached functions and methods are now also
available in Cython code. The following examples cover various ways
of usage.
Python functions::
sage: @cached_function
....: def test_pfunc(x):
....: '''
....: Some documentation
....: '''
....: return -x
sage: test_pfunc(5) is test_pfunc(5)
True
In some cases, one would only want to keep the result in cache as long
as there is any other reference to the result. By :trac:`12215`, this is
enabled for :class:`~sage.structure.unique_representation.UniqueRepresentation`,
which is used to create unique parents: If an algebraic structure, such
as a finite field, is only temporarily used, then it will not stay in
cache forever. That behaviour is implemented using ``weak_cached_function``,
that behaves the same as ``cached_function``, except that it uses a
:class:`~sage.misc.weak_dict.WeakValueDictionary` for storing the results.
::
sage: from sage.misc.cachefunc import weak_cached_function
sage: class A: pass
sage: @weak_cached_function
....: def f():
....: print "doing a computation"
....: return A()
sage: a = f()
doing a computation
The result is cached::
sage: b = f()
sage: a is b
True
However, if there are no strong references left, the result
may be garbage collected, and thus a new computation would
take place::
sage: del a
sage: del b
sage: import gc
sage: n = gc.collect()
sage: a = f()
doing a computation
Cython cdef functions do not allow arbitrary decorators.
However, one can wrap a Cython function and turn it into
a cached function, by :trac:`11115`. We need to provide
the name that the wrapped method or function should have,
since otherwise the name of the original function would
be used::
sage: cython('''cpdef test_funct(x): return -x''')
sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')
sage: wrapped_funct
Cached version of <built-in function test_funct>
sage: wrapped_funct.__name__
'wrapped_funct'
sage: wrapped_funct(5)
-5
sage: wrapped_funct(5) is wrapped_funct(5)
True
We can proceed similarly for cached methods of Cython classes,
provided that they allow attribute assignment or have a public
attribute ``__cached_methods`` of type ``<dict>``. Since
:trac:`11115`, this is the case for all classes inheriting from
:class:`~sage.structure.parent.Parent`. See below for a more explicit
example. By :trac:`12951`, cached methods of extension classes can
be defined by simply using the decorater. However, an indirect
approach is still needed for cpdef methods::
sage: cython_code = ['cpdef test_meth(self,x):',
....: ' "some doc for a wrapped cython method"',
....: ' return -x',
....: 'from sage.all import cached_method',
....: 'from sage.structure.parent cimport Parent',
....: 'cdef class MyClass(Parent):',
....: ' @cached_method',
....: ' def direct_method(self, x):',
....: ' "Some doc for direct method"',
....: ' return 2*x',
....: ' wrapped_method = cached_method(test_meth,name="wrapped_method")']
sage: cython(os.linesep.join(cython_code))
sage: O = MyClass()
sage: O.direct_method
Cached version of <method 'direct_method' of '...MyClass' objects>
sage: O.wrapped_method
Cached version of <built-in function test_meth>
sage: O.wrapped_method.__name__
'wrapped_method'
sage: O.wrapped_method(5)
-5
sage: O.wrapped_method(5) is O.wrapped_method(5)
True
sage: O.direct_method(5)
10
sage: O.direct_method(5) is O.direct_method(5)
True
In some cases, one would only want to keep the result in cache as long
as there is any other reference to the result. By :trac:`12215`, this is
enabled for :class:`~sage.structure.unique_representation.UniqueRepresentation`,
which is used to create unique parents: If an algebraic structure, such
as a finite field, is only temporarily used, then it will not stay in
cache forever. That behaviour is implemented using ``weak_cached_function``,
that behaves the same as ``cached_function``, except that it uses a
:class:`~sage.misc.weak_dict.WeakValueDictionary` for storing the results.
::
sage: from sage.misc.cachefunc import weak_cached_function
sage: class A: pass
sage: @weak_cached_function
....: def f():
....: print "doing a computation"
....: return A()
sage: a = f()
doing a computation
The result is cached::
sage: b = f()
sage: a is b
True
However, if there are no strong references left, the result
may be garbage collected, and thus a new computation would
take place::
sage: del a
sage: del b
sage: import gc
sage: n = gc.collect()
sage: a = f()
doing a computation
By :trac:`11115`, even if a parent does not allow attribute
assignment, it can inherit a cached method from the parent class of a
category (previously, the cache would have been broken)::
sage: cython_code = ["from sage.all import cached_method, cached_in_parent_method, Category, Objects",
....: "class MyCategory(Category):",
....: " @cached_method",
....: " def super_categories(self):",
....: " return [Objects()]",
....: " class ElementMethods:",
....: " @cached_method",
....: " def element_cache_test(self):",
....: " return -self",
....: " @cached_in_parent_method",
....: " def element_via_parent_test(self):",
....: " return -self",
....: " class ParentMethods:",
....: " @cached_method",
....: " def one(self):",
....: " return self.element_class(self,1)",
....: " @cached_method",
....: " def invert(self, x):",
....: " return -x"]
sage: cython('\n'.join(cython_code))
sage: C = MyCategory()
In order to keep the memory footprint of elements small, it was
decided to not support the same freedom of using cached methods
for elements: If an instance of a class derived from
:class:`~sage.structure.element.Element` does not allow attribute
assignment, then a cached method inherited from the category of
its parent will break, as in the class ``MyBrokenElement`` below.
However, there is a class :class:`~sage.structure.element.ElementWithCachedMethod`
that has generally a slower attribute access, but fully supports
cached methods. We remark, however, that cached methods are
*much* faster if attribute access works. So, we expect that
:class:`~sage.structure.element.ElementWithCachedMethod` will
hardly by used.
::
sage: cython_code = ["from sage.structure.element cimport Element, ElementWithCachedMethod",
....: "cdef class MyBrokenElement(Element):",
....: " cdef public object x",
....: " def __init__(self,P,x):",
....: " self.x=x",
....: " Element.__init__(self,P)",
....: " def __neg__(self):",
....: " return MyBrokenElement(self.parent(),-self.x)",
....: " def _repr_(self):",
....: " return '<%s>'%self.x",
....: " def __hash__(self):",
....: " return hash(self.x)",
....: " def __cmp__(left, right):",
....: " return (<Element>left)._cmp(right)",
....: " def __richcmp__(left, right, op):",
....: " return (<Element>left)._richcmp(right,op)",
....: " cdef int _cmp_c_impl(left, Element right) except -2:",
....: " return cmp(left.x,right.x)",
....: " def raw_test(self):",
....: " return -self",
....: "cdef class MyElement(ElementWithCachedMethod):",
....: " cdef public object x",
....: " def __init__(self,P,x):",
....: " self.x=x",
....: " ElementWithCachedMethod.__init__(self,P)",
....: " def __neg__(self):",
....: " return MyElement(self.parent(),-self.x)",
....: " def _repr_(self):",
....: " return '<%s>'%self.x",
....: " def __hash__(self):",
....: " return hash(self.x)",
....: " def __cmp__(left, right):",
....: " return (<Element>left)._cmp(right)",
....: " def __richcmp__(left, right, op):",
....: " return (<Element>left)._richcmp(right,op)",
....: " cdef int _cmp_c_impl(left, Element right) except -2:",
....: " return cmp(left.x,right.x)",
....: " def raw_test(self):",
....: " return -self",
....: "from sage.structure.parent cimport Parent",
....: "cdef class MyParent(Parent):",
....: " Element = MyElement"]
sage: cython('\n'.join(cython_code))
sage: P = MyParent(category=C)
sage: ebroken = MyBrokenElement(P,5)
sage: e = MyElement(P,5)
The cached methods inherited by the parent works::
sage: P.one()
<1>
sage: P.one() is P.one()
True
sage: P.invert(e)
<-5>
sage: P.invert(e) is P.invert(e)
True
The cached methods inherited by ``MyElement`` works::
sage: e.element_cache_test()
<-5>
sage: e.element_cache_test() is e.element_cache_test()
True
sage: e.element_via_parent_test()
<-5>
sage: e.element_via_parent_test() is e.element_via_parent_test()
True
The other element class can only inherit a ``cached_in_parent_method``, since
the cache is stored in the parent. In fact, equal elements share the cache,
even if they are of different types::
sage: e == ebroken
True
sage: type(e) == type(ebroken)
False
sage: ebroken.element_via_parent_test() is e.element_via_parent_test()
True
However, the cache of the other inherited method breaks, although the method
as such works::
sage: ebroken.element_cache_test()
<-5>
sage: ebroken.element_cache_test() is ebroken.element_cache_test()
False
The cache can be emptied::
sage: a = test_pfunc(5)
sage: test_pfunc.clear_cache()
sage: a is test_pfunc(5)
False
sage: a = P.one()
sage: P.one.clear_cache()
sage: a is P.one()
False
Since ``e`` and ``ebroken`` share the cache, when we empty it for one element
it is empty for the other as well::
sage: b = ebroken.element_via_parent_test()
sage: e.element_via_parent_test.clear_cache()
sage: b is ebroken.element_via_parent_test()
False
Introspection works::
sage: from sage.misc.edit_module import file_and_line
sage: from sage.misc.sageinspect import sage_getdoc, sage_getfile, sage_getsource
sage: print sage_getdoc(test_pfunc)
Some documentation
sage: print sage_getdoc(O.wrapped_method)
some doc for a wrapped cython method
<BLANKLINE>
sage: print sage_getdoc(O.direct_method)
Some doc for direct method
<BLANKLINE>
sage: print sage_getsource(O.wrapped_method)
cpdef test_meth(self,x):
"some doc for a wrapped cython method"
return -x
sage: print sage_getsource(O.direct_method)
def direct_method(self, x):
"Some doc for direct method"
return 2*x
It is a very common special case to cache a method that has no
arguments. In that special case, the time needed to access the cache
can be drastically reduced by using a special implementation. The
cached method decorator automatically determines which implementation
ought to be chosen. A typical example is
:meth:`sage.rings.polynomial.multi_polynomial_ideal.MPolynomialIdeal.gens`
(no arguments) versus
:meth:`sage.rings.polynomial.multi_polynomial_ideal.MPolynomialIdeal.groebner_basis`
(several arguments)::
sage: P.<a,b,c,d> = QQ[]
sage: I = P*[a,b]
sage: I.gens()
[a, b]
sage: I.gens() is I.gens()
True
sage: I.groebner_basis()
[a, b]
sage: I.groebner_basis() is I.groebner_basis()
True
sage: type(I.gens)
<type 'sage.misc.cachefunc.CachedMethodCallerNoArgs'>
sage: type(I.groebner_basis)
<type 'sage.misc.cachefunc.CachedMethodCaller'>
By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
methods of extension classes, as long as they either support attribute assignment
or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
latter is easy::
sage: cython_code = [
....: "from sage.misc.cachefunc import cached_method",
....: "cdef class MyClass:",
....: " cdef public dict __cached_methods",
....: " @cached_method",
....: " def f(self, a,b):",
....: " return a*b"]
sage: cython(os.linesep.join(cython_code))
sage: P = MyClass()
sage: P.f(2,3)
6
sage: P.f(2,3) is P.f(2,3)
True
Providing attribute access is a bit more tricky, since it is needed that
an attribute inherited by the instance from its class can be overridden
on the instance. That is why providing a ``__getattr__`` would not be
enough in the following example::
sage: cython_code = [
....: "from sage.misc.cachefunc import cached_method",
....: "cdef class MyOtherClass:",
....: " cdef dict D",
....: " def __init__(self):",
....: " self.D = {}",
....: " def __setattr__(self, n,v):",
....: " self.D[n] = v",
....: " def __getattribute__(self, n):",
....: " try:",
....: " return self.D[n]",
....: " except KeyError:",
....: " pass",
....: " return getattr(type(self),n).__get__(self)",
....: " @cached_method",
....: " def f(self, a,b):",
....: " return a+b"]
sage: cython(os.linesep.join(cython_code))
sage: Q = MyOtherClass()
sage: Q.f(2,3)
5
sage: Q.f(2,3) is Q.f(2,3)
True
Note that supporting attribute access is somehow faster than the
easier method::
sage: timeit("a = P.f(2,3)") # random
625 loops, best of 3: 1.3 µs per loop
sage: timeit("a = Q.f(2,3)") # random
625 loops, best of 3: 931 ns per loop
Some immutable objects (such as `p`-adic numbers) cannot implement a
reasonable hash function because their ``==`` operator has been
modified to return ``True`` for objects which might behave differently
in some computations::
sage: K.<a> = Qq(9)
sage: b = a.add_bigoh(1)
sage: c = a + 3
sage: b
a + O(3)
sage: c
a + 3 + O(3^20)
sage: b == c
True
sage: b == a
True
sage: c == a
False
If such objects defined a non-trivial hash function, this would break
caching in many places. However, such objects should still be usable
in caches. This can be achieved by defining an appropriate method
``_cache_key``::
sage: hash(b)
Traceback (most recent call last):
...
TypeError: unhashable type: 'sage.rings.padics.padic_ZZ_pX_CR_element.pAdicZZpXCRElement'
sage: @cached_method
....: def f(x): return x == a
sage: f(b)
True
sage: f(c) # if b and c were hashable, this would return True
False
sage: b._cache_key()
(..., ((0, 1),), 0, 1)
sage: c._cache_key()
(..., ((0, 1), (1,)), 0, 20)
.. NOTE::
This attribute will only be accessed if the object itself
is not hashable.
An implementation must make sure that for elements ``a`` and ``b``,
if ``a != b``, then also ``a._cache_key() != b._cache_key()``.
In practice this means that the ``_cache_key`` should always include
the parent as its first argument::
sage: S.<a> = Qq(4)
sage: d = a.add_bigoh(1)
sage: b._cache_key() == d._cache_key() # this would be True if the parents were not included
False
"""
########################################################################
# Copyright (C) 2008 William Stein <wstein@gmail.com>
# Mike Hansen <mhansen@gmail.com>
# 2011 Simon King <simon.king@uni-jena.de>
# 2014 Julian Rueth <julian.rueth@fsfe.org>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# http://www.gnu.org/licenses/
########################################################################
from function_mangling import ArgumentFixer
import os
from os.path import relpath,normpath,commonprefix
from sage.misc.sageinspect import sage_getfile, sage_getsourcelines, sage_getargspec
import sage.misc.weak_dict
from sage.misc.weak_dict import WeakValueDictionary
from sage.misc.decorators import decorator_keywords
cdef frozenset special_method_names = frozenset(['__abs__', '__add__',
'__and__', '__call__', '__cmp__', '__coerce__', '__complex__', '__contains__', '__del__',
'__delattr__', '__delete__', '__delitem__', '__delslice__', '__dir__', '__div__',
'__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__get__', '__getattr__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__hex__',
'__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__',
'__index__', '__init__', '__instancecheck__', '__int__', '__invert__', '__ior__', '__ipow__',
'__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__',
'__length_hint__', '__long__', '__lshift__', '__lt__', '__missing__', '__mod__', '__mul__',
'__ne__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__',
'__radd__', '__rand__', '__rdiv__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__',
'__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__',
'__str__', '__sub__', '__subclasscheck__', '__truediv__', '__unicode__', '__xor__', 'next'])
def _cached_function_unpickle(module,name):
"""
Unpickling of cached functions.
NOTE:
Pickling and unpickling of cached functions is by importing
from the module in which the function is defined.
INPUT:
- ``module``: A string, describing the module to import the
function from.
- ``name``: A string, name of the to-be-imported cached function.
EXAMPLE::
sage: type(cunningham_prime_factors)
<type 'sage.misc.cachefunc.CachedFunction'>
sage: loads(dumps(cunningham_prime_factors)) is cunningham_prime_factors #indirect doctest
True
"""
return getattr(__import__(module, fromlist=['']),name)
def _cache_key(o):
r"""
Helper function to return a hashable key for ``o`` which can be used for
caching.
This function is intended for objects which are not hashable such as
`p`-adic numbers. The difference from calling an object's ``_cache_key``
attribute directly, is that it also works for tuples and unpacks them
recursively (if necessary, i.e., if they are not hashable).
EXAMPLES::
sage: from sage.misc.cachefunc import _cache_key
sage: K.<u> = Qq(9)
sage: a = K(1); a
1 + O(3^20)
sage: _cache_key(a)
(..., ((1,),), 0, 20)
This function works if ``o`` is a tuple. In this case it unpacks its
entries recursively::
sage: o = (1, 2, (3, a))
sage: _cache_key(o)
(1, 2, (3, (..., ((1,),), 0, 20)))
Note that tuples are only partially unpacked if some of its entries are
hashable::
sage: o = (1/2, a)
sage: _cache_key(o)
(1/2, (..., ((1,),), 0, 20))
"""
try:
hash(o)
return o
except TypeError:
if isinstance(o, sage.structure.sage_object.SageObject):
o = o._cache_key()
if isinstance(o,tuple):
return tuple(_cache_key(item) for item in o)
else:
return o
cdef class CachedFunction(object):
"""
Create a cached version of a function, which only recomputes
values it hasn't already computed. Synonyme: ``cached_function``
INPUT:
- ``f`` -- a function
- ``name`` -- (optional string) name that the cached version
of ``f`` should be provided with
- ``key`` -- (optional callable) takes the input and returns a
key for the cache, typically one would use this to normalize input
If ``f`` is a function, do either ``g = CachedFunction(f)``
or ``g = cached_function(f)`` to make a cached version of ``f``,
or put ``@cached_function`` right before the definition of ``f``
(i.e., use Python decorators)::
@cached_function
def f(...):
....
The inputs to the function must be hashable or they must define
:meth:`sage.structure.sage_object.SageObject._cache_key`.
EXAMPLES::
sage: @cached_function
....: def mul(x, y=2):
....: return x*y
sage: mul(3)
6
We demonstrate that the result is cached, and that, moreover,
the cache takes into account the various ways of providing
default arguments::
sage: mul(3) is mul(3,2)
True
sage: mul(3,y=2) is mul(3,2)
True
The user can clear the cache::
sage: a = mul(4)
sage: mul.clear_cache()
sage: a is mul(4)
False
It is also possible to explicitly override the cache with
a different value::
sage: mul.set_cache('foo',5)
sage: mul(5,2)
'foo'
The parameter ``key`` can be used to ignore parameters for
caching. In this example we ignore the parameter ``algorithm``::
sage: @cached_function(key=lambda x,y,algorithm: (x,y))
....: def mul(x, y, algorithm="default"):
....: return x*y
sage: mul(1,1,algorithm="default") is mul(1,1,algorithm="algorithm") is mul(1,1) is mul(1,1,'default')
True
"""
def __init__(self, f, classmethod=False, name=None, key=None):
"""
Create a cached version of a function, which only recomputes
values it hasn't already computed. A custom name can be
provided by an optional argument "name".
If ``f`` is a function, do either ``g = CachedFunction(f)``
to make a cached version of ``f``, or put ``@CachedFunction``
right before the definition of ``f`` (i.e., use Python decorators)::
@CachedFunction
def f(...):
....
The inputs to the function must be hashable or they must define
:meth:`sage.structure.sage_object.SageObject._cache_key`.
TESTS::
sage: g = CachedFunction(number_of_partitions)
sage: g.__name__
'number_of_partitions'
sage: 'partitions' in sage.misc.sageinspect.sage_getdoc(g)
True
sage: g(5)
7
sage: g.cache
{((5, 'default'), ()): 7}
sage: def f(t=1): print(t)
sage: h = CachedFunction(f)
sage: w = walltime()
sage: h(); h(1); h(t=1)
1
sage: walltime(w) < 2
True
"""
self.is_classmethod = classmethod
self._common_init(f, None, name=name, key=key)
self.cache = {}
def _common_init(self, f, argument_fixer, name=None, key=None):
"""
Perform initialization common to CachedFunction and CachedMethodCaller.
TESTS::
sage: @cached_function
....: def test_cache(x):
....: return -x
sage: test_cache.__name__ # indirect doctest
'test_cache'
"""
self.f = f
self.key = key
if name is not None:
self.__name__ = name
elif hasattr(f, "__name__"):
self.__name__ = f.__name__
else:
self.__name__ = f.__name__
try:
self.__module__ = f.__module__
except AttributeError:
self.__module__ = f.__objclass__.__module__
if argument_fixer is not None: # it is None unless the argument fixer
# was known previously. See #15038.
self._argument_fixer = argument_fixer
if self.key is None:
self._fix_to_pos = argument_fixer.fix_to_pos
else:
self._fix_to_pos = self._fix_to_pos_and_create_key
cdef argfix_init(self):
"""
Perform initialization common to CachedFunction and CachedMethodCaller.
TESTS::
sage: @cached_function
....: def test_cache(x):
....: return -x
sage: test_cache(1)
-1
sage: test_cache._fix_to_pos is not None # indirect doctest
True
"""
A = ArgumentFixer(self.f,classmethod=self.is_classmethod)
self._argument_fixer = A
if self.key:
self._fix_to_pos = self._fix_to_pos_and_create_key
else:
self._fix_to_pos = A.fix_to_pos
def _fix_to_pos_and_create_key(self, *args, **kwargs):
r"""
Normalize parameters to obtain a key for the cache.
For performance reasons, this method is only called if a ``create_key`` has been passed in
the constructor.
TESTS::
sage: @cached_function(key=lambda x,y,algorithm: (x,y))
....: def mul(x, y, algorithm="default"):
....: return x*y
sage: mul(2,3) # this initializes _argument_fixer
6
sage: mul._fix_to_pos_and_create_key(1,1,"default")
(1, 1)
"""
args, kwargs = self._argument_fixer.fix_to_pos(*args, **kwargs)
return self.key(*args, **dict(kwargs))
def __reduce__(self):
"""
Pickling of cached functions.
TEST::
sage: type(cunningham_prime_factors)
<type 'sage.misc.cachefunc.CachedFunction'>
sage: loads(dumps(cunningham_prime_factors)) is cunningham_prime_factors #indirect doctest
True
"""
return _cached_function_unpickle, (self.__module__, self.__name__)
#########
## Introspection
##
## We provide some methods explicitly, and
## forward other questions to the cached function.
def _sage_doc_(self):
"""
Provide documentation for the cached function.
A cached function shall inherit the documentation
from the function that is wrapped, not from the
documentation of the wrapper.
TEST::
sage: P.<x,y> = QQ[]
sage: I = P*[x,y]
sage: from sage.misc.sageinspect import sage_getdoc
sage: print sage_getdoc(I.groebner_basis) # indirect doctest
Return the reduced Groebner basis of this ideal.
...
ALGORITHM: Uses Singular, Magma (if available), Macaulay2 (if
available), or a toy implementation.
Test that :trac:`15184` is fixed::
sage: from sage.misc.sageinspect import sage_getfile
sage: type(I.groebner_basis)
<type 'sage.misc.cachefunc.CachedMethodCaller'>
sage: os.path.exists(sage_getfile(I.groebner_basis))
True
"""
from sage.misc.sageinspect import _extract_embedded_position
f = self.f
doc = f.__doc__ or ''
if _extract_embedded_position(doc.splitlines()[0]) is None:
try:
sourcelines = sage_getsourcelines(f)
from sage.env import SAGE_SRC, SAGE_LIB
filename = sage_getfile(f)
#it would be nice if we could be sure that SAGE_SRC and
#SAGE_LIB were already normalized (e.g. not end in a slash)
S=normpath(SAGE_SRC)
L=normpath(SAGE_LIB)
if commonprefix([filename,S]) == S:
filename = relpath(filename,S)
elif commonprefix([filename,L]) == L:
filename = relpath(filename,L)
#this is a rather expensive way of getting the line number, because
#retrieving the source requires reading the source file and in many
#cases this is not required (in cython it's embedded in the docstring,
#on code objects you'll find it in co_filename and co_firstlineno)
#however, this hasn't been factored out yet in sageinspect
#and the logic in sage_getsourcelines is rather intricate.
file_info = "File: {} (starting at line {})".format(filename,sourcelines[1])+os.linesep
doc = file_info+doc
except IOError:
pass
return doc
def _sage_src_(self):
"""
Returns the source code for the wrapped function.
TESTS::
sage: from sage.misc.sageinspect import sage_getsource
sage: g = CachedFunction(number_of_partitions)
sage: 'bober' in sage_getsource(g) # indirect doctest
True
"""
from sage.misc.sageinspect import sage_getsource
return sage_getsource(self.f)
def _sage_src_lines_(self):
r"""
Returns the list of source lines and the first line number
of the wrapped function.
TEST::
sage: P.<x,y> = QQ[]
sage: I = P*[x,y]
sage: from sage.misc.sageinspect import sage_getsourcelines
sage: l = " elif algorithm == 'macaulay2:gb':\n"
sage: l in sage_getsourcelines(I.groebner_basis)[0] # indirect doctest
True
"""
from sage.misc.sageinspect import sage_getsourcelines
return sage_getsourcelines(self.f)
def _sage_argspec_(self):
"""
Return the argspec of the wrapped function or method.
This was implemented in trac ticket #11115.
EXAMPLE::
sage: P.<x,y> = QQ[]
sage: I = P*[x,y]
sage: from sage.misc.sageinspect import sage_getargspec
sage: sage_getargspec(I.groebner_basis) # indirect doctest
ArgSpec(args=['self', 'algorithm', 'deg_bound', 'mult_bound', 'prot'],
varargs='args', keywords='kwds', defaults=('', None, None,
False))
"""
return sage_getargspec(self.f)
def __call__(self, *args, **kwds):
"""
Return value from cache or call the wrapped function,
caching the output.
TESTS::
sage: g = CachedFunction(number_of_partitions)
sage: a = g(5)
sage: g.get_cache()
{((5, 'default'), ()): 7}
sage: a = g(10^5) # indirect doctest
sage: a == number_of_partitions(10^5)
True
sage: a is g(10^5)
True
sage: a is number_of_partitions(10^5)
True
Check that :trac:`16316` has been fixed, i.e., caching works for
immutable unhashable objects which define
:meth:`sage.structure.sage_object.SageObject._cache_key`::
sage: @cached_function
....: def f(x): return x+x
sage: K.<u> = Qq(4)
sage: x = K(1,1); x
1 + O(2)
sage: y = K(1,2); y
1 + O(2^2)
sage: x == y
True
sage: f(x) is f(x)
True
sage: f(y) is not f(x)
True
"""
# We shortcut a common case of no arguments
if args or kwds:
if self._argument_fixer is None:
self.argfix_init()
k = self._fix_to_pos(*args, **kwds)
else:
if self._default_key is not None:
k = self._default_key
else:
if self._argument_fixer is None:
self.argfix_init()
k = self._default_key = self._fix_to_pos()
try:
try:
return (<dict>self.cache)[k]
except TypeError: # k is not hashable
k = (_cache_key,_cache_key(k))
return (<dict>self.cache)[k]
except KeyError:
w = self.f(*args, **kwds)
self.cache[k] = w
return w
cpdef get_cache(self):
"""
Returns the cache dictionary.
EXAMPLES::
sage: g = CachedFunction(number_of_partitions)
sage: a = g(5)
sage: g.get_cache()
{((5, 'default'), ()): 7}
"""
return self.cache
def is_in_cache(self, *args, **kwds):
"""
Checks if the argument list is in the cache.
EXAMPLES::
sage: class Foo:
....: def __init__(self, x):
....: self._x = x
....: @cached_method
....: def f(self, z, y=0):
....: return self._x*z+y
sage: a = Foo(2)
sage: a.f.is_in_cache(3)
False
sage: a.f(3)
6
sage: a.f.is_in_cache(3,y=0)
True
TESTS:
Check that :trac:`16316` has been fixed, i.e., caching works for
immutable unhashable objects which define
:meth:`sage.structure.sage_object.SageObject._cache_key`::
sage: @cached_function
....: def f(x): return x
sage: K.<u> = Qq(4)
sage: x = K(1,1); x
1 + O(2)
sage: f.is_in_cache(x)
False
sage: f(x)
1 + O(2)
sage: f.is_in_cache(x)
True
"""
if self._argument_fixer is None:
self.argfix_init()
k = self._fix_to_pos(*args, **kwds)
try:
return k in (<dict>self.cache)
except TypeError: # k is not hashable
k = (_cache_key,_cache_key(k))
return k in <dict>self.cache