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
/
morphism.py
3146 lines (2457 loc) · 103 KB
/
morphism.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
# coding=utf-8
r"""
Word morphisms/substitutions
This modules implements morphisms over finite and infinite words.
AUTHORS:
- Sebastien Labbe (2007-06-01): initial version
- Sebastien Labbe (2008-07-01): merged into sage-words
- Sebastien Labbe (2008-12-17): merged into sage
- Sebastien Labbe (2009-02-03): words next generation
- Sebastien Labbe (2009-11-20): allowing the choice of the
datatype of the image. Doc improvements.
- Stepan Starosta (2012-11-09): growing letters
EXAMPLES:
Creation of a morphism from a dictionary or a string::
sage: n = WordMorphism({0:[0,2,2,1],1:[0,2],2:[2,2,1]})
::
sage: m = WordMorphism('x->xyxsxss,s->xyss,y->ys')
::
sage: n
WordMorphism: 0->0221, 1->02, 2->221
sage: m
WordMorphism: s->xyss, x->xyxsxss, y->ys
The codomain may be specified::
sage: WordMorphism({0:[0,2,2,1],1:[0,2],2:[2,2,1]}, codomain=Words([0,1,2,3,4]))
WordMorphism: 0->0221, 1->02, 2->221
Power of a morphism::
sage: n^2
WordMorphism: 0->022122122102, 1->0221221, 2->22122102
Image under a morphism::
sage: m('y')
word: ys
sage: m('xxxsy')
word: xyxsxssxyxsxssxyxsxssxyssys
Iterated image under a morphism::
sage: m('y', 3)
word: ysxyssxyxsxssysxyssxyss
Infinite fixed point of morphism::
sage: fix = m.fixed_point('x')
sage: fix
word: xyxsxssysxyxsxssxyssxyxsxssxyssxyssysxys...
sage: fix.length()
+Infinity
Incidence matrix::
sage: matrix(m)
[2 3 1]
[1 3 0]
[1 1 1]
Many other functionalities...::
sage: m.is_identity()
False
sage: m.is_endomorphism()
True
"""
#*****************************************************************************
# Copyright (C) 2008 Sebastien Labbe <slabqc@gmail.com>
#
# This program 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.
# http://www.gnu.org/licenses/
#*****************************************************************************
import itertools
from sage.misc.superseded import deprecated_function_alias
from sage.structure.sage_object import SageObject
from sage.misc.cachefunc import cached_method
from sage.sets.set import Set
from sage.rings.all import QQ
from sage.rings.infinity import Infinity
from sage.rings.integer_ring import IntegerRing
from sage.rings.integer import Integer
from sage.modules.free_module_element import vector
from sage.matrix.constructor import Matrix
from sage.combinat.words.word import FiniteWord_class
from sage.combinat.words.words import Words_all, Words
class CallableDict(dict):
r"""
Wrapper of dictionary that makes it callable.
EXAMPLES::
sage: from sage.combinat.words.morphism import CallableDict
sage: d = CallableDict({1:'one', 2:'zwei', 3:'trois'})
sage: d(1), d(2), d(3)
('one', 'zwei', 'trois')
"""
def __call__(self, key):
r"""
Returns the value with key ``key``.
EXAMPLES::
sage: from sage.combinat.words.morphism import CallableDict
sage: d = CallableDict({'one': 1, 'zwei': 2, 'trois': 3})
sage: d('one'), d('zwei'), d('trois')
(1, 2, 3)
"""
return self[key]
def get_cycles(f, domain=None):
r"""
Return the cycle of the function ``f`` on the finite set domain. It is
assumed that f is an endomorphism.
INPUT:
- ``f`` - function.
- ``domain`` - set (default: None) - the domain of ``f``. If none, then
tries to use ``f.domain()``.
EXAMPLES::
sage: from sage.combinat.words.morphism import get_cycles
sage: get_cycles(lambda i: (i+1)%3, domain=[0,1,2])
[(0, 1, 2)]
sage: get_cycles(lambda i: [0,0,0][i], domain=[0,1,2])
[(0,)]
sage: get_cycles(lambda i: [1,1,1][i], domain=[0,1,2])
[(1,)]
"""
if domain is None:
try:
domain = f.domain()
except AttributeError:
raise ValueError("you should specify the domain of the function f")
cycles = []
not_seen = dict((letter,True) for letter in domain)
for a in not_seen:
if not_seen[a]:
not_seen[a] = False
cycle = [a]
b = f(a)
while not_seen[b]:
not_seen[b] = False
cycle.append(b)
b = f(b)
if b in cycle:
cycles.append(tuple(cycle[cycle.index(b):]))
return cycles
class WordMorphism(SageObject):
r"""
WordMorphism class
EXAMPLES::
sage: n = WordMorphism({0:[0,2,2,1],1:[0,2],2:[2,2,1]})
sage: m = WordMorphism('x->xyxsxss,s->xyss,y->ys')
Power of a morphism::
sage: n^2
WordMorphism: 0->022122122102, 1->0221221, 2->22122102
Image under a morphism::
sage: m('y')
word: ys
sage: m('xxxsy')
word: xyxsxssxyxsxssxyxsxssxyssys
Iterated image under a morphism::
sage: m('y', 3)
word: ysxyssxyxsxssysxyssxyss
See more examples in the documentation of the call method
(``m.__call__?``).
Infinite fixed point of morphism::
sage: fix = m.fixed_point('x')
sage: fix
word: xyxsxssysxyxsxssxyssxyxsxssxyssxyssysxys...
sage: fix.length()
+Infinity
Incidence matrix::
sage: matrix(m)
[2 3 1]
[1 3 0]
[1 1 1]
Many other functionalities...::
sage: m.is_identity()
False
sage: m.is_endomorphism()
True
TESTS::
sage: wm = WordMorphism('a->ab,b->ba')
sage: wm == loads(dumps(wm))
True
"""
def __init__(self, data, codomain=None):
r"""
Construction of the morphism.
EXAMPLES:
1. If data is a str::
sage: WordMorphism('a->ab,b->ba')
WordMorphism: a->ab, b->ba
sage: WordMorphism('a->ab,b->ba')
WordMorphism: a->ab, b->ba
sage: WordMorphism('a->abc,b->bca,c->cab')
WordMorphism: a->abc, b->bca, c->cab
sage: WordMorphism('a->abdsf,b->hahdad,c->asdhasd')
WordMorphism: a->abdsf, b->hahdad, c->asdhasd
sage: WordMorphism('(->(),)->)(')
WordMorphism: (->(), )->)(
sage: WordMorphism('a->53k,b->y5?,$->49i')
WordMorphism: $->49i, a->53k, b->y5?
An erasing morphism::
sage: WordMorphism('a->ab,b->')
WordMorphism: a->ab, b->
Use the arrows ('->') correctly::
sage: WordMorphism('a->ab,b-')
Traceback (most recent call last):
...
ValueError: The second and third characters must be '->' (not '-')
sage: WordMorphism('a->ab,b')
Traceback (most recent call last):
...
ValueError: The second and third characters must be '->' (not '')
sage: WordMorphism('a->ab,a-]asdfa')
Traceback (most recent call last):
...
ValueError: The second and third characters must be '->' (not '-]')
Each letter must be defined only once::
sage: WordMorphism('a->ab,a->ba')
Traceback (most recent call last):
...
ValueError: The image of 'a' is defined twice.
2. From a dictionary::
sage: WordMorphism({"a":"ab","b":"ba"})
WordMorphism: a->ab, b->ba
sage: WordMorphism({2:[4,5,6],3:[1,2,3]})
WordMorphism: 2->456, 3->123
sage: WordMorphism({'a':['a',6,'a'],6:[6,6,6,'a']})
WordMorphism: 6->666a, a->a6a
The image of a letter can be a set, but the order is not
preserved::
sage: WordMorphism({2:[4,5,6],3:set([4,1,8])}) #random results
WordMorphism: 2->456, 3->814
If the image of a letter is not iterable, it is considered as a
letter::
sage: WordMorphism({0:1, 1:0})
WordMorphism: 0->1, 1->0
sage: WordMorphism({0:123, 1:789})
WordMorphism: 0->123, 1->789
sage: WordMorphism({2:[4,5,6], 3:123})
WordMorphism: 2->456, 3->123
3. From a WordMorphism::
sage: WordMorphism(WordMorphism('a->ab,b->ba'))
WordMorphism: a->ab, b->ba
TESTS::
sage: WordMorphism(',,,a->ab,,,b->ba,,')
WordMorphism: a->ab, b->ba
"""
if isinstance(data, WordMorphism):
self._domain = data._domain
self._codomain = data._codomain
self._morph = data._morph
else:
if isinstance(data, str):
data = self._build_dict(data)
elif not isinstance(data, dict):
raise NotImplementedError
if codomain is None:
codomain = self._build_codomain(data)
if not isinstance(codomain,Words_all):
raise TypeError("the codomain must be a Words domain")
self._codomain = codomain
self._morph = {}
dom_alph = list()
for (key,val) in data.iteritems():
dom_alph.append(key)
if val in codomain.alphabet():
self._morph[key] = codomain([val])
else:
self._morph[key] = codomain(val)
dom_alph.sort()
self._domain = Words(dom_alph)
def _build_dict(self, s):
r"""
Parse the string input to WordMorphism and build the dictionary
it represents.
TESTS::
sage: wm = WordMorphism('a->ab,b->ba')
sage: wm._build_dict('a->ab,b->ba') == {'a': 'ab', 'b': 'ba'}
True
sage: wm._build_dict('a->ab,a->ba')
Traceback (most recent call last):
...
ValueError: The image of 'a' is defined twice.
sage: wm._build_dict('a->ab,b>ba')
Traceback (most recent call last):
...
ValueError: The second and third characters must be '->' (not '>b')
"""
tmp_dict = {}
for fleche in s.split(','):
if len(fleche) == 0:
continue
if len(fleche) < 3 or fleche[1:3] != '->':
raise ValueError("The second and third characters must be '->' (not '%s')"%fleche[1:3])
lettre = fleche[0]
image = fleche[3:]
if lettre in tmp_dict:
raise ValueError("The image of %r is defined twice." %lettre)
tmp_dict[lettre] = image
return tmp_dict
def _build_codomain(self, data):
r"""
Returns a Words domain containing all the letter in the keys of
data (which must be a dictionary).
TESTS:
If the image of all the letters are iterable::
sage: wm = WordMorphism('a->ab,b->ba')
sage: wm._build_codomain({'a': 'ab', 'b': 'ba'})
Words over {'a', 'b'}
sage: wm._build_codomain({'a': 'dcb', 'b': 'a'})
Words over {'a', 'b', 'c', 'd'}
sage: wm._build_codomain({2:[4,5,6],3:[1,2,3]})
Words over {1, 2, 3, 4, 5, 6}
sage: wm._build_codomain({2:[4,5,6],3:set([4,1,8])})
Words over {1, 4, 5, 6, 8}
If the image of a letter is not iterable, it is considered as
a letter::
sage: wm._build_codomain({2:[4,5,6],3:123})
Words over {4, 5, 6, 123}
sage: wm._build_codomain({0:1, 1:0, 2:2})
Words over {0, 1, 2}
"""
codom_alphabet = set()
for key,val in data.iteritems():
try:
it = iter(val)
except Exception:
it = [val]
codom_alphabet.update(it)
return Words(sorted(codom_alphabet))
def __eq__(self, other):
r"""
Returns ``True`` if ``self`` is equal to ``other``.
EXAMPLES::
sage: n = WordMorphism('a->a,b->aa,c->aaa')
sage: n**3 == n**1
True
sage: WordMorphism('b->ba,a->ab') == WordMorphism('a->ab,b->ba')
True
sage: WordMorphism('b->ba,a->ab') == WordMorphism({"a":"ab","b":"ba"})
True
sage: m = WordMorphism({0:[1,2,3],1:[4,5,6]}); m
WordMorphism: 0->123, 1->456
sage: o = WordMorphism('0->123,1->456'); o
WordMorphism: 0->123, 1->456
sage: m == o
False
TESTS:
Check that equality depends on the codomain::
sage: m = WordMorphism('a->a,b->aa,c->aaa')
sage: n = WordMorphism('a->a,b->aa,c->aaa', codomain=Words('abc'))
sage: m == n
False
"""
if not isinstance(other, WordMorphism):
return False
return self._morph == other._morph and self._codomain == other._codomain
def __ne__(self, other):
r"""
Returns whether ``self`` is not equal to ``other``.
EXAMPLES::
sage: m = WordMorphism('a->ab,b->baba')
sage: n = WordMorphism('a->ab,b->baba')
sage: o = WordMorphism('a->ab,b->bab')
sage: m != n
False
sage: n != o
True
This solves :trac:`12475`::
sage: s = WordMorphism('1->121,2->131,3->4,4->1')
sage: s == s.reversal()
True
sage: s != s.reversal()
False
"""
return not self.__eq__(other)
def __repr__(self):
r"""
Returns the string representation of the morphism.
EXAMPLES::
sage: WordMorphism('a->ab,b->ba')
WordMorphism: a->ab, b->ba
sage: WordMorphism({0:[0,1],1:[1,0]})
WordMorphism: 0->01, 1->10
TESTS::
sage: s = WordMorphism('a->ab,b->ba')
sage: repr(s)
'WordMorphism: a->ab, b->ba'
"""
return "WordMorphism: %s" % str(self)
def __str__(self):
r"""
Returns the morphism in str.
EXAMPLES::
sage: print WordMorphism('a->ab,b->ba')
a->ab, b->ba
sage: print WordMorphism({0:[0,1],1:[1,0]})
0->01, 1->10
The output is sorted to make it unique::
sage: print WordMorphism('b->ba,a->ab')
a->ab, b->ba
The str method is used for string formatting::
sage: s = WordMorphism('a->ab,b->ba')
sage: "Here is a map : %s" % s
'Here is a map : a->ab, b->ba'
::
sage: s = WordMorphism({1:[1,2],2:[1]})
sage: s.dual_map()
E_1^*(1->12, 2->1)
TESTS::
sage: s = WordMorphism('a->ab,b->ba')
sage: str(s)
'a->ab, b->ba'
"""
L = [str(lettre) + '->' + image.string_rep() for lettre,image in self._morph.iteritems()]
return ', '.join(sorted(L))
def __call__(self, w, order=1, datatype='iter'):
r"""
Returns the image of ``w`` under self to the given order.
INPUT:
- ``w`` - word or sequence in the domain of self
- ``order`` - integer or plus ``Infinity`` (default: 1)
- ``datatype`` - (default: ``'iter'``) ``'list'``, ``'str'``,
``'tuple'``, ``'iter'``. The datatype of the output
(note that only list, str and tuple allows the word to be
pickled and saved).
OUTPUT:
- ``word`` - order-th iterated image under self of ``w``
EXAMPLES:
The image of a word under a morphism:
1. The image of a finite word under a morphism::
sage: tm = WordMorphism ('a->ab,b->ba')
sage: tm('a')
word: ab
sage: tm('aabababb')
word: ababbaabbaabbaba
2. The iterated image of a word::
sage: tm('a', 2)
word: abba
sage: tm('aba', 3)
word: abbabaabbaababbaabbabaab
3. The infinitely iterated image of a letter::
sage: tm('a', oo)
word: abbabaabbaababbabaababbaabbabaabbaababba...
4. The image of an infinite word::
sage: t = words.ThueMorseWord()
sage: n = WordMorphism({0:[0, 1], 1:[1, 0]})
sage: n(t)
word: 0110100110010110100101100110100110010110...
sage: n(t, 3)
word: 0110100110010110100101100110100110010110...
sage: n(t)[:1000] == t[:1000]
True
The Fibonacci word::
sage: w = words.FibonacciWord()
sage: m = WordMorphism({0:'a', 1:'b'})
sage: m(w)
word: abaababaabaababaababaabaababaabaababaaba...
sage: f = words.FibonacciWord('ab')
sage: f[:1000] == m(w)[:1000]
True
::
sage: w = words.FibonacciWord("ab")
sage: m = WordMorphism('a->01,b->101')
sage: m(w)
word: 0110101011010110101011010101101011010101...
The default datatype of the output is an iterable which
can be saved (for finite word only)::
sage: m = WordMorphism('a->ab,b->ba')
sage: w = m('aabb')
sage: type(w)
<class 'sage.combinat.words.word.FiniteWord_iter_with_caching'>
sage: w == loads(dumps(w))
True
sage: save(w, filename=os.path.join(SAGE_TMP, 'test.sobj'))
One may impose the datatype of the resulting word::
sage: w = m('aaab',datatype='list')
sage: type(w)
<class 'sage.combinat.words.word.FiniteWord_list'>
sage: w = m('aaab',datatype='str')
sage: type(w)
<class 'sage.combinat.words.word.FiniteWord_str'>
sage: w = m('aaab',datatype='tuple')
sage: type(w)
<class 'sage.combinat.words.word.FiniteWord_tuple'>
To use str datatype for the output word, the domain and codomain
alphabet must consist of str objects::
sage: m = WordMorphism({0:[0,1],1:[1,0]})
sage: w = m([0],4); type(w)
<class 'sage.combinat.words.word.FiniteWord_iter_with_caching'>
sage: w = m([0],4,datatype='list'); type(w)
<class 'sage.combinat.words.word.FiniteWord_list'>
sage: w = m([0],4,datatype='str')
Traceback (most recent call last):
...
ValueError: 0 not in alphabet!
sage: w = m([0],4,datatype='tuple'); type(w)
<class 'sage.combinat.words.word.FiniteWord_tuple'>
The word must be in the domain of self::
sage: tm('0021')
Traceback (most recent call last):
...
KeyError: '0'
The order must be a positive integer or plus Infinity::
sage: tm('a', -1)
Traceback (most recent call last):
...
TypeError: order (-1) must be a positive integer or plus Infinity
sage: tm('a', 6.7)
Traceback (most recent call last):
...
TypeError: order (6.70000000000000) must be a positive integer or plus Infinity
Only the first letter is considered for infinitely iterated image of
a word under a morphism::
sage: tm('aba',oo)
word: abbabaabbaababbabaababbaabbabaabbaababba...
The morphism self must be prolongable on the given letter for infinitely
iterated image::
sage: m = WordMorphism('a->ba,b->ab')
sage: m('a', oo)
Traceback (most recent call last):
...
TypeError: self must be prolongable on a
The empty word is fixed by any morphism for all natural
powers::
sage: phi = WordMorphism('a->ab,b->a')
sage: phi(Word())
word:
sage: phi(Word(), oo)
word:
sage: it = iter([])
sage: phi(it, oo)
word:
TESTS::
sage: for i in range(6):
... tm('a', i)
...
word: a
word: ab
word: abba
word: abbabaab
word: abbabaabbaababba
word: abbabaabbaababbabaababbaabbabaab
sage: m = WordMorphism('a->,b->')
sage: m('')
word:
"""
if order == 1:
if isinstance(w, (tuple,str,list)):
length = 'finite'
elif isinstance(w, FiniteWord_class):
#Is it really a good thing to precompute the length?
length = sum(self._morph[a].length() * b for (a,b) in w.evaluation_dict().iteritems())
elif hasattr(w, '__iter__'):
length = Infinity
datatype = 'iter'
elif w in self._domain.alphabet():
return self._morph[w]
else:
raise TypeError("Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w)
return self.codomain()((x for y in w for x in self._morph[y]), length=length, datatype=datatype)
elif order is Infinity:
if isinstance(w, (tuple,str,list,FiniteWord_class)):
if len(w) == 0:
return self.codomain()()
else:
letter = w[0]
elif hasattr(w, '__iter__'):
try:
letter = w.next()
except StopIteration:
return self.codomain()()
elif w in self._domain.alphabet():
letter = w
else:
raise TypeError("Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w)
return self.fixed_point(letter=letter)
elif isinstance(order, (int,Integer)) and order > 1:
return self(self(w, order-1),datatype=datatype)
elif order == 0:
return self._domain(w)
else:
raise TypeError("order (%s) must be a positive integer or plus Infinity" % order)
def latex_layout(self, layout=None):
r"""
Get or set the actual latex layout (oneliner vs array).
INPUT:
- ``layout`` - string (default: ``None``), can take one of the
following values:
- ``None`` - Returns the actual latex layout. By default, the
layout is ``'array'``
- ``'oneliner'`` - Set the layout to ``'oneliner'``
- ``'array'`` - Set the layout to ``'array'``
EXAMPLES::
sage: s = WordMorphism('a->ab,b->ba')
sage: s.latex_layout()
'array'
sage: s.latex_layout('oneliner')
sage: s.latex_layout()
'oneliner'
"""
if layout is None:
# return the layout
if not hasattr(self, '_latex_layout'):
self._latex_layout = 'array'
return self._latex_layout
else:
# change the layout
self._latex_layout = layout
def _latex_(self):
r"""
Returns the latex representation of the morphism.
Use :method:`latex_layout` to change latex layout (oneliner vs
array). The default is an latex array.
EXAMPLES::
sage: s = WordMorphism('a->ab,b->ba')
sage: s._latex_()
\begin{array}{l}
a \mapsto ab\\
b \mapsto ba
\end{array}
Change the latex layout to a one liner::
sage: s.latex_layout('oneliner')
sage: s._latex_()
a \mapsto ab,b \mapsto ba
TESTS:
Unknown latex style::
sage: s.latex_layout('tabular')
sage: s._latex_()
Traceback (most recent call last):
...
ValueError: unknown latex_layout(=tabular)
"""
from sage.misc.latex import LatexExpr
A = self.domain().alphabet()
latex_layout = self.latex_layout()
if latex_layout == 'oneliner':
L = [r"%s \mapsto %s" % (a, self.image(a)) for a in A]
return LatexExpr(r','.join(L))
elif latex_layout == 'array':
s = r""
s += r"\begin{array}{l}" + '\n'
lines = []
for a in A:
lines.append(r"%s \mapsto %s"% (a, self.image(a)))
s += '\\\\\n'.join(lines)
s += '\n' + "\end{array}"
return LatexExpr(s)
else:
raise ValueError('unknown latex_layout(=%s)' % latex_layout)
def __mul__(self, other):
r"""
Returns the morphism ``self``\*``other``.
EXAMPLES::
sage: m = WordMorphism('a->ab,b->ba')
sage: fibo = WordMorphism('a->ab,b->a')
sage: fibo*m
WordMorphism: a->aba, b->aab
sage: fibo*fibo
WordMorphism: a->aba, b->ab
sage: m*fibo
WordMorphism: a->abba, b->ab
::
sage: n = WordMorphism('a->a,b->aa,c->aaa')
sage: p1 = n*m
sage: p1
WordMorphism: a->aaa, b->aaa
sage: p1.domain()
Words over {'a', 'b'}
sage: p1.codomain()
Words over {'a'}
::
sage: p2 = m*n
sage: p2
WordMorphism: a->ab, b->abab, c->ababab
sage: p2.domain()
Words over {'a', 'b', 'c'}
sage: p2.codomain()
Words over {'a', 'b'}
::
sage: m = WordMorphism('0->a,1->b')
sage: n = WordMorphism('a->c,b->e',codomain=Words('abcde'))
sage: p = n * m
sage: p.codomain()
Words over {'a', 'b', 'c', 'd', 'e'}
TESTS::
sage: m = WordMorphism('a->b,b->c,c->a')
sage: WordMorphism('')*m
Traceback (most recent call last):
...
KeyError: 'b'
sage: m * WordMorphism('')
WordMorphism:
"""
return WordMorphism(dict((key, self(w)) for (key, w) in other._morph.iteritems()), codomain=self.codomain())
def __pow__(self, exp):
r"""
Returns the power of ``self`` with exponent = ``exp``.
INPUT:
- ``exp`` - a positive integer
EXAMPLES::
sage: m = WordMorphism('a->ab,b->ba')
sage: m^1
WordMorphism: a->ab, b->ba
sage: m^2
WordMorphism: a->abba, b->baab
sage: m^3
WordMorphism: a->abbabaab, b->baababba
The exponent must be a positive integer::
sage: m^1.5
Traceback (most recent call last):
...
ValueError: exponent (1.50000000000000) must be an integer
sage: m^-2
Traceback (most recent call last):
...
ValueError: exponent (-2) must be strictly positive
When ``self`` is not an endomorphism::
sage: n = WordMorphism('a->ba,b->abc')
sage: n^2
Traceback (most recent call last):
...
KeyError: 'c'
"""
#If exp is not an integer
if not isinstance(exp, (int,Integer)):
raise ValueError("exponent (%s) must be an integer" %exp)
#If exp is negative
elif exp <= 0:
raise ValueError("exponent (%s) must be strictly positive" %exp)
#Base of induction
elif exp == 1:
return self
else:
nexp = int(exp / 2)
over = exp % 2
res = (self * self) ** nexp
if over == 1:
res *= self
return res
def extend_by(self, other):
r"""
Returns ``self`` extended by ``other``.
Let `\varphi_1:A^*\rightarrow B^*` and `\varphi_2:C^*\rightarrow D^*`
be two morphisms. A morphism `\mu:(A\cup C)^*\rightarrow (B\cup D)^*`
corresponds to `\varphi_1` *extended by* `\varphi_2` if
`\mu(a)=\varphi_1(a)` if `a\in A` and `\mu(a)=\varphi_2(a)` otherwise.
INPUT:
- ``other`` - a WordMorphism.
OUTPUT:
WordMorphism
EXAMPLES::
sage: m = WordMorphism('a->ab,b->ba')
sage: n = WordMorphism({0:1,1:0,'a':5})
sage: m.extend_by(n)
WordMorphism: 0->1, 1->0, a->ab, b->ba
sage: n.extend_by(m)
WordMorphism: 0->1, 1->0, a->5, b->ba
sage: m.extend_by(m)
WordMorphism: a->ab, b->ba
TESTS::
sage: m.extend_by(WordMorphism({})) == m
True
sage: m.extend_by(WordMorphism('')) == m
True
::
sage: m.extend_by(4)
Traceback (most recent call last):
...
TypeError: other (=4) is not a WordMorphism
"""
if not isinstance(other, WordMorphism):
raise TypeError("other (=%s) is not a WordMorphism"%other)
nv = dict(other._morph)
for k,v in self._morph.iteritems():
nv[k] = v
return WordMorphism(nv)
def restrict_domain(self, alphabet):
r"""
Returns a restriction of ``self`` to the given alphabet.
INPUT:
- ``alphabet`` - an iterable
OUTPUT:
WordMorphism
EXAMPLES::
sage: m = WordMorphism('a->b,b->a')
sage: m.restrict_domain('a')
WordMorphism: a->b
sage: m.restrict_domain('')
WordMorphism:
sage: m.restrict_domain('A')
WordMorphism:
sage: m.restrict_domain('Aa')
WordMorphism: a->b
The input alphabet must be iterable::
sage: m.restrict_domain(66)