File size: 105,840 Bytes
92416a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
import Mathlib

namespace OAI

namespace Rokhlin

open MeasureTheory Filter
open scoped BigOperators ComplexConjugate

section

structure ProjectiveCharacters {Y L : Type*} [MeasurableSpace Y] [AddCommGroup L]
    (η : Measure Y) (χ : L → Y → ℂ) : Prop where
  measurable : ∀ l, AEStronglyMeasurable (χ l) η
  modulus : ∀ l, ∀ᵐ y ∂η, ‖χ l y‖ = 1
  zero : χ 0 =ᵐ[η] fun _ => 1
  mul : ∀ l l', ∃ c : ℂ, ‖c‖ = 1 ∧
    (fun y => χ l y * χ l' y) =ᵐ[η] (fun y => c * χ (l + l') y)
  mean : ∀ l, l ≠ 0 → ∫ y, χ l y ∂η = 0

namespace ProjectiveCharacters
variable {Y L : Type*} [MeasurableSpace Y] [AddCommGroup L]
  {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
  (hχ : ProjectiveCharacters η χ)
include hχ

theorem integrable (l : L) : Integrable (χ l) η :=
  (integrable_const (1 : ℝ)).mono' (hχ.measurable l) ((hχ.modulus l).mono (fun _ h => h.le))

omit [IsProbabilityMeasure η] in

theorem conjugate (l : L) : ∃ c : ℂ, ‖c‖ = 1 ∧
    (fun y => conj (χ l y)) =ᵐ[η] (fun y => c * χ (-l) y) := by
  obtain ⟨c, hc, hm⟩ := hχ.mul (-l) l
  refine ⟨c⁻¹, by simp [hc], ?_⟩
  filter_upwards [hm, hχ.zero, hχ.modulus l] with y hy h0 hn
  simp only [neg_add_cancel, h0, mul_one] at hy
  have hcn : c ≠ 0 := by intro hz; simp [hz] at hc
  have hln : χ l y ≠ 0 := by intro hz; simp [hz] at hn
  rw [← Complex.inv_eq_conj hn]
  apply (mul_right_cancel₀ hln)
  rw [inv_mul_cancel₀ hln, mul_assoc, hy, inv_mul_cancel₀ hcn]

omit [IsProbabilityMeasure η] in

theorem finset_prod {ι : Type*} (s : Finset ι) (l : ι → L) :
    ∃ c : ℂ, ‖c‖ = 1 ∧
      (fun y => ∏ i ∈ s, χ (l i) y) =ᵐ[η] (fun y => c * χ (∑ i ∈ s, l i) y) := by
  classical
  induction s using Finset.induction_on with
  | empty =>
    refine ⟨1, norm_one, ?_⟩
    filter_upwards [hχ.zero] with y hy
    simp [hy]
  | @insert i s hi ih =>
    obtain ⟨c, hc, hsp⟩ := ih
    obtain ⟨d, hd, hmul⟩ := hχ.mul (l i) (∑ j ∈ s, l j)
    refine ⟨c * d, by simp [hc, hd], ?_⟩
    filter_upwards [hsp, hmul] with y hy hm
    simp only [Finset.prod_insert hi, Finset.sum_insert hi, hy]
    calc
      χ (l i) y * (c * χ (∑ j ∈ s, l j) y) =
        c * (χ (l i) y * χ (∑ j ∈ s, l j) y) := by ring
      _ = c * (d * χ (l i + ∑ j ∈ s, l j) y) := by rw [hm]
      _ = c * d * χ (l i + ∑ j ∈ s, l j) y := by ring

omit [IsProbabilityMeasure η] in
omit [IsProbabilityMeasure η] in

theorem integral_finset_prod_eq_zero {ι : Type*} (s : Finset ι) (l : ι → L)
    (hl : ∑ i ∈ s, l i ≠ 0) :
    ∫ y, ∏ i ∈ s, χ (l i) y ∂η = 0 := by
  obtain ⟨c, _, hp⟩ := hχ.finset_prod s l
  rw [integral_congr_ae hp, integral_const_mul, hχ.mean _ hl, mul_zero]

omit [IsProbabilityMeasure η] in
omit [IsProbabilityMeasure η] in

theorem orthogonal (l m : L) (hlm : l ≠ m) :
    ∫ y, χ l y * conj (χ m y) ∂η = 0 := by
  obtain ⟨c, _, hc⟩ := hχ.conjugate m
  obtain ⟨d, _, hd⟩ := hχ.mul l (-m)
  have heq : (fun y => χ l y * conj (χ m y)) =ᵐ[η]
      (fun y => (c * d) * χ (l - m) y) := by
    filter_upwards [hc, hd] with y hy hz
    rw [hy]
    calc
      χ l y * (c * χ (-m) y) = c * (χ l y * χ (-m) y) := by ring
      _ = c * (d * χ (l + -m) y) := by rw [hz]
      _ = (c * d) * χ (l - m) y := by simp only [sub_eq_add_neg]; ring
  rw [integral_congr_ae heq, integral_const_mul, hχ.mean _ (sub_ne_zero.mpr hlm), mul_zero]

theorem integrable_finset_prod {ι : Type*} (s : Finset ι) (l : ι → L) :
    Integrable (fun y => ∏ i ∈ s, χ (l i) y) η := by
  obtain ⟨c, _, hp⟩ := hχ.finset_prod s l
  exact ((hχ.integrable _).const_mul c).congr hp.symm

theorem weighted_finset_prod {ι : Type*} (s : Finset ι) (l : ι → L) (a : ι → ℂ) :
    Integrable (fun y => ∏ i ∈ s, a i * χ (l i) y) η ∧
    (∫ y, ∏ i ∈ s, a i * χ (l i) y ∂η) =
      (∏ i ∈ s, a i) * ∫ y, ∏ i ∈ s, χ (l i) y ∂η := by
  simp_rw [Finset.prod_mul_distrib]
  exact ⟨(hχ.integrable_finset_prod s l).const_mul _, integral_const_mul _ _⟩

end ProjectiveCharacters

def Dissociated {L : Type*} [AddCommGroup L] (l : ℕ → L) : Prop :=
  ∀ s : Finset ℕ, s.Nonempty → ∀ ε : ℕ → Bool,
    (∑ i ∈ s, if ε i then l i else -l i) ≠ 0

namespace ProjectiveCharacters
variable {Y L : Type*} [MeasurableSpace Y] [AddCommGroup L]
  {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
  (hχ : ProjectiveCharacters η χ)
include hχ

theorem integral_signed_linear_prod_eq_zero (l : ℕ → L) (hd : Dissociated l)
    (s : Finset ℕ) (hs : s.Nonempty) (a b : ℕ → ℂ) :
    Integrable (fun y => ∏ i ∈ s, (a i * χ (l i) y + b i * χ (-l i) y)) η ∧
    (∫ y, ∏ i ∈ s, (a i * χ (l i) y + b i * χ (-l i) y) ∂η) = 0 := by
  classical
  let term (t : Finset ℕ) (y : Y) :=
    (∏ i ∈ t, a i * χ (l i) y) * ∏ i ∈ s \ t, b i * χ (-l i) y
  have ht (t : Finset ℕ) (hts : t ⊆ s) : term t = fun y => ∏ i ∈ s,
      (if i ∈ t then a i else b i) * χ (if i ∈ t then l i else -l i) y := by
    funext y
    let f (i : ℕ) := (if i ∈ t then a i else b i) *
      χ (if i ∈ t then l i else -l i) y
    change _ = ∏ i ∈ s, f i
    rw [← Finset.prod_sdiff hts, mul_comm]
    apply congrArg₂ (· * ·)
    · exact Finset.prod_congr rfl (fun i hi => by simp [f, hi])
    · exact Finset.prod_congr rfl (fun i hi => by simp [f, (Finset.mem_sdiff.mp hi).2])
  have hterm (t : Finset ℕ) (hts : t ∈ s.powerset) :
      Integrable (term t) η ∧ (∫ y, term t y ∂η) = 0 := by
    rw [ht t (Finset.mem_powerset.mp hts)]
    have hh := hχ.weighted_finset_prod s
      (fun i => if i ∈ t then l i else -l i) (fun i => if i ∈ t then a i else b i)
    refine ⟨hh.1, hh.2.trans ?_⟩
    rw [hχ.integral_finset_prod_eq_zero s _ (by
      simpa using hd s hs (fun i => decide (i ∈ t))), mul_zero]
  have heq : (fun y => ∏ i ∈ s, (a i * χ (l i) y + b i * χ (-l i) y)) =
      fun y => ∑ t ∈ s.powerset, term t y := by
    funext y
    exact Finset.prod_add _ _ s
  rw [heq]
  exact ⟨integrable_finsetSum _ (fun t ht => (hterm t ht).1), by
    rw [integral_finsetSum _ (fun t ht => (hterm t ht).1)]
    exact Finset.sum_eq_zero (fun t ht => (hterm t ht).2)⟩

theorem integral_real_prod_eq_zero (l : ℕ → L) (hd : Dissociated l)
    (s : Finset ℕ) (hs : s.Nonempty) (w : ℕ → ℂ) :
    Integrable (fun y => ∏ i ∈ s, (w i * conj (χ (l i) y)).re) η ∧
    (∫ y, ∏ i ∈ s, (w i * conj (χ (l i) y)).re ∂η) = 0 := by
  choose c hc heq using fun i => hχ.conjugate (l i)
  have hlin := hχ.integral_signed_linear_prod_eq_zero l hd s hs
    (fun i => conj (w i) / 2) (fun i => w i * c i / 2)
  have heq' : (fun y => ((∏ i ∈ s, (w i * conj (χ (l i) y)).re : ℝ) : ℂ)) =ᵐ[η]
      (fun y => ∏ i ∈ s, (conj (w i) / 2 * χ (l i) y +
        (w i * c i / 2) * χ (-l i) y)) := by
    filter_upwards [ae_all_iff.mpr heq] with y hy
    push_cast
    apply Finset.prod_congr rfl
    intro i _
    rw [Complex.re_eq_add_conj, map_mul, starRingEnd_self_apply, hy i]
    ring
  have hint : Integrable (fun y => ((∏ i ∈ s, (w i * conj (χ (l i) y)).re : ℝ) : ℂ)) η :=
    hlin.1.congr heq'.symm
  have hintR := hint.re
  change Integrable (fun y => (((∏ i ∈ s, (w i * conj (χ (l i) y)).re : ℝ) : ℂ)).re) η at hintR
  refine ⟨by simpa only [Complex.ofReal_re] using hintR, ?_⟩
  apply Complex.ofReal_injective
  rw [← integral_complex_ofReal, integral_congr_ae heq', hlin.2]
  rfl

theorem integral_affine_real_prod (l : ℕ → L) (hd : Dissociated l)
    (s : Finset ℕ) (w : ℕ → ℂ) (b : ℕ → ℝ) :
    Integrable (fun y => ∏ i ∈ s, (b i + (w i * conj (χ (l i) y)).re)) η ∧
    (∫ y, ∏ i ∈ s, (b i + (w i * conj (χ (l i) y)).re) ∂η) = ∏ i ∈ s, b i := by
  classical
  have ht (t : Finset ℕ) :
      Integrable (fun y => (∏ i ∈ t, (w i * conj (χ (l i) y)).re) *
        ∏ i ∈ s \ t, b i) η ∧
      (∫ y, (∏ i ∈ t, (w i * conj (χ (l i) y)).re) *
        ∏ i ∈ s \ t, b i ∂η) = if t = ∅ then ∏ i ∈ s, b i else 0 := by
    by_cases he : t = ∅
    · subst t
      simp
    · obtain ⟨hit, hzt⟩ := hχ.integral_real_prod_eq_zero l hd t
        (Finset.nonempty_iff_ne_empty.mpr he) w
      exact ⟨hit.mul_const _, by rw [integral_mul_const, hzt]; simp [he]⟩
  have hex (y : Y) :
      (∏ i ∈ s, (b i + (w i * conj (χ (l i) y)).re)) =
      ∑ t ∈ s.powerset, (∏ i ∈ t, (w i * conj (χ (l i) y)).re) *
        ∏ i ∈ s \ t, b i := by
    simp_rw [add_comm (b _)]
    exact Finset.prod_add _ _ _
  simp_rw [hex]
  refine ⟨integrable_finsetSum _ (fun t _ => (ht t).1), ?_⟩
  rw [integral_finsetSum _ (fun t _ => (ht t).1)]
  simp_rw [(ht _).2]
  simp

theorem dissociated_exponential_bound (l : ℕ → L) (hd : Dissociated l)
    (s : Finset ℕ) (w : ℕ → ℂ) (hw : ∀ i ∈ s, ‖w i‖ ≤ 1)
    {θ : ℝ} (hθ : 0 ≤ θ) (hθ1 : θ ≤ 1) :
    Integrable (fun y => Real.exp (θ * ∑ i ∈ s, (w i * conj (χ (l i) y)).re)) η ∧
    (∫ y, Real.exp (θ * ∑ i ∈ s, (w i * conj (χ (l i) y)).re) ∂η) ≤
      Real.exp (2 * θ ^ 2 * s.card) := by
  have hg := hχ.integral_affine_real_prod l hd s (fun i => (θ : ℂ) * w i)
    (fun _ => 1 + 2 * θ ^ 2)
  have hscale (i : ℕ) (y : Y) :
      ((θ : ℂ) * w i * conj (χ (l i) y)).re =
        θ * (w i * conj (χ (l i) y)).re := by
    simp only [mul_assoc, Complex.mul_re, Complex.ofReal_re, Complex.ofReal_im, zero_mul, sub_zero]
  simp_rw [hscale] at hg
  have hpoint : ∀ᵐ y ∂η, ∀ i ∈ s,
      Real.exp (θ * (w i * conj (χ (l i) y)).re) ≤
        1 + 2 * θ ^ 2 + θ * (w i * conj (χ (l i) y)).re := by
    filter_upwards [ae_all_iff.mpr (fun i => hχ.modulus (l i))] with y hy i hi
    have hr : |(w i * conj (χ (l i) y)).re| ≤ 1 := by
      calc
        _ ≤ ‖w i * conj (χ (l i) y)‖ := Complex.abs_re_le_norm _
        _ = ‖w i‖ := by rw [norm_mul, Complex.norm_conj, hy i, mul_one]
        _ ≤ 1 := hw i hi
    have ht : |θ * (w i * conj (χ (l i) y)).re| ≤ θ := by
      rw [abs_mul, abs_of_nonneg hθ]
      simpa using mul_le_mul_of_nonneg_left hr hθ
    have hq := Real.abs_exp_sub_one_sub_id_le (ht.trans hθ1)
    have hqq : (θ * (w i * conj (χ (l i) y)).re) ^ 2 ≤ θ ^ 2 := by
      rw [← sq_abs]
      exact (sq_le_sq₀ (abs_nonneg _) hθ).mpr ht
    have hupper := (le_abs_self _).trans hq
    nlinarith [sq_nonneg θ]
  have hprod : (fun y => Real.exp (θ * ∑ i ∈ s, (w i * conj (χ (l i) y)).re)) ≤ᵐ[η]
      (fun y => ∏ i ∈ s, (1 + 2 * θ ^ 2 + θ * (w i * conj (χ (l i) y)).re)) := by
    filter_upwards [hpoint] with y hy
    rw [Finset.mul_sum, Real.exp_sum]
    exact Finset.prod_le_prod₀ (fun _ _ => (Real.exp_pos _).le) hy
  have hm : AEStronglyMeasurable
      (fun y => Real.exp (θ * ∑ i ∈ s, (w i * conj (χ (l i) y)).re)) η := by
    apply Real.continuous_exp.comp_aestronglyMeasurable
    apply AEStronglyMeasurable.const_mul
    have hi (i : ℕ) : AEStronglyMeasurable
        (fun y => (w i * conj (χ (l i) y)).re) η :=
      Complex.continuous_re.comp_aestronglyMeasurable
        ((hχ.measurable (l i)).star.const_mul (w i))
    convert Finset.aestronglyMeasurable_sum s (fun i _ => hi i) using 1
    funext y
    simp only [Finset.sum_apply]
  have hint := hg.1.mono' hm (hprod.mono (fun y hy => by
    simpa only [Real.norm_of_nonneg (Real.exp_pos _).le] using hy))
  refine ⟨hint, (integral_mono_ae hint hg.1 hprod).trans ?_⟩
  rw [hg.2, Finset.prod_const]
  calc
    (1 + 2 * θ ^ 2) ^ s.card ≤ (Real.exp (2 * θ ^ 2)) ^ s.card := by
      apply pow_le_pow_left₀ (by positivity)
      simpa only [add_comm] using Real.add_one_le_exp (2 * θ ^ 2)
    _ = Real.exp (2 * θ ^ 2 * s.card) := by rw [← Real.exp_nat_mul, mul_comm]

end ProjectiveCharacters
end

open MeasureTheory Filter
open scoped BigOperators Topology

section

noncomputable def shannonEntropy {A : Type*} [Fintype A] (p : A → ℝ) : ℝ :=
  ∑ a, -p a * Real.log (p a)

section FiniteDistribution
variable {A : Type*} [Fintype A] (p : A → ℝ)
    (hp : ∀ a, 0 ≤ p a) (hsum : ∑ a, p a = 1)
include hp hsum

theorem probability_le_one (a : A) : p a ≤ 1 := by
  rw [← hsum]
  exact Finset.single_le_sum (fun a _ => hp a) (Finset.mem_univ a)

theorem entropy_term_nonneg (a : A) : 0 ≤ -p a * Real.log (p a) := by
  rw [neg_mul, neg_nonneg]
  exact mul_nonpos_of_nonneg_of_nonpos (hp a)
    (Real.log_nonpos (hp a) (probability_le_one p hp hsum a))

theorem shannonEntropy_nonneg : 0 ≤ shannonEntropy p :=
  Finset.sum_nonneg (fun a _ => entropy_term_nonneg p hp hsum a)

theorem unlikely_mass_bound {a : ℝ} (ha : 0 < a) :
    ∑ i ∈ Finset.univ.filter (fun i => p i < Real.exp (-a)), p i ≤
      shannonEntropy p / a := by
  classical
  rw [le_div_iff₀ ha, Finset.sum_mul]
  calc
    ∑ i ∈ Finset.univ.filter (fun i => p i < Real.exp (-a)), p i * a ≤
        ∑ i ∈ Finset.univ.filter (fun i => p i < Real.exp (-a)), -p i * Real.log (p i) := by
      apply Finset.sum_le_sum
      intro i hi
      by_cases hz : p i = 0
      · simp [hz]
      · have hpi : 0 < p i := (hp i).lt_of_ne' hz
        have hlog := (Real.log_lt_iff_lt_exp hpi).mpr (Finset.mem_filter.mp hi).2
        nlinarith [mul_nonneg (hp i) (le_of_lt (show 0 < -a - Real.log (p i) by linarith))]
    _ ≤ shannonEntropy p := by
      apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _)
      intro i _ _
      exact entropy_term_nonneg p hp hsum i

theorem likely_card_bound (a : ℝ) :
    ((Finset.univ.filter (fun i => Real.exp (-a) ≤ p i)).card : ℝ) ≤ Real.exp a := by
  classical
  have h : ((Finset.univ.filter (fun i => Real.exp (-a) ≤ p i)).card : ℝ) *
      Real.exp (-a) ≤ 1 := by
    calc
      _ = ∑ i ∈ Finset.univ.filter (fun i => Real.exp (-a) ≤ p i), Real.exp (-a) := by simp
      _ ≤ ∑ i ∈ Finset.univ.filter (fun i => Real.exp (-a) ≤ p i), p i :=
        Finset.sum_le_sum (fun i hi => (Finset.mem_filter.mp hi).2)
      _ ≤ ∑ i, p i :=
        Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _) (fun i _ _ => hp i)
      _ = 1 := hsum
  have hm := mul_le_mul_of_nonneg_right h (Real.exp_pos a).le
  simpa only [mul_assoc, ← Real.exp_add, neg_add_cancel, Real.exp_zero, mul_one, one_mul] using hm

end FiniteDistribution
variable {Y : Type*} [MeasurableSpace Y] {η : Measure Y} [IsProbabilityMeasure η]

theorem exponential_tail_bound (S : Y → ℝ) {θ b t : ℝ} (hθ : 0 < θ)
    (hint : Integrable (fun y => Real.exp (θ * S y)) η)
    (hbound : (∫ y, Real.exp (θ * S y) ∂η) ≤ Real.exp b) :
    η.real {y | t < S y} ≤ Real.exp (b - θ * t) := by
  have hm := mul_meas_ge_le_integral_of_nonneg
    (Eventually.of_forall (fun y => (Real.exp_pos (θ * S y)).le)) hint (Real.exp (θ * t))
  have hsub : {y | t < S y} ⊆ {y | Real.exp (θ * t) ≤ Real.exp (θ * S y)} := by
    intro y hy
    exact Real.exp_le_exp.mpr (mul_le_mul_of_nonneg_left hy.le hθ.le)
  have hm' := (mul_le_mul_of_nonneg_left (measureReal_mono hsub) (Real.exp_pos _).le).trans
    (hm.trans hbound)
  rw [Real.exp_sub]
  exact (le_div_iff₀ (Real.exp_pos _)).mpr (by simpa only [mul_comm] using hm')

theorem randomized_tail_bound {A : Type*} [Fintype A] (F : Y → A)
    (hF : ∀ a, MeasurableSet (F ⁻¹' {a})) (S : A → Y → ℝ)
    {a ε δ : ℝ} (ha : 0 < a) (hδ : 0 ≤ δ)
    (ht : ∀ w, η.real {y | ε < S w y} ≤ δ) :
    η.real {y | ε < S (F y) y} ≤
      shannonEntropy (fun w => η.real (F ⁻¹' {w})) / a + Real.exp a * δ := by
  classical
  let p (w : A) := η.real (F ⁻¹' {w})
  have hp : ∀ w, 0 ≤ p w := fun _ => measureReal_nonneg
  have hsum : ∑ w, p w = 1 := by
    have hh := sum_measureReal_preimage_singleton (μ := η) Finset.univ (fun w _ => hF w)
    simpa [p] using hh
  let good := Finset.univ.filter (fun w => Real.exp (-a) ≤ p w)
  let bad := Finset.univ.filter (fun w => p w < Real.exp (-a))
  have hsub : {y | ε < S (F y) y} ⊆
      (F ⁻¹' (bad : Set A)) ∪ ⋃ w ∈ good, {y | ε < S w y} := by
    intro y hy
    by_cases hg : Real.exp (-a) ≤ p (F y)
    · right
      exact Set.mem_iUnion.mpr ⟨F y, Set.mem_iUnion.mpr ⟨by simp [good, hg], hy⟩⟩
    · left
      simpa [bad] using lt_of_not_ge hg
  have hbad : η.real (F ⁻¹' (bad : Set A)) ≤ shannonEntropy p / a := by
    rw [← sum_measureReal_preimage_singleton bad (fun w _ => hF w)]
    exact unlikely_mass_bound p hp hsum ha
  calc
    η.real {y | ε < S (F y) y} ≤
        η.real (F ⁻¹' (bad : Set A)) + η.real (⋃ w ∈ good, {y | ε < S w y}) :=
      (measureReal_mono hsub).trans (measureReal_union_le _ _)
    _ ≤ shannonEntropy p / a + ∑ w ∈ good, η.real {y | ε < S w y} :=
      add_le_add hbad (measureReal_biUnion_finset_le _ _)
    _ ≤ shannonEntropy p / a + Real.exp a * δ := by
      apply add_le_add_right
      calc
        _ ≤ ∑ _ ∈ good, δ := Finset.sum_le_sum (fun w _ => ht w)
        _ = (good.card : ℝ) * δ := by simp
        _ ≤ Real.exp a * δ := mul_le_mul_of_nonneg_right (likely_card_bound p hp hsum a) hδ

end

section
open MeasureTheory Filter
open scoped BigOperators Topology

theorem integral_le_threshold_add_tail {Y : Type*} [MeasurableSpace Y]
    {η : Measure Y} [IsProbabilityMeasure η] {S : Y → ℝ}
    (hint : Integrable S η) (hS : ∀ᵐ y ∂η, S y ≤ 1) {ε : ℝ} (hε : 0 ≤ ε) :
    (∫ y, S y ∂η) ≤ ε + η.real {y | ε < S y} := by
  let s := {y | ε < S y}
  have hs : NullMeasurableSet s η :=
    aestronglyMeasurable_const.nullMeasurableSet_lt hint.aestronglyMeasurable
  have he : ∫ y in s, S y ∂η ≤ η.real s := by
    have hh := integral_mono_ae hint.restrict (integrable_const (1 : ℝ))
      (ae_restrict_of_ae hS : ∀ᵐ y ∂η.restrict s, S y ≤ 1)
    simpa using hh
  have hc : ∫ y in sᶜ, S y ∂η ≤ ε := by
    have hh : ∫ y in sᶜ, S y ∂η ≤ η.real sᶜ * ε := by
      have hh := integral_mono_ae hint.restrict (integrable_const ε)
        ((ae_restrict_mem₀ hs.compl).mono (fun y hy => le_of_not_gt hy))
      simpa using hh
    exact hh.trans (by simpa using mul_le_mul_of_nonneg_right (measureReal_le_one (s := sᶜ)) hε)
  rw [← integral_add_compl₀ hs hint]
  linarith

end

section
open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate

variable {Y L : Type*} [MeasurableSpace Y] [AddCommGroup L]
    {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}

theorem dissociated_tail_bound (hχ : ProjectiveCharacters η χ)
    (l : ℕ → L) (hd : Dissociated l) (n : ℕ) (hn : 0 < n)
    (w : ℕ → ℂ) (hw : ∀ i < n, ‖w i‖ ≤ 1)
    {ε : ℝ} (hε : 0 < ε) (hε1 : ε ≤ 1) :
    η.real {y | ε < (∑ i ∈ Finset.range n, (w i * conj (χ (l i) y)).re) / n} ≤
      Real.exp (-ε ^ 2 * n / 8) := by
  have hn' : (0 : ℝ) < n := by exact_mod_cast hn
  have hh := hχ.dissociated_exponential_bound l hd (Finset.range n) w
    (fun i hi => hw i (Finset.mem_range.mp hi)) (θ := ε / 4) (by positivity) (by linarith)
  have ht := exponential_tail_bound
    (fun y => ∑ i ∈ Finset.range n, (w i * conj (χ (l i) y)).re)
    (θ := ε / 4) (b := 2 * (ε / 4) ^ 2 * n) (t := ε * n) (by positivity)
    hh.1 (by simpa using hh.2)
  have he : (-ε ^ 2 * (n : ℝ) / 8) = 2 * (ε / 4) ^ 2 * n - ε / 4 * (ε * n) := by ring
  rw [he]
  convert ht using 1
  congr 1
  ext y
  exact lt_div_iff₀ hn'

def entropyWord {A : Type*} (F : ℕ → Y → A) (n : ℕ) : Y → (Fin n → A) :=
  fun y i => F i.val y

noncomputable def wordEntropy {A : Type*} [Fintype A] (F : ℕ → Y → A) (n : ℕ) : ℝ :=
  shannonEntropy (fun w => η.real (entropyWord F n ⁻¹' {w}))

end

section
open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate
variable {Y L A : Type*} [MeasurableSpace Y] [AddCommGroup L]
    {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]

theorem randomized_dissociated_tail (hχ : ProjectiveCharacters η χ)
    (l : ℕ → L) (hd : Dissociated l)
    (F : ℕ → Y → A) (hF : ∀ i, Measurable (F i))
    (v : A → ℂ) (hv : ∀ a, ‖v a‖ ≤ 1)
    (ω : ℕ → ℂ) (hω : ∀ i, ‖ω i‖ ≤ 1)
    (n : ℕ) (hn : 0 < n) {a ε : ℝ} (ha : 0 < a) (hε : 0 < ε) (hε1 : ε ≤ 1) :
    η.real {y | ε < (∑ i ∈ Finset.range n,
      (ω i * v (F i y) * conj (χ (l i) y)).re) / n} ≤
      wordEntropy (η := η) F n / a + Real.exp (a - ε ^ 2 * n / 8) := by
  classical
  let w (t : Fin n → A) (i : ℕ) := if h : i < n then ω i * v (t ⟨i, h⟩) else 0
  let S (t : Fin n → A) (y : Y) :=
    (∑ i ∈ Finset.range n, (w t i * conj (χ (l i) y)).re) / n
  have ht (t : Fin n → A) : η.real {y | ε < S t y} ≤ Real.exp (-ε ^ 2 * n / 8) := by
    apply dissociated_tail_bound hχ l hd n hn (w t) _ hε hε1
    intro i hi
    simp only [w, dite_eq_left hi, norm_mul]
    exact (mul_le_mul (hω i) (hv _) (norm_nonneg _) (by norm_num)).trans_eq (one_mul 1)
  have hf : Measurable (entropyWord F n) := Measurable.of_eval (fun i => hF i.val)
  have hh := randomized_tail_bound (entropyWord F n)
    (fun t => hf (measurableSet_singleton t)) S ha (Real.exp_pos _).le ht
  have he (y : Y) : S (entropyWord F n y) y =
      (∑ i ∈ Finset.range n, (ω i * v (F i y) * conj (χ (l i) y)).re) / n := by
    dsimp only [S]
    apply congrArg (fun r : ℝ => r / (n : ℝ))
    apply Finset.sum_congr rfl
    intro i hi
    simp only [w, dite_eq_left (Finset.mem_range.mp hi), entropyWord]
  simp_rw [he] at hh
  simpa only [wordEntropy, ← Real.exp_add, sub_eq_add_neg, neg_mul, neg_div] using hh

end

section
open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate

theorem exists_aligning_phase (z : ℂ) : ∃ ω : ℂ, ‖ω‖ = 1 ∧ (ω * z).re = ‖z‖ := by
  by_cases hz : z = 0
  · exact ⟨1, by simp, by simp [hz]⟩
  · refine ⟨conj z / (‖z‖ : ℂ), ?_, ?_⟩
    · simp [hz]
    · have hn : ‖z‖ ≠ 0 := norm_ne_zero_iff.mpr hz
      rw [div_mul_eq_mul_div, ← Complex.normSq_eq_conj_mul_self, Complex.div_ofReal_re,
        Complex.ofReal_re, Complex.normSq_eq_norm_sq]
      field_simp

variable {Y L A : Type*} [MeasurableSpace Y] [AddCommGroup L]
    {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]

theorem dissociated_correlation_mean_bound (hχ : ProjectiveCharacters η χ)
    (l : ℕ → L) (hd : Dissociated l)
    (F : ℕ → Y → A) (hF : ∀ i, Measurable (F i))
    (v : A → ℂ) (hv : ∀ a, ‖v a‖ ≤ 1)
    (n : ℕ) (hn : 0 < n) {a ε : ℝ} (ha : 0 < a) (hε : 0 < ε) (hε1 : ε ≤ 1) :
    (∑ i ∈ Finset.range n, ‖∫ y, v (F i y) * conj (χ (l i) y) ∂η‖) / n ≤
      ε + wordEntropy (η := η) F n / a + Real.exp (a - ε ^ 2 * n / 8) := by
  choose ω hω hw using fun i =>
    exists_aligning_phase (∫ y, v (F i y) * conj (χ (l i) y) ∂η)
  let q (i : ℕ) (y : Y) := ω i * v (F i y) * conj (χ (l i) y)
  have hqm (i : ℕ) : AEStronglyMeasurable (q i) η :=
    ((((measurable_of_finite v).comp (hF i)).aestronglyMeasurable.const_mul (ω i)).mul
      (hχ.measurable (l i)).star)
  have hqb (i : ℕ) : ∀ᵐ y ∂η, ‖q i y‖ ≤ 1 := by
    filter_upwards [hχ.modulus (l i)] with y hy
    simpa only [q, norm_mul, Complex.norm_conj, hy, hω i, one_mul, mul_one] using hv (F i y)
  have hqi (i : ℕ) : Integrable (q i) η :=
    (integrable_const (1 : ℝ)).mono' (hqm i) (hqb i)
  have hqR (i : ℕ) : Integrable (fun y => (q i y).re) η := (hqi i).re
  let S (y : Y) := (∑ i ∈ Finset.range n, (q i y).re) / n
  have hSi : Integrable S η :=
    (integrable_finsetSum _ (fun i _ => hqR i)).div_const _
  have hn' : (0 : ℝ) < n := by exact_mod_cast hn
  have hSb : ∀ᵐ y ∂η, S y ≤ 1 := by
    filter_upwards [ae_all_iff.mpr hqb] with y hy
    apply (div_le_iff₀ hn').mpr
    calc
      _ ≤ ∑ _ ∈ Finset.range n, (1 : ℝ) := Finset.sum_le_sum
        (fun i _ => (Complex.re_le_norm _).trans (hy i))
      _ = 1 * n := by simp
  have hmean : (∫ y, S y ∂η) =
      (∑ i ∈ Finset.range n, ‖∫ y, v (F i y) * conj (χ (l i) y) ∂η‖) / n := by
    rw [integral_div, integral_finsetSum _ (fun i _ => hqR i)]
    congr 1
    apply Finset.sum_congr rfl
    intro i _
    change (∫ y, Complex.reCLM (q i y) ∂η) = _
    rw [Complex.reCLM.integral_comp_comm (hqi i)]
    change (∫ y, ω i * v (F i y) * conj (χ (l i) y) ∂η).re = _
    simp_rw [mul_assoc]
    rw [integral_const_mul]
    exact hw i
  rw [← hmean]
  have htail := randomized_dissociated_tail hχ l hd F hF v hv ω (fun i => (hω i).le)
    n hn ha hε hε1
  have hh := integral_le_threshold_add_tail hSi hSb hε.le
  exact hh.trans (by simpa only [add_assoc] using add_le_add_right htail ε)

end

section
open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate
variable {Y L A : Type*} [MeasurableSpace Y] [AddCommGroup L]
    {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]

theorem entropy_cancellation (hχ : ProjectiveCharacters η χ)
    (l : ℕ → L) (hd : Dissociated l)
    (F : ℕ → Y → A) (hF : ∀ i, Measurable (F i))
    (v : A → ℂ) (hv : ∀ a, ‖v a‖ ≤ 1)
    (hH : Tendsto (fun n : ℕ => wordEntropy (η := η) F n / n) atTop (𝓝 0)) :
    Tendsto (fun n : ℕ =>
      (∑ i ∈ Finset.range n, ‖∫ y, v (F i y) * conj (χ (l i) y) ∂η‖) / n)
      atTop (𝓝 0) := by
  apply tendsto_order.mpr
  constructor
  · intro b hb
    exact Eventually.of_forall (fun n => hb.trans_le (by positivity))
  · intro b hb
    let ε : ℝ := min (b / 2) 1
    have hε : 0 < ε := lt_min (by positivity) zero_lt_one
    have hε1 : ε ≤ 1 := min_le_right _ _
    have hεb : ε ≤ b / 2 := min_le_left _ _
    let c : ℝ := ε ^ 2 / 16
    have hc : 0 < c := by positivity
    have hE : Tendsto (fun n : ℕ => Real.exp (-(c * n))) atTop (𝓝 0) :=
      Real.tendsto_exp_atBot.comp
        (tendsto_neg_atTop_atBot.comp ((tendsto_const_mul_atTop_of_pos hc).mpr
          tendsto_natCast_atTop_atTop))
    have hH' : Tendsto (fun n : ℕ => wordEntropy (η := η) F n / (c * n)) atTop (𝓝 0) := by
      simpa only [div_div, mul_comm, zero_div] using hH.div_const c
    have ht := hH'.add hE
    simp only [add_zero] at ht
    filter_upwards [ht.eventually (gt_mem_nhds (show 0 < b / 2 by positivity)),
      eventually_gt_atTop 0] with n hn hn0
    have hn' : (0 : ℝ) < n := by exact_mod_cast hn0
    have hh := dissociated_correlation_mean_bound hχ l hd F hF v hv n hn0
      (a := c * n) (mul_pos hc hn') hε hε1
    have he : c * (n : ℝ) - ε ^ 2 * n / 8 = -(c * n) := by dsimp [c]; ring
    rw [he] at hh
    linarith

end

section FactorEntropy
variable {A B : Type*} [Fintype A] [Fintype B]

theorem shannonEntropy_map_le [DecidableEq B] (p : A → ℝ) (hp : ∀ a, 0 ≤ p a) (f : A → B) :
    shannonEntropy (fun b => ∑ a, if f a = b then p a else 0) ≤ shannonEntropy p := by
  classical
  let q (b : B) := ∑ a, if f a = b then p a else 0
  have hpq (a : A) : p a ≤ q (f a) := by
    exact (by simpa [q] using
      (Finset.single_le_sum (s := Finset.univ)
        (f := fun x => if f x = f a then p x else 0)
        (fun x _ => by split_ifs; exact hp x; exact le_rfl) (Finset.mem_univ a)))
  have he (b : B) : -q b * Real.log (q b) =
      ∑ a, if f a = b then -p a * Real.log (q b) else 0 := by
    change -(∑ a, if f a = b then p a else 0) * Real.log (q b) = _
    rw [neg_mul, Finset.sum_mul, ← Finset.sum_neg_distrib]
    apply Finset.sum_congr rfl
    intro a _
    split_ifs <;> simp
  change (∑ b, -q b * Real.log (q b)) ≤ ∑ a, -p a * Real.log (p a)
  simp_rw [he]
  rw [Finset.sum_comm]
  apply Finset.sum_le_sum
  intro a _
  simp only [Finset.sum_ite_eq, Finset.mem_univ, ite_true]
  by_cases ha : p a = 0
  · simp [ha]
  · exact mul_le_mul_of_nonpos_left
      (Real.log_le_log ((hp a).lt_of_ne' ha) (hpq a)) (neg_nonpos.mpr (hp a))

end FactorEntropy
section
variable {Y A B : Type*} [MeasurableSpace Y] {η : Measure Y} [IsProbabilityMeasure η]
    [Fintype A] [Fintype B] [MeasurableSpace A] [MeasurableSingletonClass A]

theorem randomEntropy_comp_le (F : Y → A) (hF : Measurable F) (g : A → B) :
    shannonEntropy (fun b => η.real ((g ∘ F) ⁻¹' {b})) ≤
      shannonEntropy (fun a => η.real (F ⁻¹' {a})) := by
  classical
  have he (b : B) : η.real ((g ∘ F) ⁻¹' {b}) =
      ∑ a, if g a = b then η.real (F ⁻¹' {a}) else 0 := by
    rw [← Finset.sum_filter]
    have hh := sum_measureReal_preimage_singleton (μ := η)
      (Finset.univ.filter (fun a => g a = b)) (fun a _ => hF (measurableSet_singleton a))
    rw [hh]
    congr 1
    ext y
    simp
  simp_rw [he]
  exact shannonEntropy_map_le _ (fun _ => measureReal_nonneg) g

theorem wordEntropy_nonneg (F : ℕ → Y → A) (hF : ∀ n, Measurable (F n)) (n : ℕ) :
    0 ≤ wordEntropy (η := η) F n := by
  apply shannonEntropy_nonneg _ (fun _ => measureReal_nonneg)
  have hm : Measurable (entropyWord F n) := Measurable.of_eval (fun _ => hF _)
  have hh := sum_measureReal_preimage_singleton (μ := η) Finset.univ
    (fun w _ => hm (measurableSet_singleton w))
  simpa using hh

theorem wordEntropy_progression_le (F : ℕ → Y → A) (hF : ∀ n, Measurable (F n))
    (p : ℕ) (hp : 0 < p) (j n : ℕ) :
    wordEntropy (η := η) (fun m => F (p * m + j)) n ≤
      wordEntropy (η := η) F (p * n + j) := by
  let select (w : Fin (p * n + j) → A) (i : Fin n) :=
    w ⟨p * i.val + j, Nat.add_lt_add_right (Nat.mul_lt_mul_of_pos_left i.isLt hp) j⟩
  have hm : Measurable (entropyWord F (p * n + j)) :=
    Measurable.of_eval (fun _ => hF _)
  exact randomEntropy_comp_le (entropyWord F (p * n + j)) hm select

theorem zero_entropy_progression (F : ℕ → Y → A) (hF : ∀ n, Measurable (F n))
    (hH : Tendsto (fun n : ℕ => wordEntropy (η := η) F n / n) atTop (𝓝 0))
    (p : ℕ) (hp : 0 < p) (j : ℕ) :
    Tendsto (fun n : ℕ => wordEntropy (η := η) (fun m => F (p * m + j)) n / n)
      atTop (𝓝 0) := by
  have hM : Tendsto (fun n : ℕ => p * n + j) atTop atTop := by
    apply tendsto_atTop_mono (fun n => ?_) tendsto_id
    change n ≤ p * n + j
    have hh := Nat.mul_le_mul_right n hp
    omega
  have ht := (hH.comp hM).mul_const ((p + j : ℕ) : ℝ)
  simp only [zero_mul] at ht
  apply squeeze_zero' ?_ ?_ ht
  · exact Eventually.of_forall (fun n => div_nonneg
      (wordEntropy_nonneg _ (fun m => hF (p * m + j)) n) (Nat.cast_nonneg n))
  · filter_upwards [eventually_gt_atTop 0] with n hn
    have hn' : (0 : ℝ) < n := by exact_mod_cast hn
    have hM' : (0 : ℝ) < p * n + j := by positivity
    have hMn : (p * n + j : ℝ) ≤ (p + j) * n := by
      have h1 : (1 : ℝ) ≤ n := by exact_mod_cast hn
      nlinarith [mul_le_mul_of_nonneg_left h1 (show (0 : ℝ) ≤ j by positivity)]
    have hpos := wordEntropy_nonneg (η := η) F hF (p * n + j)
    calc
      _ ≤ wordEntropy (η := η) F (p * n + j) / n :=
        div_le_div_of_nonneg_right (wordEntropy_progression_le F hF p hp j n) hn'.le
      _ ≤ wordEntropy (η := η) F (p * n + j) / (p * n + j) * (p + j) := by
        apply (div_le_iff₀ hn').mpr
        rw [div_mul_eq_mul_div, div_mul_eq_mul_div]
        apply (le_div_iff₀ hM').mpr
        nlinarith [mul_le_mul_of_nonneg_left hMn hpos]
      _ = _ := by simp only [Function.comp_apply, Nat.cast_add, Nat.cast_mul]

end

open MeasureTheory Filter
open scoped Topology InnerProductSpace ComplexConjugate


section Hilbert
variable {H ι : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H]
    (U : ι → H →ₗᵢ[ℂ] H) (l : Filter ι) (e : H)

theorem isClosed_mixing_right (f : H) :
    IsClosed {g : H | Tendsto (fun i => inner ℂ f (U i g)) l
      (𝓝 (inner ℂ f e * inner ℂ e g))} := by
  apply Equicontinuous.isClosed_setOfPred_tendsto
  · apply UniformEquicontinuous.equicontinuous
    apply LipschitzWith.uniformEquicontinuous _ ‖f‖₊
    intro i
    apply LipschitzWith.of_dist_le_mul
    intro x y
    rw [dist_eq_norm, ← inner_sub_right]
    calc
      ‖inner ℂ f (U i x - U i y)‖ ≤ ‖f‖ * ‖U i x - U i y‖ := norm_inner_le_norm _ _
      _ = ‖f‖₊ * dist x y := by rw [← map_sub, LinearIsometry.norm_map, dist_eq_norm]; rfl
  · exact continuous_const.mul (continuous_const.inner continuous_id)

theorem isClosed_mixing_left (g : H) :
    IsClosed {f : H | Tendsto (fun i => inner ℂ f (U i g)) l
      (𝓝 (inner ℂ f e * inner ℂ e g))} := by
  apply Equicontinuous.isClosed_setOfPred_tendsto
  · apply UniformEquicontinuous.equicontinuous
    apply LipschitzWith.uniformEquicontinuous _ ‖g‖₊
    intro i
    apply LipschitzWith.of_dist_le_mul
    intro x y
    rw [dist_eq_norm, ← inner_sub_left]
    calc
      ‖inner ℂ (x - y) (U i g)‖ ≤ ‖x - y‖ * ‖U i g‖ := norm_inner_le_norm _ _
      _ = ‖g‖₊ * dist x y := by rw [LinearIsometry.norm_map, dist_eq_norm]; exact mul_comm _ _
  · exact (continuous_id.inner continuous_const).mul continuous_const
end Hilbert
section

variable {Ω ι : Type*} [MeasurableSpace Ω]
    {μ : Measure Ω} [IsProbabilityMeasure μ]
    (t : ι → Ω → Ω) (ht : ∀ i, MeasurePreserving (t i) μ μ) (l : Filter ι)

noncomputable def probabilityOne : Lp ℂ 2 μ :=
  indicatorConstLp 2 MeasurableSet.univ (measure_ne_top _ _) (1 : ℂ)

theorem mixing_L2
    (hmix : ∀ A B : Set Ω, MeasurableSet A → MeasurableSet B →
      Tendsto (fun i => μ (A ∩ t i ⁻¹' B)) l (𝓝 (μ A * μ B)))
    (f g : Lp ℂ 2 μ) :
    Tendsto (fun i => inner ℂ f ((Lp.compMeasurePreservingₗᵢ ℂ (t i) (ht i)) g)) l
      (𝓝 (inner ℂ f (probabilityOne (μ := μ)) *
        inner ℂ (probabilityOne (μ := μ)) g)) := by
  let U := fun i => Lp.compMeasurePreservingₗᵢ (E := ℂ) (p := 2) ℂ (t i) (ht i)
  let e : Lp ℂ 2 μ := probabilityOne
  change Tendsto (fun i => inner ℂ f (U i g)) l (𝓝 (inner ℂ f e * inner ℂ e g))
  have hbase (A B : Set Ω) (hA : MeasurableSet A) (hB : MeasurableSet B)
      (a b : ℂ) : Tendsto (fun i => inner ℂ
        (indicatorConstLp 2 hA (measure_ne_top _ _) a)
        (U i (indicatorConstLp 2 hB (measure_ne_top _ _) b))) l
      (𝓝 (inner ℂ (indicatorConstLp 2 hA (measure_ne_top _ _) a) e *
        inner ℂ e (indicatorConstLp 2 hB (measure_ne_top _ _) b))) := by
    have hreal := (ENNReal.tendsto_toReal (by finiteness : μ A * μ B ≠ ⊤)).comp
      (hmix A B hA hB)
    have hcomplex := Complex.continuous_ofReal.continuousAt.tendsto.comp hreal
    have hc := hcomplex.mul_const (conj a * b)
    convert hc using 1
    · funext i
      change inner ℂ (indicatorConstLp 2 hA _ a)
        (Lp.compMeasurePreserving (t i) (ht i) (indicatorConstLp 2 hB _ b)) = _
      rw [Lp.indicatorConstLp_compMeasurePreserving,
        L2.inner_indicatorConstLp_indicatorConstLp]
      simp [RCLike.inner_apply, measureReal_def, mul_comm]
    · dsimp [e, probabilityOne]
      rw [L2.inner_indicatorConstLp_indicatorConstLp,
        L2.inner_indicatorConstLp_indicatorConstLp]
      congr 1
      simp [RCLike.inner_apply, ENNReal.toReal_mul, measureReal_def, Algebra.smul_def]
      ring
  have hfirst (A : Set Ω) (hA : MeasurableSet A) (a : ℂ) :
      ∀ g : Lp ℂ 2 μ, Tendsto (fun i => inner ℂ
        (indicatorConstLp 2 hA (measure_ne_top _ _) a) (U i g)) l
        (𝓝 (inner ℂ (indicatorConstLp 2 hA (measure_ne_top _ _) a) e * inner ℂ e g)) := by
    refine Lp.induction (by norm_num : (2 : ENNReal) ≠ ⊤) _ ?_ ?_ ?_
    · intro b B hB _
      exact hbase A B hA hB a b
    · intro f g hf hg _ h₁ h₂
      simpa only [map_add, inner_add_right, mul_add] using h₁.add h₂
    · exact isClosed_mixing_right U l e _
  have hall : ∀ f : Lp ℂ 2 μ, ∀ g : Lp ℂ 2 μ,
      Tendsto (fun i => inner ℂ f (U i g)) l (𝓝 (inner ℂ f e * inner ℂ e g)) := by
    refine Lp.induction (by norm_num : (2 : ENNReal) ≠ ⊤) _ ?_ ?_ ?_
    · intro a A hA _
      exact hfirst A hA a
    · intro f g hf hg _ h₁ h₂ w
      simpa only [inner_add_left, add_mul] using (h₁ w).add (h₂ w)
    · simp only [Set.ofPred_forall]
      exact isClosed_iInter (fun g => isClosed_mixing_left U l e g)
  exact hall f g

theorem inner_probabilityOne (f : Lp ℂ 2 μ) :
    inner ℂ (probabilityOne (μ := μ)) f = ∫ y, f y ∂μ := by
  rw [L2.inner_def]
  apply integral_congr_ae
  filter_upwards [indicatorConstLp_coeFn (p := 2) (hs := MeasurableSet.univ)
    (hμs := measure_ne_top μ Set.univ) (c := (1 : ℂ))] with y hy
  change inner ℂ ((indicatorConstLp 2 MeasurableSet.univ
    (measure_ne_top μ Set.univ) (1 : ℂ)) y) (f y) = f y
  rw [hy]
  simp

include ht in

theorem mixing_integral_coupling {Y : Type*} [MeasurableSpace Y]
    {η : Measure Y} [IsProbabilityMeasure η] (x : Y → Ω)
    (hx : MeasurePreserving x η μ)
    (hmix : ∀ A B : Set Ω, MeasurableSet A → MeasurableSet B →
      Tendsto (fun i => μ (A ∩ t i ⁻¹' B)) l (𝓝 (μ A * μ B)))
    {F : Ω → ℂ} (hF : MemLp F 2 μ) (hF0 : ∫ z, F z ∂μ = 0)
    {q : Y → ℂ} (hq : MemLp q 2 η) :
    Tendsto (fun i => ∫ y, F (t i (x y)) * conj (q y) ∂η) l (𝓝 0) := by
  let V := (Lp.compMeasurePreservingₗᵢ (E := ℂ) (p := 2) ℂ x hx).toContinuousLinearMap
  have hm := mixing_L2 t ht l hmix (V.adjoint (hq.toLp q)) (hF.toLp F)
  have hmean : inner ℂ (probabilityOne (μ := μ)) (hF.toLp F) = 0 := by
    rw [inner_probabilityOne]
    exact (integral_congr_ae hF.coeFn_toLp).trans hF0
  rw [hmean, mul_zero] at hm
  convert hm using 1
  funext i
  rw [ContinuousLinearMap.adjoint_inner_left, L2.inner_def]
  apply integral_congr_ae
  have h₁ := Lp.coeFn_compMeasurePreserving
    (Lp.compMeasurePreserving (t i) (ht i) (hF.toLp F)) hx
  have h₂ := hx.quasiMeasurePreserving.ae_eq_comp
    (Lp.coeFn_compMeasurePreserving (hF.toLp F) (ht i))
  have h₃ := (ht i).quasiMeasurePreserving.ae_eq_comp hF.coeFn_toLp
  have h₄ := hx.quasiMeasurePreserving.ae_eq_comp h₃
  filter_upwards [hq.coeFn_toLp, h₁, h₂, h₄] with y hy h1 h2 h4
  change F (t i (x y)) * conj (q y) =
    inner ℂ ((hq.toLp q) y)
      ((Lp.compMeasurePreserving x hx
        (Lp.compMeasurePreserving (t i) (ht i) (hF.toLp F))) y)
  rw [hy, h1, h2, h4]
  rfl

end

open Filter
open scoped BigOperators Topology InnerProductSpace

section

noncomputable def cesaro {E : Type*} [AddCommGroup E] [Module ℝ E]
    (v : ℕ → E) (N : ℕ) : E := (N : ℝ)⁻¹ • ∑ n ∈ Finset.range N, v n

section Normed
variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]

theorem norm_cesaro_le (v : ℕ → E) (N : ℕ) :
    ‖cesaro v N‖ ≤ (N : ℝ)⁻¹ * ∑ n ∈ Finset.range N, ‖v n‖ := by
  rw [cesaro, norm_smul, Real.norm_of_nonneg (by positivity : 0 ≤ (N : ℝ)⁻¹)]
  exact mul_le_mul_of_nonneg_left (norm_sum_le _ _) (by positivity)

theorem norm_cesaro_le_bound (v : ℕ → E) {C : ℝ} (hC : 0 ≤ C)
    (hv : ∀ n, ‖v n‖ ≤ C) (N : ℕ) : ‖cesaro v N‖ ≤ C := by
  by_cases hN : N = 0
  · simp [cesaro, hN, hC]
  calc
    ‖cesaro v N‖ ≤ (N : ℝ)⁻¹ * ∑ n ∈ Finset.range N, ‖v n‖ := norm_cesaro_le v N
    _ ≤ (N : ℝ)⁻¹ * ∑ _ ∈ Finset.range N, C :=
      mul_le_mul_of_nonneg_left (Finset.sum_le_sum (fun n _ => hv n)) (by positivity)
    _ = C := by simp [hN]

theorem norm_cesaro_shift_sub_le (v : ℕ → E) {C : ℝ}
    (hv : ∀ n, ‖v n‖ ≤ C) (s N : ℕ) :
    ‖cesaro (fun n => v (n + s)) N - cesaro v N‖ ≤
      (N : ℝ)⁻¹ * (2 * s * C) := by
  have heq : (∑ n ∈ Finset.range N, v (n + s)) - ∑ n ∈ Finset.range N, v n =
      (∑ n ∈ Finset.range s, v (n + N)) - ∑ n ∈ Finset.range s, v n := by
    have h₁ := Finset.sum_range_add v N s
    have h₂ := Finset.sum_range_add v s N
    rw [Nat.add_comm s N] at h₂
    simp only [Nat.add_comm] at h₁ h₂
    rw [h₁] at h₂
    apply sub_eq_sub_iff_add_eq_add.mpr
    simpa only [add_comm] using h₂.symm
  calc
    ‖cesaro (fun n => v (n + s)) N - cesaro v N‖ =
        (N : ℝ)⁻¹ * ‖(∑ n ∈ Finset.range s, v (n + N)) -
          ∑ n ∈ Finset.range s, v n‖ := by
      rw [cesaro, cesaro, ← smul_sub, heq, norm_smul,
        Real.norm_of_nonneg (by positivity : 0 ≤ (N : ℝ)⁻¹)]
    _ ≤ (N : ℝ)⁻¹ * ((∑ n ∈ Finset.range s, ‖v (n + N)‖) +
          ∑ n ∈ Finset.range s, ‖v n‖) := by
      apply mul_le_mul_of_nonneg_left _ (by positivity)
      exact (norm_sub_le _ _).trans (add_le_add (norm_sum_le _ _) (norm_sum_le _ _))
    _ ≤ (N : ℝ)⁻¹ * ((∑ _ ∈ Finset.range s, C) + ∑ _ ∈ Finset.range s, C) := by
      apply mul_le_mul_of_nonneg_left _ (by positivity)
      exact add_le_add (Finset.sum_le_sum (fun n _ => hv (n + N)))
        (Finset.sum_le_sum (fun n _ => hv n))
    _ = (N : ℝ)⁻¹ * (2 * s * C) := by
      simp only [Finset.sum_const, Finset.card_range, nsmul_eq_mul]
      ring

theorem cesaro_shift_sub_tendsto_zero (v : ℕ → E) {C : ℝ}
    (hv : ∀ n, ‖v n‖ ≤ C) (s : ℕ) :
    Tendsto (fun N => cesaro (fun n => v (n + s)) N - cesaro v N) atTop (𝓝 0) := by
  apply squeeze_zero_norm (norm_cesaro_shift_sub_le v hv s)
  simpa using (tendsto_inv_atTop_zero.comp
    (tendsto_natCast_atTop_atTop (R := ℝ))).mul_const (2 * s * C)

theorem cesaro_finset_sum {ι : Type*} (s : Finset ι) (v : ι → ℕ → E) (N : ℕ) :
    cesaro (fun n => ∑ i ∈ s, v i n) N = ∑ i ∈ s, cesaro (v i) N := by
  simp only [cesaro, Finset.smul_sum]
  rw [Finset.sum_comm]

theorem cesaro_smul (c : ℝ) (v : ℕ → E) (N : ℕ) :
    cesaro (fun n => c • v n) N = c • cesaro v N := by
  unfold cesaro
  rw [← Finset.smul_sum]
  exact smul_comm _ _ _

theorem cesaro_sub (v w : ℕ → E) (N : ℕ) :
    cesaro (fun n => v n - w n) N = cesaro v N - cesaro w N := by
  simp only [cesaro, Finset.sum_sub_distrib, smul_sub]

theorem cesaro_smoothing_sub_tendsto_zero (v : ℕ → E) {C : ℝ}
    (hv : ∀ n, ‖v n‖ ≤ C) (H : ℕ) (hH : H ≠ 0) (r : Fin H → ℕ) :
    Tendsto (fun N => cesaro (fun n => (H : ℝ)⁻¹ • ∑ a : Fin H, v (n + r a)) N -
      cesaro v N) atTop (𝓝 0) := by
  have h := (tendsto_finsetSum Finset.univ (fun (a : Fin H) _ =>
    cesaro_shift_sub_tendsto_zero v hv (r a))).const_smul (H : ℝ)⁻¹
  simp only [Finset.sum_const_zero, smul_zero] at h
  convert h using 1
  funext N
  rw [cesaro_smul, cesaro_finset_sum]
  rw [Finset.sum_sub_distrib, smul_sub, Finset.sum_const,
    Finset.card_univ, Fintype.card_fin, ← Nat.cast_smul_eq_nsmul ℝ,
    smul_smul, inv_mul_cancel₀ (Nat.cast_ne_zero.mpr hH), one_smul]

end Normed

theorem cesaro_mono {f g : ℕ → ℝ} (h : ∀ n, f n ≤ g n) (N : ℕ) :
    cesaro f N ≤ cesaro g N := by
  exact mul_le_mul_of_nonneg_left (Finset.sum_le_sum (fun n _ => h n)) (by positivity)

theorem cesaro_le_bound {f : ℕ → ℝ} {C : ℝ} (hC : 0 ≤ C)
    (h : ∀ n, f n ≤ C) (N : ℕ) : cesaro f N ≤ C := by
  by_cases hN : N = 0
  · simpa [cesaro, hN] using hC
  · exact (cesaro_mono h N).trans_eq (by simp [cesaro, hN])

variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E]

theorem norm_cesaro_sq_le (v : ℕ → E) (N : ℕ) :
    ‖cesaro v N‖ ^ 2 ≤ cesaro (fun n => ‖v n‖ ^ 2) N := by
  by_cases hN : N = 0
  · simp [cesaro, hN]
  have hn : (0 : ℝ) < N := Nat.cast_pos.mpr (Nat.pos_of_ne_zero hN)
  have hs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.range N)
    (fun n => ‖v n‖) (fun _ => (1 : ℝ))
  simp only [mul_one, one_pow, Finset.sum_const, Finset.card_range, nsmul_eq_mul,
    mul_one] at hs
  have hnorm := norm_cesaro_le v N
  have hsquare : ‖cesaro v N‖ ^ 2 ≤
      (N : ℝ)⁻¹ ^ 2 * (∑ n ∈ Finset.range N, ‖v n‖)^2 := by
    simpa only [mul_pow] using pow_le_pow_left₀ (norm_nonneg _) hnorm 2
  calc
    ‖cesaro v N‖ ^ 2 ≤ (N : ℝ)⁻¹ ^ 2 * (∑ n ∈ Finset.range N, ‖v n‖)^2 := hsquare
    _ ≤ (N : ℝ)⁻¹ ^ 2 * ((∑ n ∈ Finset.range N, ‖v n‖^2) * N) :=
      mul_le_mul_of_nonneg_left hs (by positivity)
    _ = cesaro (fun n => ‖v n‖ ^ 2) N := by
      simp only [cesaro, smul_eq_mul]
      field_simp

theorem norm_finite_mean_sq (v : ℕ → E) (H : ℕ) (r : Fin H → ℕ) (n : ℕ) :
    ‖(H : ℝ)⁻¹ • ∑ a : Fin H, v (n + r a)‖ ^ 2 =
      (H : ℝ)⁻¹ ^ 2 * ∑ a : Fin H, ∑ b : Fin H,
        inner ℝ (v (n + r a)) (v (n + r b)) := by
  rw [norm_smul, Real.norm_of_nonneg (by positivity : 0 ≤ (H : ℝ)⁻¹), mul_pow,
    ← real_inner_self_eq_norm_sq]
  simp only [sum_inner, inner_sum]
  rw [Finset.sum_comm]

theorem norm_smoothed_cesaro_sq_le (v : ℕ → E) (H N : ℕ) (r : Fin H → ℕ) :
    ‖cesaro (fun n => (H : ℝ)⁻¹ • ∑ a : Fin H, v (n + r a)) N‖ ^ 2 ≤
      (H : ℝ)⁻¹ ^ 2 * ∑ a : Fin H, ∑ b : Fin H,
        cesaro (fun n => inner ℝ (v (n + r a)) (v (n + r b))) N := by
  convert norm_cesaro_sq_le (fun n => (H : ℝ)⁻¹ • ∑ a : Fin H, v (n + r a)) N using 1
  simp_rw [norm_finite_mean_sq]
  change _ = cesaro (fun n => ((H : ℝ)⁻¹ ^ 2) • ∑ a : Fin H, ∑ b : Fin H,
    inner ℝ (v (n + r a)) (v (n + r b))) N
  rw [cesaro_smul, cesaro_finset_sum]
  simp_rw [cesaro_finset_sum, smul_eq_mul]

def LagCesaroBound (v : ℕ → E) (c : ℕ → ℝ) : Prop :=
  ∀ h : ℕ, 0 < h → ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop,
    cesaro (fun n => |inner ℝ (v n) (v (n + h))|) N ≤ c h + ε

theorem shifted_lag_cesaro_bound (v : ℕ → E) {C : ℝ} (hv : ∀ n, ‖v n‖ ≤ C)
    {c : ℕ → ℝ} (hc : LagCesaroBound v c) (s h : ℕ) (hh : 0 < h)
    (ε : ℝ) (hε : 0 < ε) : ∀ᶠ N in atTop,
    cesaro (fun n => |inner ℝ (v (n + s)) (v (n + s + h))|) N ≤ c h + ε := by
  have hC : 0 ≤ C := (norm_nonneg (v 0)).trans (hv 0)
  have hb : ∀ n, ‖|inner ℝ (v n) (v (n + h))|‖ ≤ C ^ 2 := by
    intro n
    rw [Real.norm_eq_abs, abs_abs, ← Real.norm_eq_abs]
    exact (norm_inner_le_norm _ _).trans
      (by simpa only [pow_two] using mul_le_mul (hv n) (hv (n + h)) (norm_nonneg _) hC)
  have hs := cesaro_shift_sub_tendsto_zero _ hb s
  have he := hs.eventually_lt_const (half_pos hε)
  filter_upwards [he, hc h hh (ε / 2) (half_pos hε)] with N hshift hbase
  change cesaro (fun n => |inner ℝ (v (n + s)) (v (n + s + h))|) N -
    cesaro (fun n => |inner ℝ (v n) (v (n + h))|) N < ε / 2 at hshift
  linarith

theorem pair_cesaro_bound (v : ℕ → E) {C : ℝ} (hv : ∀ n, ‖v n‖ ≤ C)
    {c : ℕ → ℝ} (hc : LagCesaroBound v c) (a b : ℕ) (hab : a ≠ b)
    (ε : ℝ) (hε : 0 < ε) : ∀ᶠ N in atTop,
    cesaro (fun n => inner ℝ (v (n + a)) (v (n + b))) N ≤ c (Nat.dist a b) + ε := by
  rcases le_total a b with hle | hle
  · have he := shifted_lag_cesaro_bound v hv hc a (b - a) (by omega) ε hε
    filter_upwards [he] with N hN
    have hsub : ∀ n, n + a + (b - a) = n + b := by omega
    simp_rw [hsub, ← Nat.dist_eq_sub_of_le hle] at hN
    exact (cesaro_mono (fun n => le_abs_self _) N).trans hN
  · have he := shifted_lag_cesaro_bound v hv hc b (a - b) (by omega) ε hε
    filter_upwards [he] with N hN
    have hsub : ∀ n, n + b + (a - b) = n + a := by omega
    simp_rw [hsub, ← Nat.dist_eq_sub_of_le_right hle] at hN
    exact (cesaro_mono (fun n => (real_inner_comm _ _).le.trans (le_abs_self _)) N).trans hN

theorem van_der_corput (v : ℕ → E) {C : ℝ} (hv : ∀ n, ‖v n‖ ≤ C)
    {c : ℕ → ℝ} (hc : LagCesaroBound v c) (hclim : Tendsto c atTop (𝓝 0)) :
    Tendsto (cesaro v) atTop (𝓝 0) := by
  apply Metric.tendsto_nhds.mpr
  intro ε hε
  have hδ : 0 < ε ^ 2 / 16 := by positivity
  have hinv : Tendsto (fun H : ℕ => (H : ℝ)⁻¹ * C ^ 2) atTop (𝓝 0) := by
    simpa using (tendsto_inv_atTop_zero.comp
      (tendsto_natCast_atTop_atTop (R := ℝ))).mul_const (C ^ 2)
  obtain ⟨H, hHpos, hHsmall⟩ :=
    ((eventually_ge_atTop 1).and (hinv.eventually_lt_const hδ)).exists
  have hH : H ≠ 0 := by omega
  have hHR : (H : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hH
  obtain ⟨L₀, hL₀⟩ := eventually_atTop.mp (hclim.eventually_lt_const (half_pos hδ))
  let L := L₀ + 1
  let r (a : Fin H) := a.val * L
  have hpairs : ∀ a b : Fin H, ∀ᶠ N in atTop,
      cesaro (fun n => inner ℝ (v (n + r a)) (v (n + r b))) N ≤
        (if a = b then C ^ 2 else 0) + ε ^ 2 / 16 := by
    intro a b
    by_cases hab : a = b
    · subst b
      apply Eventually.of_forall
      intro N
      simp only [ite_true]
      have hdiag : cesaro (fun n => inner ℝ (v (n + r a)) (v (n + r a))) N ≤ C ^ 2 := by
        apply cesaro_le_bound (sq_nonneg C)
        intro n
        rw [real_inner_self_eq_norm_sq]
        exact pow_le_pow_left₀ (norm_nonneg _) (hv _) 2
      linarith
    · have hval : a.val ≠ b.val := fun h => hab (Fin.ext h)
      have hdist : L₀ ≤ Nat.dist (r a) (r b) := by
        dsimp [r]
        rw [Nat.dist_mul_right]
        have hh : 1 ≤ Nat.dist a.val b.val := Nat.dist_pos_of_ne hval
        have hh' := Nat.mul_le_mul_right L hh
        simp only [one_mul] at hh'
        exact (by dsimp [L]; omega : L₀ ≤ L).trans hh'
      have hr : r a ≠ r b := by
        intro hh
        have hh' := Nat.eq_of_mul_eq_mul_right (by dsimp [L]; omega : 0 < L) hh
        exact hval hh'
      filter_upwards [pair_cesaro_bound v hv hc (r a) (r b) hr
        (ε ^ 2 / 16 / 2) (half_pos hδ)] with N hN
      simp only [ite_eq_right hab]
      have hh := hL₀ _ hdist
      linarith
  have hpairs' : ∀ᶠ N in atTop, ∀ a b : Fin H,
      cesaro (fun n => inner ℝ (v (n + r a)) (v (n + r b))) N ≤
        (if a = b then C ^ 2 else 0) + ε ^ 2 / 16 :=
    eventually_all.mpr (fun a => eventually_all.mpr (hpairs a))
  let w (n : ℕ) := (H : ℝ)⁻¹ • ∑ a : Fin H, v (n + r a)
  have hdiff := cesaro_smoothing_sub_tendsto_zero v hv H hH r
  have hdiff' := (Metric.tendsto_nhds.mp hdiff) (ε / 2) (half_pos hε)
  filter_upwards [hpairs', hdiff'] with N hN hdiffN
  have hbound : ‖cesaro w N‖ ^ 2 ≤ (H : ℝ)⁻¹ * C ^ 2 + ε ^ 2 / 16 := by
    calc
      ‖cesaro w N‖ ^ 2 ≤ (H : ℝ)⁻¹ ^ 2 * ∑ a : Fin H, ∑ b : Fin H,
          cesaro (fun n => inner ℝ (v (n + r a)) (v (n + r b))) N :=
        norm_smoothed_cesaro_sq_le v H N r
      _ ≤ (H : ℝ)⁻¹ ^ 2 * ∑ a : Fin H, ∑ b : Fin H,
          ((if a = b then C ^ 2 else 0) + ε ^ 2 / 16) := by
        apply mul_le_mul_of_nonneg_left _ (sq_nonneg _)
        exact Finset.sum_le_sum (fun a _ => Finset.sum_le_sum (fun b _ => hN a b))
      _ = (H : ℝ)⁻¹ * C ^ 2 + ε ^ 2 / 16 := by
        simp only [Finset.sum_add_distrib, Finset.sum_ite_eq, Finset.mem_univ, ite_true,
          Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
        field_simp
  have hw : ‖cesaro w N‖ < ε / 2 := by
    nlinarith [norm_nonneg (cesaro w N)]
  have he : ‖cesaro w N - cesaro v N‖ < ε / 2 := by
    simpa only [dist_zero_right] using hdiffN
  simp only [dist_zero_right]
  calc
    ‖cesaro v N‖ = ‖cesaro w N - (cesaro w N - cesaro v N)‖ := by
      congr 1; abel
    _ ≤ ‖cesaro w N‖ + ‖cesaro w N - cesaro v N‖ := norm_sub_le _ _
    _ < ε := by linarith

end

section

open MeasureTheory Filter
open scoped BigOperators Topology InnerProductSpace ComplexConjugate

def DifferencePolynomial {L : Type*} [AddCommGroup L] : ℕ → (ℕ → L) → Prop
  | 0, P => ∃ l, ∀ m, P m = l
  | d + 1, P => ∀ h : ℕ, 0 < h → DifferencePolynomial d (fun m => P (m + h) - P m)

namespace DifferencePolynomial
variable {L : Type*} [AddCommGroup L]

theorem const (l : L) (d : ℕ) : DifferencePolynomial d (fun _ => l) := by
  induction d generalizing l with
  | zero => exact ⟨l, fun _ => rfl⟩
  | succ d ih =>
    intro h _
    simpa only [sub_self] using ih (0 : L)

theorem add {d : ℕ} {P Q : ℕ → L} (hP : DifferencePolynomial d P)
    (hQ : DifferencePolynomial d Q) : DifferencePolynomial d (fun m => P m + Q m) := by
  induction d generalizing P Q with
  | zero =>
    obtain ⟨p, hp⟩ := hP
    obtain ⟨q, hq⟩ := hQ
    exact ⟨p + q, fun m => by simp only [hp, hq]⟩
  | succ d ih =>
    intro h hh
    have hx := ih (hP h hh) (hQ h hh)
    convert hx using 1
    funext m
    exact add_sub_add_comm _ _ _ _

theorem shift {d : ℕ} {P : ℕ → L} (hP : DifferencePolynomial d P) (s : ℕ) :
    DifferencePolynomial d (fun m => P (m + s)) := by
  induction d generalizing P with
  | zero => obtain ⟨l, hl⟩ := hP; exact ⟨l, fun m => hl (m + s)⟩
  | succ d ih =>
    intro h hh
    have hx := ih (hP h hh)
    convert hx using 1
    funext m
    simp only [Nat.add_right_comm]

theorem sum {ι : Type*} (S : Finset ι) {d : ℕ} (P : ι → ℕ → L)
    (hP : ∀ i ∈ S, DifferencePolynomial d (P i)) :
    DifferencePolynomial d (fun m => ∑ i ∈ S, P i m) := by
  classical
  induction S using Finset.induction_on with
  | empty => simpa using const (0 : L) d
  | @insert i S hi ih =>
    simp only [Finset.sum_insert hi]
    exact (hP i (Finset.mem_insert_self _ _)).add
      (ih (fun j hj => hP j (Finset.mem_insert_of_mem hj)))

theorem succ {d : ℕ} {P : ℕ → L} (hP : DifferencePolynomial d P) :
    DifferencePolynomial (d + 1) P := by
  induction d generalizing P with
  | zero =>
    obtain ⟨l, hl⟩ := hP
    have heq : P = fun _ => l := funext hl
    rw [heq]
    exact const l 1
  | succ d ih => exact fun h hh => ih (hP h hh)

theorem mono {d e : ℕ} (hde : d ≤ e) {P : ℕ → L} (hP : DifferencePolynomial d P) :
    DifferencePolynomial e P := by
  induction e, hde using Nat.le_induction with
  | base => exact hP
  | succ e _ ih => exact ih.succ

theorem of_forward_difference {d : ℕ} {P : ℕ → L}
    (hP : DifferencePolynomial d (fun m => P (m + 1) - P m)) :
    DifferencePolynomial (d + 1) P := by
  intro h hh
  clear hh
  have hs := sum (Finset.range h) (fun i m => P (m + i + 1) - P (m + i))
    (fun i _ => hP.shift i)
  have heq (m : ℕ) : (∑ i ∈ Finset.range h, (P (m + i + 1) - P (m + i))) =
      P (m + h) - P m := by
    clear hs
    induction h with
    | zero => simp
    | succ h ih =>
      rw [Finset.sum_range_succ, ih]
      simp only [Nat.add_assoc]
      abel
  simpa only [heq] using hs

theorem choose_nsmul (a : ℕ) (l : L) :
    DifferencePolynomial a (fun m => m.choose a • l) := by
  induction a with
  | zero => simpa using const l 0
  | succ a ih =>
    apply of_forward_difference
    convert ih using 1
    funext m
    rw [Nat.choose_succ_succ, add_nsmul]
    abel

theorem binomial (d : ℕ) (l : ℕ → L) :
    DifferencePolynomial d (fun m => ∑ a ∈ Finset.range (d + 1), m.choose a • l a) := by
  apply sum
  intro a ha
  exact (choose_nsmul a (l a)).mono (by have := Finset.mem_range.mp ha; omega)

end DifferencePolynomial

section Bounded
variable {Y : Type*} [MeasurableSpace Y] {η : Measure Y} [IsProbabilityMeasure η]

theorem norm_toLp_le_bound {f : Y → ℂ} (hf : MemLp f 2 η) {C : ℝ}
    (hC : 0 ≤ C) (hb : ∀ᵐ y ∂η, ‖f y‖ ≤ C) : ‖hf.toLp f‖ ≤ C := by
  have hb' : ∀ᵐ y ∂η, ‖hf.toLp f y‖ ≤ C := by
    filter_upwards [hf.coeFn_toLp, hb] with y hy hb
    simpa only [hy] using hb
  simpa [measureUnivNNReal] using Lp.norm_le_of_ae_bound hC hb'
end Bounded

namespace ProjectiveCharacters
variable {Y L : Type*} [MeasurableSpace Y] [AddCommGroup L]
    {η : Measure Y} [IsProbabilityMeasure η] {χ : L → Y → ℂ}
    (hχ : ProjectiveCharacters η χ)
include hχ

omit [IsProbabilityMeasure η] in

theorem mul_conj (l m : L) : ∃ c : ℂ, ‖c‖ = 1 ∧
    (fun y => χ l y * conj (χ m y)) =ᵐ[η] (fun y => c * χ (l - m) y) := by
  obtain ⟨c, hc, hcon⟩ := hχ.conjugate m
  obtain ⟨d, hd, hmul⟩ := hχ.mul l (-m)
  refine ⟨c * d, by simp [hc, hd], ?_⟩
  filter_upwards [hcon, hmul] with y hy hz
  rw [hy]
  calc
    χ l y * (c * χ (-m) y) = c * (χ l y * χ (-m) y) := by ring
    _ = c * (d * χ (l + -m) y) := by rw [hz]
    _ = (c * d) * χ (l - m) y := by simp only [sub_eq_add_neg]; ring

theorem norm_integral_conj_le_one (l : L) : ‖∫ y, conj (χ l y) ∂η‖ ≤ 1 := by
  have hb : ∀ᵐ y ∂η, ‖conj (χ l y)‖ ≤ 1 := by
    filter_upwards [hχ.modulus l] with y hy
    simpa using hy.le
  simpa using norm_integral_le_of_norm_le_const hb
end ProjectiveCharacters

theorem l2_real_inner_eq_re_inner {Y : Type*} [MeasurableSpace Y] {η : Measure Y}
    (f g : Lp ℂ 2 η) : inner ℝ f g = (inner ℂ f g).re := by
  rw [L2.inner_def, L2.inner_def]
  simp_rw [real_inner_eq_re_inner ℂ]
  exact integral_re (L2.integrable_inner (𝕜 := ℂ) f g)

variable {X Y L : Type*} [MeasurableSpace X] [MeasurableSpace Y] [AddCommGroup L]
    {μ : Measure X} [IsProbabilityMeasure μ]
    {η : Measure Y} [IsProbabilityMeasure η]
    (x : Y → X) (hx : MeasurePreserving x η μ)
    (t : ℕ → X → X) (ht : ∀ m, MeasurePreserving (t m) μ μ)
    {χ : L → Y → ℂ} (hχ : ProjectiveCharacters η χ)

omit [IsProbabilityMeasure μ] in
include hx ht hχ in

theorem phased_memLp {F : X → ℂ} (hFm : AEStronglyMeasurable F μ)
    {C : ℝ} (hFb : ∀ᵐ z ∂μ, ‖F z‖ ≤ C) (P : ℕ → L)
    (ω : ℕ → ℂ) (hω : ∀ m, ‖ω m‖ = 1) (m : ℕ) :
    MemLp (fun y => ω m * F (t m (x y)) * conj (χ (P m) y)) 2 η := by
  apply MemLp.of_bound
    (((hFm.comp_measurePreserving ((ht m).comp hx)).const_mul _).mul
      (hχ.measurable _).star) C
  filter_upwards [((ht m).comp hx).quasiMeasurePreserving.ae hFb,
    hχ.modulus (P m)] with y hy hz
  change ‖ω m * F (t m (x y)) * conj (χ (P m) y)‖ ≤ C
  simpa only [norm_mul, Complex.norm_conj, hω, hz, one_mul, mul_one, Function.comp_def] using hy

omit [MeasurableSpace X] [IsProbabilityMeasure η] in
include hχ in

theorem phased_lag_norm {F : X → ℂ} (P : ℕ → L) (ω : ℕ → ℂ)
    (hω : ∀ m, ‖ω m‖ = 1) (m h : ℕ)
    (htadd : ∀ a b z, t (a + b) z = t b (t a z))
    (hf : ∀ m, MemLp (fun y => ω m * F (t m (x y)) * conj (χ (P m) y)) 2 η) :
    ‖inner ℂ ((hf m).toLp _) ((hf (m + h)).toLp _)‖ =
      ‖∫ y, (F (t h (t m (x y))) * conj (F (t m (x y)))) *
        conj (χ (P (m + h) - P m) y) ∂η‖ := by
  obtain ⟨c, hc, hm⟩ := hχ.mul_conj (P (m + h)) (P m)
  rw [L2.inner_def]
  have heq : (fun y => inner ℂ (((hf m).toLp _) y) (((hf (m + h)).toLp _) y)) =ᵐ[η]
      (fun y => (ω (m + h) * conj (ω m) * conj c) *
        ((F (t h (t m (x y))) * conj (F (t m (x y)))) *
          conj (χ (P (m + h) - P m) y))) := by
    filter_upwards [(hf m).coeFn_toLp, (hf (m + h)).coeFn_toLp, hm] with y hy hz hm
    rw [hy, hz, RCLike.inner_apply, map_mul, map_mul, starRingEnd_self_apply,
      htadd m h]
    have hm' := congrArg conj hm
    simp only [map_mul, starRingEnd_self_apply] at hm'
    calc
      _ = (ω (m + h) * conj (ω m)) *
        (F (t h (t m (x y))) * conj (F (t m (x y)))) *
        (conj (χ (P (m + h)) y) * χ (P m) y) := by ring
      _ = _ := by rw [hm']; ring
  rw [integral_congr_ae heq, integral_const_mul, norm_mul]
  simp [hω, hc]

include hx ht hχ in

theorem polynomial_cancellation
    (htadd : ∀ a b z, t (a + b) z = t b (t a z))
    (hmix : ∀ A B : Set X, MeasurableSet A → MeasurableSet B →
      Tendsto (fun m => μ (A ∩ t m ⁻¹' B)) atTop (𝓝 (μ A * μ B)))
    (d : ℕ) (P : ℕ → L) (hP : DifferencePolynomial d P)
    {F : X → ℂ} (hFm : AEStronglyMeasurable F μ)
    {C : ℝ} (hC : 0 ≤ C) (hFb : ∀ᵐ z ∂μ, ‖F z‖ ≤ C)
    (hF0 : ∫ z, F z ∂μ = 0) :
    Tendsto (fun N : ℕ => (N : ℝ)⁻¹ * ∑ m ∈ Finset.range N,
      ‖∫ y, F (t m (x y)) * conj (χ (P m) y) ∂η‖) atTop (𝓝 0) := by
  induction d generalizing P F C with
  | zero =>
    obtain ⟨l, hl⟩ := hP
    have hF := MemLp.of_bound (p := 2) hFm C hFb
    have hq := MemLp.of_bound (p := 2) (hχ.measurable l) 1
      ((hχ.modulus l).mono (fun _ h => h.le))
    have hm := mixing_integral_coupling t ht atTop x hx hmix hF hF0 hq
    simpa only [hl, norm_zero] using hm.norm.cesaro
  | succ d ih =>
    choose ω hω hw using fun m =>
      exists_aligning_phase (∫ y, F (t m (x y)) * conj (χ (P m) y) ∂η)
    let q (m : ℕ) (y : Y) := ω m * F (t m (x y)) * conj (χ (P m) y)
    have hq (m : ℕ) : MemLp (q m) 2 η := phased_memLp x hx t ht hχ hFm hFb P ω hω m
    let v (m : ℕ) : Lp ℂ 2 η := (hq m).toLp (q m)
    have hv (m : ℕ) : ‖v m‖ ≤ C := by
      apply norm_toLp_le_bound (hq m) hC
      filter_upwards [((ht m).comp hx).quasiMeasurePreserving.ae hFb,
        hχ.modulus (P m)] with y hy hz
      simpa only [q, norm_mul, Complex.norm_conj, hω, hz, one_mul, mul_one, Function.comp_def] using hy
    let c (h : ℕ) := ‖∫ z, F (t h z) * conj (F z) ∂μ‖
    have hclim : Tendsto c atTop (𝓝 0) := by
      have hF := MemLp.of_bound (p := 2) hFm C hFb
      have hm := mixing_integral_coupling t ht atTop id (MeasurePreserving.id μ)
        hmix hF hF0 hF
      simpa only [c, id_eq, norm_zero] using hm.norm
    have hlag : LagCesaroBound v c := by
      intro h hh ε hε
      let H (z : X) := F (t h z) * conj (F z)
      have hHm : AEStronglyMeasurable H μ :=
        (hFm.comp_measurePreserving (ht h)).mul hFm.star
      have hHb : ∀ᵐ z ∂μ, ‖H z‖ ≤ C ^ 2 := by
        filter_upwards [(ht h).quasiMeasurePreserving.ae hFb, hFb] with z hz hf
        dsimp [H]
        rw [norm_mul, Complex.norm_conj, pow_two]
        exact mul_le_mul hz hf (norm_nonneg _) hC
      have hHi : Integrable H μ := (MemLp.of_bound (p := 1) hHm (C ^ 2) hHb).integrable le_rfl
      let a : ℂ := ∫ z, H z ∂μ
      let G (z : X) := H z - a
      have hGm : AEStronglyMeasurable G μ := hHm.sub aestronglyMeasurable_const
      have hGb : ∀ᵐ z ∂μ, ‖G z‖ ≤ C ^ 2 + ‖a‖ := by
        filter_upwards [hHb] with z hz
        exact (norm_sub_le _ _).trans (add_le_add hz le_rfl)
      have hG0 : ∫ z, G z ∂μ = 0 := by
        dsimp [G]
        rw [integral_sub hHi (integrable_const a)]
        simp [a]
      let D (m : ℕ) := P (m + h) - P m
      have hGc := ih D (hP h hh) hGm (by positivity : 0 ≤ C ^ 2 + ‖a‖) hGb hG0
      let b (m : ℕ) := ‖∫ y, G (t m (x y)) * conj (χ (D m) y) ∂η‖
      have hbound (m : ℕ) : |inner ℝ (v m) (v (m + h))| ≤ b m + c h := by
        have hreal : |inner ℝ (v m) (v (m + h))| ≤
            ‖inner ℂ (v m) (v (m + h))‖ := by
          rw [l2_real_inner_eq_re_inner]
          exact Complex.abs_re_le_norm _
        have heq := phased_lag_norm x t hχ P ω hω m h htadd hq
        change ‖inner ℂ (v m) (v (m + h))‖ = _ at heq
        rw [heq] at hreal
        refine hreal.trans ?_
        have hGi : Integrable (fun y => G (t m (x y)) * conj (χ (D m) y)) η := by
          have hhq := phased_memLp x hx t ht hχ hGm hGb D (fun _ => 1)
            (fun _ => norm_one) m
          simpa only [one_mul] using hhq.integrable (by norm_num : (1 : ENNReal) ≤ 2)
        have hei : Integrable (fun y => a * conj (χ (D m) y)) η :=
          ((MemLp.of_bound (p := 1) (hχ.measurable _).star 1
            ((hχ.modulus (D m)).mono (fun y hy => by simpa only [Pi.star_apply, norm_star] using hy.le))).integrable le_rfl).const_mul a
        have hi : (∫ y, H (t m (x y)) * conj (χ (D m) y) ∂η) =
            (∫ y, G (t m (x y)) * conj (χ (D m) y) ∂η) +
              a * (∫ y, conj (χ (D m) y) ∂η) := by
          rw [← integral_const_mul, ← integral_add hGi hei]
          apply integral_congr_ae
          exact Eventually.of_forall (fun y => by dsimp [G]; ring)
        change ‖∫ y, H (t m (x y)) * conj (χ (D m) y) ∂η‖ ≤ _
        rw [hi]
        calc
          _ ≤ b m + ‖a * ∫ y, conj (χ (D m) y) ∂η‖ := norm_add_le _ _
          _ ≤ b m + ‖a‖ := by
            gcongr
            rw [norm_mul]
            exact (mul_le_mul_of_nonneg_left (hχ.norm_integral_conj_le_one _) (norm_nonneg a)).trans_eq
              (mul_one _)
          _ = b m + c h := rfl
      filter_upwards [hGc.eventually_lt_const hε, eventually_gt_atTop 0] with N hN hN0
      have hNne : (N : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hN0)
      change cesaro (fun m => |inner ℝ (v m) (v (m + h))|) N ≤ c h + ε
      calc
        _ ≤ cesaro (fun m => b m + c h) N := cesaro_mono hbound N
        _ = cesaro b N + c h := by
          simp [cesaro, Finset.sum_add_distrib, mul_add, hNne]
        _ ≤ c h + ε := by change (N : ℝ)⁻¹ * ∑ m ∈ Finset.range N, b m < ε at hN
                          change (N : ℝ)⁻¹ * ∑ m ∈ Finset.range N, b m + c h ≤ c h + ε
                          linarith
    have hc := van_der_corput v hv hlag hclim
    have hcont : Continuous (fun w : Lp ℂ 2 η =>
        inner ℝ (probabilityOne (μ := η)) w) := by fun_prop
    have he (m : ℕ) : inner ℝ (probabilityOne (μ := η)) (v m) =
        ‖∫ y, F (t m (x y)) * conj (χ (P m) y) ∂η‖ := by
      rw [l2_real_inner_eq_re_inner, inner_probabilityOne]
      have hqi : (∫ y, v m y ∂η) = ∫ y, q m y ∂η := integral_congr_ae (hq m).coeFn_toLp
      rw [hqi]
      change (∫ y, ω m * F (t m (x y)) * conj (χ (P m) y) ∂η).re = _
      simp_rw [mul_assoc]
      rw [integral_const_mul]
      exact hw m
    have hi' : Tendsto (fun N => inner ℝ (probabilityOne (μ := η)) (cesaro v N)) atTop (𝓝 0) := by
      simpa only [Function.comp_def, inner_zero_right] using (hcont.tendsto 0).comp hc
    convert hi' using 1
    funext N
    simp only [cesaro, inner_smul_right, inner_sum, he]

include hx ht hχ in

theorem binomial_cancellation
    (htadd : ∀ a b z, t (a + b) z = t b (t a z))
    (hmix : ∀ A B : Set X, MeasurableSet A → MeasurableSet B →
      Tendsto (fun m => μ (A ∩ t m ⁻¹' B)) atTop (𝓝 (μ A * μ B)))
    (d : ℕ) (l : ℕ → L)
    {F : X → ℂ} (hFm : AEStronglyMeasurable F μ)
    {C : ℝ} (hC : 0 ≤ C) (hFb : ∀ᵐ z ∂μ, ‖F z‖ ≤ C)
    (hF0 : ∫ z, F z ∂μ = 0) :
    Tendsto (fun N : ℕ => (N : ℝ)⁻¹ * ∑ m ∈ Finset.range N,
      ‖∫ y, F (t m (x y)) *
        conj (χ (∑ a ∈ Finset.range (d + 1), m.choose a • l a) y) ∂η‖)
      atTop (𝓝 0) :=
  polynomial_cancellation x hx t ht hχ htadd hmix d _
    (DifferencePolynomial.binomial d l) hFm hC hFb hF0

end

open scoped BigOperators
open Polynomial
section

theorem monic_mahlerMeasure_eq_one (p : ℤ[X]) (hp : p.Monic)
    (hroots : ∀ z ∈ p.aroots ℂ, ‖z‖ ≤ 1) :
    (p.map (Int.castRingHom ℂ)).mahlerMeasure = 1 := by
  rw [Polynomial.mahlerMeasure_eq_leadingCoeff_mul_prod_roots]
  rw [(hp.map _).leadingCoeff, norm_one, one_mul]
  apply Multiset.prod_eq_one
  intro r hr
  obtain ⟨z, hz, rfl⟩ := Multiset.mem_map.mp hr
  exact max_eq_left (hroots z hz)

theorem integer_polynomial_dvd_cyclotomic_power (p : ℤ[X]) (hp : p.Monic)
    (hzero : ∀ z ∈ p.aroots ℂ, z ≠ 0)
    (hroots : ∀ z ∈ p.aroots ℂ, ‖z‖ ≤ 1) :
    ∃ N d : ℕ, 0 < N ∧ 0 < d ∧ p ∣ (X ^ N - 1) ^ d := by
  classical
  let f := p.map (Int.castRingHom ℂ)
  let s := f.roots.toFinset
  have hmahler := monic_mahlerMeasure_eq_one p hp hroots
  have horders (z : s) : ∃ n : ℕ, 0 < n ∧ (z.val : ℂ) ^ n = 1 := by
    have hz : z.val ∈ p.aroots ℂ := Multiset.mem_toFinset.mp z.property
    exact Polynomial.pow_eq_one_of_mahlerMeasure_eq_one hmahler (hzero _ hz) hz
  choose n hnpos hn using horders
  let N := ∏ z : s, n z
  have hN : 0 < N := Finset.prod_pos (fun _ _ => hnpos _)
  have hpow : ∀ z ∈ f.roots, z ^ N = 1 := by
    intro z hz
    let w : s := ⟨z, Multiset.mem_toFinset.mpr hz⟩
    have hd : n w ∣ N := Finset.dvd_prod_of_mem n (Finset.mem_univ w)
    obtain ⟨a, ha⟩ := hd
    rw [ha, pow_mul, hn w, one_pow]
  let Q : ℂ[X] := X ^ N - 1
  have hQ : Q ≠ 0 := by
    intro hh
    have he := congrArg (eval (0 : ℂ)) hh
    simp [Q, hN.ne'] at he
  have hQroots : ∀ z ∈ f.roots, z ∈ Q.roots := by
    intro z hz
    apply (mem_roots hQ).mpr
    simp [IsRoot.def, Q, hpow z hz]
  let d := f.roots.card + 1
  have hd : 0 < d := Nat.succ_pos _
  have hmult : f.roots ≤ (Q ^ d).roots := by
    rw [roots_pow]
    apply Multiset.le_iff_count.mpr
    intro z
    rw [Multiset.count_nsmul]
    by_cases hz : z ∈ f.roots
    · have hc : 0 < Q.roots.count z := Multiset.count_pos.mpr (hQroots z hz)
      calc
        f.roots.count z ≤ f.roots.card := Multiset.count_le_card _ _
        _ ≤ d := Nat.le_succ _
        _ ≤ d * Q.roots.count z := Nat.le_mul_of_pos_right d hc
    · simp [Multiset.count_eq_zero.mpr hz]
  have hf0 : f ≠ 0 := (hp.map _).ne_zero
  have hdivC : f ∣ Q ^ d :=
    ((IsAlgClosed.splits f).dvd_iff_roots_le_roots hf0 (pow_ne_zero d hQ)).mpr hmult
  refine ⟨N, d, hN, hd, ?_⟩
  apply (Polynomial.map_dvd_map (Int.castRingHom ℂ) (Int.castRingHom ℂ).injective_int hp).mp
  simpa [f, Q] using hdivC

theorem quasiUnipotent_of_integer_annihilator {A : Type*} [Ring A] [Algebra ℤ A]
    (a : A) (p : ℤ[X]) (hp : p.Monic) (hann : aeval a p = 0)
    (hzero : ∀ z ∈ p.aroots ℂ, z ≠ 0)
    (hroots : ∀ z ∈ p.aroots ℂ, ‖z‖ ≤ 1) :
    ∃ N d : ℕ, 0 < N ∧ 0 < d ∧ (a ^ N - 1) ^ d = 0 := by
  obtain ⟨N, d, hN, hd, hdiv⟩ := integer_polynomial_dvd_cyclotomic_power p hp hzero hroots
  refine ⟨N, d, hN, hd, ?_⟩
  have hh := Polynomial.aeval_eq_zero_of_dvd_aeval_eq_zero hdiv hann
  simpa using hh

section Lattice
variable {R M : Type*} [CommRing R] [AddCommGroup M] [Module R M]
  [Module.Free R M] [Module.Finite R M]

lemma charpoly_dual (f : M →ₗ[R] M) : f.dualMap.charpoly = f.charpoly := by
  classical
  let b := Module.Free.chooseBasis R M
  have hm : LinearMap.toMatrix b.dualBasis b.dualBasis f.dualMap =
      (LinearMap.toMatrix b b f).transpose := by
    ext i j
    simp [LinearMap.toMatrix_apply, Module.Basis.dualBasis_repr,
      Matrix.transpose_apply]
  rw [← f.dualMap.charpoly_toMatrix b.dualBasis, hm, Matrix.charpoly_transpose,
    f.charpoly_toMatrix b]

end Lattice

section Torsion
variable {M : Type*} [AddCommGroup M] (G : M ≃ₗ[ℤ] M)

lemma map_mem_torsion {x : M} (hx : x ∈ Submodule.torsion ℤ M) :
    G x ∈ Submodule.torsion ℤ M := by
  obtain ⟨a, ha⟩ := (Submodule.mem_torsion_iff x).mp hx
  apply (Submodule.mem_torsion_iff (G x)).mpr
  refine ⟨a, ?_⟩
  change (a : ℤ) • x = 0 at ha
  change (a : ℤ) • G x = 0
  simpa only [map_smul, map_zero] using congrArg G ha

lemma torsion_map_equiv : (Submodule.torsion ℤ M).map G.toLinearMap =
    Submodule.torsion ℤ M := by
  ext x
  constructor
  · rintro ⟨y, hy, rfl⟩
    exact map_mem_torsion G hy
  · intro hx
    exact ⟨G.symm x, map_mem_torsion G.symm hx, G.apply_symm_apply x⟩

noncomputable def torsionQuotEquiv : (M ⧸ Submodule.torsion ℤ M) ≃ₗ[ℤ]
    (M ⧸ Submodule.torsion ℤ M) :=
  Submodule.Quotient.equiv _ _ G (torsion_map_equiv G)

@[simp] lemma torsionQuotEquiv_mk (x : M) :
    torsionQuotEquiv G ((Submodule.torsion ℤ M).mkQ x) =
      (Submodule.torsion ℤ M).mkQ (G x) := rfl

noncomputable def torsionRestrictEquiv : (Submodule.torsion ℤ M) ≃ₗ[ℤ]
    (Submodule.torsion ℤ M) where
  toFun x := ⟨G x, map_mem_torsion G x.property⟩
  invFun x := ⟨G.symm x, map_mem_torsion G.symm x.property⟩
  left_inv x := by ext; exact G.symm_apply_apply x
  right_inv x := by ext; exact G.apply_symm_apply x
  map_add' x y := by ext; exact map_add G _ _
  map_smul' a x := by ext; exact map_smul G a (x : M)

lemma torsionRestrictEquiv_pow (n : ℕ) (x : Submodule.torsion ℤ M) :
    ((torsionRestrictEquiv G ^ n) x : M) = (G ^ n) x := by
  induction n with
  | zero => rfl
  | succ n ih =>
    simp only [pow_succ', LinearEquiv.mul_apply]
    change G ((torsionRestrictEquiv G ^ n) x : M) = _
    rw [ih]

lemma torsion_period [Module.Finite ℤ M] :
    ∃ n : ℕ, 0 < n ∧ ∀ x ∈ Submodule.torsion ℤ M, (G ^ n) x = x := by
  classical
  have : Finite (Submodule.torsion ℤ M) :=
    Module.finite_of_fg_torsion _ (Submodule.torsion_isTorsion)
  have : Finite ((Submodule.torsion ℤ M) ≃ₗ[ℤ] (Submodule.torsion ℤ M)) :=
    Finite.of_injective (fun f => (f : (Submodule.torsion ℤ M) → (Submodule.torsion ℤ M)))
      DFunLike.coe_injective
  let H := torsionRestrictEquiv G
  refine ⟨orderOf H, orderOf_pos H, ?_⟩
  intro x hx
  have hh := congrArg (fun f : (Submodule.torsion ℤ M) ≃ₗ[ℤ]
      (Submodule.torsion ℤ M) => ((f ⟨x, hx⟩ : Submodule.torsion ℤ M) : M))
      (pow_orderOf_eq_one H)
  change ((torsionRestrictEquiv G ^ orderOf H) ⟨x, hx⟩ : M) = x at hh
  rw [torsionRestrictEquiv_pow] at hh
  exact hh

end Torsion

section CyclicLattice
open scoped TensorProduct
variable {M : Type*} [AddCommGroup M] (G : M ≃ₗ[ℤ] M) (l : M)

lemma eigenfunctional_generator_ne_zero
    (hspan : Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l) = ⊤)
    (φ : M →+ ℂ) (hφ : φ ≠ 0) (ζ : ℂ) (hζ : ζ ≠ 0)
    (heigen : ∀ x, φ (G x) = ζ * φ x) : φ l ≠ 0 := by
  intro hl
  have horbit (n : ℤ) : φ ((G ^ n) l) = 0 := by
    induction n using Int.induction_on with
    | zero => simpa using hl
    | succ n ih =>
      rw [add_comm (n : ℤ), zpow_add, zpow_one, LinearEquiv.mul_apply, heigen, ih, mul_zero]
    | pred n ih =>
      have heq : G * G ^ (-(n : ℤ) - 1) = G ^ (-(n : ℤ)) := by
        calc
          G * G ^ (-(n : ℤ) - 1) = G ^ (1 : ℤ) * G ^ (-(n : ℤ) - 1) := by rw [zpow_one]
          _ = G ^ (1 + (-(n : ℤ) - 1)) := by rw [zpow_add]
          _ = G ^ (-(n : ℤ)) := by congr 1; omega
      have hh := heigen ((G ^ (-(n : ℤ) - 1)) l)
      rw [← LinearEquiv.mul_apply, heq, ih] at hh
      exact (mul_eq_zero.mp hh.symm).resolve_left hζ
  have hker : Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l) ≤
      φ.toIntLinearMap.ker := by
    apply Submodule.span_le.mpr
    rintro _ ⟨n, rfl⟩
    exact horbit n
  rw [hspan] at hker
  exact hφ (by ext x; exact hker (Submodule.mem_top : x ∈ (⊤ : Submodule ℤ M)))

variable [Module.Free ℤ M] [Module.Finite ℤ M]

theorem lattice_orbit_alternative
    (hspan : Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l) = ⊤) :
    (∃ (φ : M →+ ℂ) (ζ : ℂ), φ l ≠ 0 ∧ 1 < ‖ζ‖ ∧
      ∀ x, φ (G x) = ζ * φ x) ∨
    (∃ N d : ℕ, 0 < N ∧ 0 < d ∧ (G.toLinearMap ^ N - 1) ^ d = 0) := by
  classical
  let V := ℂ ⊗[ℤ] M
  let H : V ≃ₗ[ℂ] V := G.baseChange ℤ ℂ M M
  let p := G.toLinearMap.charpoly
  have hp : p.Monic := G.toLinearMap.charpoly_monic
  have hchar : H.toLinearMap.charpoly = p.map (Int.castRingHom ℂ) := by
    exact G.toLinearMap.charpoly_baseChange ℂ
  have hzero : ∀ ζ ∈ p.aroots ℂ, ζ ≠ 0 := by
    intro ζ hζ hz
    have hr : H.toLinearMap.charpoly.IsRoot ζ := by
      rw [hchar]
      exact (Polynomial.mem_roots (hp.map _).ne_zero).mp hζ
    have he := (Module.End.hasEigenvalue_iff_isRoot_charpoly H.toLinearMap ζ).mpr hr
    obtain ⟨v, hv, hv0⟩ := he.exists_hasEigenvector
    have hh : H v = 0 := by simpa [hz] using Module.End.mem_eigenspace_iff.mp hv
    exact hv0 (H.injective (hh.trans (map_zero H).symm))
  by_cases hex : ∃ ζ ∈ p.aroots ℂ, 1 < ‖ζ‖
  · obtain ⟨ζ, hroot, hζ⟩ := hex
    have hr : H.toLinearMap.dualMap.charpoly.IsRoot ζ := by
      rw [charpoly_dual, hchar]
      exact (Polynomial.mem_roots (hp.map _).ne_zero).mp hroot
    have he := (Module.End.hasEigenvalue_iff_isRoot_charpoly H.toLinearMap.dualMap ζ).mpr hr
    obtain ⟨F, hF⟩ := he.exists_hasEigenvector
    let φ : M →+ ℂ := F.toAddMonoidHom.comp
      (TensorProduct.mk ℤ ℂ M (1 : ℂ)).toAddMonoidHom
    have hφapply (x : M) : φ x = F ((1 : ℂ) ⊗ₜ[ℤ] x) := rfl
    have hφ0 : φ ≠ 0 := by
      intro hh
      apply hF.2
      apply LinearMap.ext
      intro v
      change F v = 0
      induction v using TensorProduct.inductionOn with
      | tmul a x =>
        have hFx : F ((1 : ℂ) ⊗ₜ[ℤ] x) = 0 := by
          change φ x = 0
          simp only [hh, AddMonoidHom.zero_apply]
        rw [show a ⊗ₜ[ℤ] x = a • ((1 : ℂ) ⊗ₜ[ℤ] x) by
          rw [TensorProduct.smul_tmul']; simp, map_smul, hFx, smul_zero]
      | add v w hv hw => rw [map_add, hv, hw, add_zero]
    have heigen (x : M) : φ (G x) = ζ * φ x := by
      have hh := congrArg (fun f : Module.Dual ℂ V => f ((1 : ℂ) ⊗ₜ[ℤ] x))
        hF.apply_eq_smul
      change F (H ((1 : ℂ) ⊗ₜ[ℤ] x)) = ζ * F ((1 : ℂ) ⊗ₜ[ℤ] x) at hh
      exact hh
    exact Or.inl ⟨φ, ζ, eigenfunctional_generator_ne_zero G l hspan φ hφ0 ζ
      (hzero ζ hroot) heigen, hζ, heigen⟩
  · right
    apply quasiUnipotent_of_integer_annihilator G.toLinearMap p hp
      G.toLinearMap.aeval_self_charpoly hzero
    intro ζ hζ
    exact le_of_not_gt (fun hh => hex ⟨ζ, hζ, hh⟩)

end CyclicLattice

lemma nilpotent_pow_sub_one {A : Type*} [Ring A] [Algebra ℤ A]
    (a : A) (d q : ℕ) (h : (a - 1) ^ d = 0) : (a ^ q - 1) ^ d = 0 := by
  have hdiv : ((X : ℤ[X]) - 1) ^ d ∣ (X ^ q - 1) ^ d :=
    pow_dvd_pow_of_dvd (sub_one_dvd_pow_sub_one X q) d
  have hh := Polynomial.aeval_eq_zero_of_dvd_aeval_eq_zero hdiv
    (show aeval a (((X : ℤ[X]) - 1) ^ d) = 0 by simpa using h)
  simpa using hh

lemma linear_semiconj_pow {R M N : Type*} [Semiring R]
    [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N]
    (q : M →ₗ[R] N) (a : Module.End R M) (b : Module.End R N)
    (h : ∀ x, q (a x) = b (q x)) (n : ℕ) (x : M) :
    q ((a ^ n) x) = (b ^ n) (q x) := by
  induction n with
  | zero => rfl
  | succ n ih => simp only [pow_succ', Module.End.mul_apply, h, ih]

variable {M : Type*} [AddCommGroup M] (G : M ≃ₗ[ℤ] M)

lemma torsionQuotEquiv_zpow_mk (n : ℤ) (x : M) :
    (torsionQuotEquiv G ^ n) ((Submodule.torsion ℤ M).mkQ x) =
      (Submodule.torsion ℤ M).mkQ ((G ^ n) x) := by
  induction n using Int.induction_on generalizing x with
  | zero => rfl
  | succ n ih =>
    simp only [zpow_add, zpow_one, LinearEquiv.mul_apply]
    exact ih (x := G x)
  | pred n ih =>
    simp only [zpow_sub, zpow_one, LinearEquiv.mul_apply]
    exact ih (x := G.symm x)

lemma torsionQuot_cyclic (l : M)
    (hspan : Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l) = ⊤) :
    Submodule.span ℤ (Set.range fun n : ℤ =>
      (torsionQuotEquiv G ^ n) ((Submodule.torsion ℤ M).mkQ l)) = ⊤ := by
  let q := (Submodule.torsion ℤ M).mkQ
  have hrange : (Set.range fun n : ℤ => (torsionQuotEquiv G ^ n) (q l)) =
      q '' (Set.range fun n : ℤ => (G ^ n) l) := by
    rw [← Set.range_comp]
    congr 1
    funext n
    exact torsionQuotEquiv_zpow_mk G n l
  rw [hrange, ← Submodule.map_span, hspan, Submodule.map_top]
  exact LinearMap.range_eq_top.mpr (Submodule.mkQ_surjective _)

theorem quasiUnipotent_of_torsionQuot [Module.Finite ℤ M] (N d : ℕ)
    (hN : 0 < N) (_hd : 0 < d)
    (hquot : ((torsionQuotEquiv G).toLinearMap ^ N - 1) ^ d = 0) :
    ∃ p e : ℕ, 0 < p ∧ 0 < e ∧ (G.toLinearMap ^ p - 1) ^ e = 0 := by
  obtain ⟨q, hq, hper⟩ := torsion_period G
  let p := N * q
  have hp : 0 < p := Nat.mul_pos hN hq
  have hquot' : ((torsionQuotEquiv G).toLinearMap ^ p - 1) ^ d = 0 := by
    simpa [p, ← pow_mul] using
      nilpotent_pow_sub_one ((torsionQuotEquiv G).toLinearMap ^ N) d q hquot
  have hper' (x : M) (hx : x ∈ Submodule.torsion ℤ M) : (G ^ p) x = x := by
    change (G ^ (N * q)) x = x
    rw [Nat.mul_comm N q, pow_mul]
    have hfix : ∀ n : ℕ, ((G ^ q) ^ n) x = x := by
      intro n
      induction n with
      | zero => rfl
      | succ n ih => simp only [pow_succ', LinearEquiv.mul_apply, ih, hper x hx]
    exact hfix N
  let π := (Submodule.torsion ℤ M).mkQ
  have hpow (n : ℕ) (x : M) : π ((G.toLinearMap ^ n) x) =
      ((torsionQuotEquiv G).toLinearMap ^ n) (π x) :=
    linear_semiconj_pow π G.toLinearMap (torsionQuotEquiv G).toLinearMap
      (fun _ => rfl) n x
  have hdiff (x : M) : π ((G.toLinearMap ^ p - 1) x) =
      ((torsionQuotEquiv G).toLinearMap ^ p - 1) (π x) := by
    simp only [LinearMap.sub_apply, Module.End.one_apply, map_sub, hpow]
  have himage (x : M) : ((G.toLinearMap ^ p - 1) ^ d) x ∈ Submodule.torsion ℤ M := by
    apply (Submodule.Quotient.mk_eq_zero _).mp
    change π (((G.toLinearMap ^ p - 1) ^ d) x) = 0
    rw [linear_semiconj_pow π _ _ hdiff, hquot', LinearMap.zero_apply]
  refine ⟨p, d + 1, hp, Nat.succ_pos _, ?_⟩
  apply LinearMap.ext
  intro x
  rw [pow_succ', Module.End.mul_apply, LinearMap.sub_apply, Module.End.one_apply,
    LinearMap.zero_apply, sub_eq_zero]
  simpa only [Module.End.pow_apply, LinearEquiv.pow_apply, LinearEquiv.coe_coe] using
    hper' (((G.toLinearMap ^ p - 1) ^ d) x) (himage x)

theorem fg_cyclic_orbit_alternative [Module.Finite ℤ M] (l : M)
    (hspan : Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l) = ⊤) :
    (∃ (φ : M →+ ℂ) (ζ : ℂ), φ l ≠ 0 ∧ 1 < ‖ζ‖ ∧
      ∀ x, φ (G x) = ζ * φ x) ∨
    (∃ N d : ℕ, 0 < N ∧ 0 < d ∧ (G.toLinearMap ^ N - 1) ^ d = 0) := by
  let π := (Submodule.torsion ℤ M).mkQ
  rcases lattice_orbit_alternative (torsionQuotEquiv G) (π l)
      (torsionQuot_cyclic G l hspan) with h | h
  · obtain ⟨φ, ζ, hφ, hζ, heigen⟩ := h
    exact Or.inl ⟨φ.comp π.toAddMonoidHom, ζ, hφ, hζ, fun x => heigen (π x)⟩
  · obtain ⟨N, d, hN, hd, hnil⟩ := h
    exact Or.inr (quasiUnipotent_of_torsionQuot G N d hN hd hnil)

end

open scoped BigOperators
section
variable {L : Type*} [AddCommGroup L] (G : L ≃ₗ[ℤ] L) (l : L)

noncomputable def cyclicOrbit : Submodule ℤ L :=
  Submodule.span ℤ (Set.range fun n : ℤ => (G ^ n) l)

noncomputable def initialOrbit (q : ℕ) : Submodule ℤ L :=
  Submodule.span ℤ ((fun n : ℕ => (G ^ n) l) '' {n | n < q})

lemma mem_initialOrbit {q i : ℕ} (hi : i < q) :
    (G ^ i) l ∈ initialOrbit G l q :=
  Submodule.subset_span ⟨i, hi, rfl⟩

theorem cyclicOrbit_fg_of_boundary (q : ℕ) (hq : 0 < q)
    (hupper : (G ^ q) l ∈ initialOrbit G l q)
    (hlower : G.symm l ∈ initialOrbit G l q) :
    (cyclicOrbit G l).FG := by
  let M := initialOrbit G l q
  have hforward : M ≤ M.comap G.toLinearMap := by
    apply Submodule.span_le.mpr
    rintro _ ⟨i, hi, rfl⟩
    change G ((G ^ i) l) ∈ M
    rw [← LinearEquiv.mul_apply, ← pow_succ']
    have hle : i + 1 ≤ q := hi
    rcases lt_or_eq_of_le hle with hlt | heq
    · exact mem_initialOrbit G l hlt
    · simpa [heq] using hupper
  have hbackward : M ≤ M.comap G.symm.toLinearMap := by
    apply Submodule.span_le.mpr
    rintro _ ⟨i, hi, rfl⟩
    change G.symm ((G ^ i) l) ∈ M
    cases i with
    | zero => simpa using hlower
    | succ i =>
      rw [pow_succ', LinearEquiv.mul_apply, G.symm_apply_apply]
      exact mem_initialOrbit G l (Nat.lt_trans (Nat.lt_succ_self i) hi)
  have hzero : l ∈ M := by simpa using mem_initialOrbit G l hq
  have horbit (n : ℤ) : (G ^ n) l ∈ M := by
    induction n using Int.induction_on with
    | zero => simpa using hzero
    | succ n ih =>
      have hh := hforward ih
      change G ((G ^ (n : ℤ)) l) ∈ M at hh
      simpa only [← LinearEquiv.mul_apply, ← zpow_one_add, add_comm] using hh
    | pred n ih =>
      have hh := hbackward ih
      change G.symm ((G ^ (-(n : ℤ))) l) ∈ M at hh
      have heq : G.symm * G ^ (-(n : ℤ)) = G ^ (-(n : ℤ) - 1) := by
        change G⁻¹ * G ^ (-(n : ℤ)) = _
        rw [← zpow_neg_one, ← zpow_add]
        congr 1
        omega
      rw [← LinearEquiv.mul_apply, heq] at hh
      convert hh using 1
  have hEq : cyclicOrbit G l = M := by
    apply le_antisymm
    · exact Submodule.span_le.mpr (by rintro _ ⟨n, rfl⟩; exact horbit n)
    · apply Submodule.span_le.mpr
      rintro _ ⟨i, _, rfl⟩
      exact Submodule.subset_span ⟨(i : ℤ), by simp⟩
  rw [hEq]
  exact Submodule.fg_span ((Set.finite_Iio q).image _)

theorem cyclicOrbit_fg_of_relation (q : ℕ) (hq : 0 < q) (b : ℕ → ℤ)
    (hb0 : b 0 = 1 ∨ b 0 = -1) (hbq : b q = 1 ∨ b q = -1)
    (hrel : ∑ i ∈ Finset.range (q + 1), b i • (G ^ i) l = 0) :
    (cyclicOrbit G l).FG := by
  apply cyclicOrbit_fg_of_boundary G l q hq
  · have hs : (∑ i ∈ Finset.range q, b i • (G ^ i) l) ∈ initialOrbit G l q := by
      apply Submodule.sum_mem
      intro i hi
      exact Submodule.smul_mem _ _ (mem_initialOrbit G l (Finset.mem_range.mp hi))
    rw [Finset.sum_range_succ] at hrel
    have hh : b q • (G ^ q) l ∈ initialOrbit G l q := by
      rw [eq_neg_of_add_eq_zero_right hrel]
      exact Submodule.neg_mem _ hs
    rcases hbq with h | h <;> simpa [h] using hh
  · have hs : (∑ i ∈ Finset.range q, b (i + 1) • (G ^ i) l) ∈
        initialOrbit G l q := by
      apply Submodule.sum_mem
      intro i hi
      exact Submodule.smul_mem _ _ (mem_initialOrbit G l (Finset.mem_range.mp hi))
    rw [Finset.sum_range_succ'] at hrel
    have hh := congrArg G.symm hrel
    simp only [map_add, map_sum, map_zsmul, pow_zero,
      pow_succ', LinearEquiv.mul_apply, G.symm_apply_apply, map_zero] at hh
    change (∑ x ∈ Finset.range q, b (x + 1) • (G ^ x) l) + b 0 • G.symm l = 0 at hh
    have hb : b 0 • G.symm l ∈ initialOrbit G l q := by
      rw [eq_neg_of_add_eq_zero_right hh]
      exact Submodule.neg_mem _ hs
    rcases hb0 with h | h <;> simpa [h] using hb

lemma cyclicOrbit_shift (m : ℕ) : cyclicOrbit G ((G ^ m) l) = cyclicOrbit G l := by
  unfold cyclicOrbit
  congr 1
  ext x
  constructor
  · rintro ⟨n, rfl⟩
    refine ⟨n + (m : ℤ), ?_⟩
    change (G ^ (n + (m : ℤ))) l = (G ^ n) ((G ^ m) l)
    rw [zpow_add, LinearEquiv.mul_apply, zpow_natCast]
  · rintro ⟨n, rfl⟩
    refine ⟨n - (m : ℤ), ?_⟩
    change (G ^ (n - (m : ℤ))) ((G ^ m) l) = (G ^ n) l
    rw [← zpow_natCast G m, ← LinearEquiv.mul_apply, ← zpow_add, sub_add_cancel]

theorem cyclicOrbit_fg_of_signed_relation (s : Finset ℕ) (hs : s.Nonempty)
    (ε : ℕ → Bool) (hrel : (∑ i ∈ s, if ε i then (G ^ i) l else -((G ^ i) l)) = 0) :
    (cyclicOrbit G l).FG := by
  classical
  let m := s.min' hs
  let M := s.max' hs
  let q := M - m
  let v := (G ^ m) l
  let b : ℕ → ℤ := fun i => if m + i ∈ s then (if ε (m + i) then 1 else -1) else 0
  let f : ℕ → L := fun i => if i ∈ s then (if ε i then (G ^ i) l else -((G ^ i) l)) else 0
  have hm : m ∈ s := Finset.min'_mem s hs
  have hM : M ∈ s := Finset.max'_mem s hs
  have hmM : m ≤ M := Finset.min'_le s M hM
  have hmq : m + q = M := by dsimp [q]; omega
  have hsub : s ⊆ Finset.Ico m (M + 1) := by
    intro i hi
    exact Finset.mem_Ico.mpr ⟨Finset.min'_le s i hi,
      Nat.lt_succ_of_le (Finset.le_max' s i hi)⟩
  have hsum : (∑ i ∈ Finset.Ico m (M + 1), f i) = 0 := by
    rw [← Finset.sum_subset hsub (by intro i _ hi; simp [f, hi])]
    simpa only [f, Finset.sum_congr rfl (fun i hi => ite_eq_left hi)] using hrel
  have hb0 : b 0 = 1 ∨ b 0 = -1 := by simp only [b, Nat.add_zero, ite_eq_left hm]; split <;> simp
  have hbq : b q = 1 ∨ b q = -1 := by simp only [b, hmq, ite_eq_left hM]; split <;> simp
  have hnormalized : (∑ i ∈ Finset.range (q + 1), b i • (G ^ i) v) = 0 := by
    have hcount : M + 1 - m = q + 1 := by dsimp [q]; omega
    rw [Finset.sum_Ico_eq_sum_range, hcount] at hsum
    convert hsum using 1
    apply Finset.sum_congr rfl
    intro i _
    dsimp [b, f, v]
    split_ifs with hi hε
    · simp only [one_smul, ← LinearEquiv.mul_apply, ← pow_add, Nat.add_comm]
    · simp only [neg_one_smul, ← LinearEquiv.mul_apply, ← pow_add, Nat.add_comm]
    · simp only [zero_smul]
  have hv : (cyclicOrbit G v).FG := by
    rcases Nat.eq_zero_or_pos q with hq | hq
    · have hb : b 0 • v = 0 := by simpa [hq] using hnormalized
      have hv0 : v = 0 := by rcases hb0 with h | h <;> simpa [h] using hb
      simp only [hv0, cyclicOrbit, map_zero, Set.range_const, Submodule.span_singleton_eq_bot.mpr rfl]
      exact Submodule.fg_bot
    · exact cyclicOrbit_fg_of_relation G v q hq b hb0 hbq hnormalized
  simpa only [v, cyclicOrbit_shift] using hv

end

section OrbitGrowth
variable {L : Type*} [AddCommGroup L]

theorem dissociated_of_geometric_functional (l : ℕ → L) (φ : L →+ ℂ)
    (a ζ : ℂ) (ha : a ≠ 0) (hζ : 2 < ‖ζ‖)
    (hφ : ∀ m, φ (l m) = a * ζ ^ m) : Dissociated l := by
  classical
  intro s hs ε heq
  let m := s.max' hs
  have hm : m ∈ s := Finset.max'_mem s hs
  have hrel : (∑ i ∈ s, if ε i then a * ζ ^ i else -(a * ζ ^ i)) = 0 := by
    have hh := congrArg φ heq
    simpa only [map_sum, apply_ite, map_neg, map_zero, hφ] using hh
  have heq' : (if ε m then a * ζ ^ m else -(a * ζ ^ m)) =
      -(∑ i ∈ s.erase m, if ε i then a * ζ ^ i else -(a * ζ ^ i)) := by
    rw [← Finset.sum_erase_add _ _ hm] at hrel
    exact eq_neg_of_add_eq_zero_left (by simpa [add_comm] using hrel)
  have hsmall : s.erase m ⊆ Finset.range m := by
    intro i hi
    have his := Finset.mem_of_mem_erase hi
    have hne := (Finset.mem_erase.mp hi).1
    exact Finset.mem_range.mpr (lt_of_le_of_ne (Finset.le_max' s i his) hne)
  have hbound : ‖a‖ * ‖ζ‖ ^ m ≤ ‖a‖ * ∑ i ∈ Finset.range m, ‖ζ‖ ^ i := by
    calc
      _ = ‖if ε m then a * ζ ^ m else -(a * ζ ^ m)‖ := by
        split <;> simp [norm_pow]
      _ = ‖∑ i ∈ s.erase m, if ε i then a * ζ ^ i else -(a * ζ ^ i)‖ := by
        rw [heq', norm_neg]
      _ ≤ ∑ i ∈ s.erase m, ‖if ε i then a * ζ ^ i else -(a * ζ ^ i)‖ := norm_sum_le _ _
      _ = ∑ i ∈ s.erase m, ‖a‖ * ‖ζ‖ ^ i := by
        apply Finset.sum_congr rfl
        intro i _
        split <;> simp [norm_pow]
      _ ≤ ∑ i ∈ Finset.range m, ‖a‖ * ‖ζ‖ ^ i :=
        Finset.sum_le_sum_of_subset_of_nonneg hsmall (fun _ _ _ => by positivity)
      _ = _ := by rw [Finset.mul_sum]
  have hsum : (∑ i ∈ Finset.range m, ‖ζ‖ ^ i) < ‖ζ‖ ^ m := by
    induction m with
    | zero => simp
    | succ m ih =>
      rw [Finset.sum_range_succ, pow_succ]
      have hp : 0 < ‖ζ‖ ^ m := pow_pos (lt_trans (by norm_num) hζ) m
      nlinarith
  have ha' : 0 < ‖a‖ := norm_pos_iff.mpr ha
  exact (not_lt_of_ge hbound) (mul_lt_mul_of_pos_left hsum ha')

theorem dissociated_progressions_of_eigenfunctional (G : L → L) (l : L)
    (φ : L →+ ℂ) (ζ : ℂ) (hl : φ l ≠ 0) (hζ : 1 < ‖ζ‖)
    (heigen : ∀ v, φ (G v) = ζ * φ v) :
    ∃ p : ℕ, 0 < p ∧ ∀ j : ℕ,
      Dissociated (fun m => G^[p * m + j] l) := by
  obtain ⟨p, hp⟩ := pow_unbounded_of_one_lt (2 : ℝ) hζ
  have hp0 : 0 < p := by
    by_contra hh
    have : p = 0 := Nat.eq_zero_of_not_pos hh
    simp [this] at hp
  have hφ (n : ℕ) : φ (G^[n] l) = φ l * ζ ^ n := by
    induction n with
    | zero => simp
    | succ n ih =>
      rw [Function.iterate_succ_apply', heigen, ih, pow_succ]
      ring
  refine ⟨p, hp0, fun j => ?_⟩
  apply dissociated_of_geometric_functional _ φ (φ l * ζ ^ j) (ζ ^ p)
  · exact mul_ne_zero hl (pow_ne_zero _ (by intro hh; norm_num [hh] at hζ))
  · simpa only [norm_pow] using hp
  · intro m
    rw [hφ, pow_add, pow_mul]
    ring


theorem differencePolynomial_of_nilpotent_difference (G : Module.End ℤ L)
    (d : ℕ) (l : L) (h : ((G - 1) ^ (d + 1)) l = 0) :
    DifferencePolynomial d (fun m => (G ^ m) l) := by
  induction d generalizing l with
  | zero =>
    have hl : G l = l := by
      simpa only [zero_add, pow_one, LinearMap.sub_apply, Module.End.one_apply,
        sub_eq_zero] using h
    refine ⟨l, ?_⟩
    intro m
    induction m with
    | zero => rfl
    | succ m ih => simpa only [pow_succ, Module.End.mul_apply, hl] using ih
  | succ d ih =>
    apply DifferencePolynomial.of_forward_difference
    have hn : ((G - 1) ^ (d + 1)) ((G - 1) l) = 0 := by
      simpa only [pow_succ, Module.End.mul_apply] using h
    have hp := ih ((G - 1) l) hn
    convert hp using 1
    funext m
    simp only [pow_succ, Module.End.mul_apply, LinearMap.sub_apply,
      Module.End.one_apply, map_sub]

theorem polynomial_progressions_of_nilpotent (G : Module.End ℤ L)
    (p d : ℕ) (h : (G ^ p - 1) ^ (d + 1) = 0) (l : L) (j : ℕ) :
    DifferencePolynomial d (fun m => (G ^ (p * m + j)) l) := by
  have hn : ((G ^ p - 1) ^ (d + 1)) ((G ^ j) l) = 0 := by rw [h]; rfl
  have hp := differencePolynomial_of_nilpotent_difference (G ^ p) d ((G ^ j) l) hn
  convert hp using 1
  funext m
  rw [pow_add, pow_mul, Module.End.mul_apply]

end OrbitGrowth

section
variable {L : Type*} [AddCommGroup L] (G : L ≃ₗ[ℤ] L) (l : L)

lemma cyclicOrbit_zpow_mem (m : ℤ) {x : L} (hx : x ∈ cyclicOrbit G l) :
    (G ^ m) x ∈ cyclicOrbit G l := by
  induction hx using Submodule.span_induction with
  | mem y hy =>
    obtain ⟨n, rfl⟩ := hy
    apply Submodule.subset_span
    exact ⟨m + n, by dsimp; rw [zpow_add, LinearEquiv.mul_apply]⟩
  | zero => simpa only [map_zero] using (zero_mem (cyclicOrbit G l))
  | add x y _ _ hx hy => simpa only [map_add] using Submodule.add_mem _ hx hy
  | smul a x _ hx => simpa only [map_smul] using Submodule.smul_mem _ a hx

lemma cyclicOrbit_apply_mem {x : L} (hx : x ∈ cyclicOrbit G l) :
    G x ∈ cyclicOrbit G l := by simpa using cyclicOrbit_zpow_mem G l 1 hx

lemma cyclicOrbit_symm_apply_mem {x : L} (hx : x ∈ cyclicOrbit G l) :
    G.symm x ∈ cyclicOrbit G l := by simpa using cyclicOrbit_zpow_mem G l (-1) hx

noncomputable def cyclicOrbitEquiv : cyclicOrbit G l ≃ₗ[ℤ] cyclicOrbit G l where
  toFun x := ⟨G x, cyclicOrbit_apply_mem G l x.property⟩
  invFun x := ⟨G.symm x, cyclicOrbit_symm_apply_mem G l x.property⟩
  left_inv x := by ext; exact G.symm_apply_apply x
  right_inv x := by ext; exact G.apply_symm_apply x
  map_add' x y := by ext; exact map_add G _ _
  map_smul' a x := by ext; exact map_smul G a (x : L)

lemma cyclicOrbitEquiv_zpow_coe (n : ℤ) (x : cyclicOrbit G l) :
    ((cyclicOrbitEquiv G l ^ n) x : L) = (G ^ n) x := by
  induction n using Int.induction_on generalizing x with
  | zero => rfl
  | succ n ih =>
    simp only [zpow_add, zpow_one, LinearEquiv.mul_apply]
    exact ih (cyclicOrbitEquiv G l x)
  | pred n ih =>
    simp only [zpow_sub, zpow_one, LinearEquiv.mul_apply]
    exact ih ((cyclicOrbitEquiv G l).symm x)

lemma cyclicOrbitEquiv_pow_coe (n : ℕ) (x : cyclicOrbit G l) :
    ((cyclicOrbitEquiv G l ^ n) x : L) = (G ^ n) x := by
  simpa only [zpow_natCast] using cyclicOrbitEquiv_zpow_coe G l (n : ℤ) x

noncomputable def cyclicGenerator : cyclicOrbit G l :=
  ⟨l, Submodule.subset_span ⟨0, by simp⟩⟩

lemma cyclicGenerator_spans : Submodule.span ℤ (Set.range fun n : ℤ =>
    (cyclicOrbitEquiv G l ^ n) (cyclicGenerator G l)) = ⊤ := by
  apply (Submodule.span_val_image_eq_iff (cyclicOrbit G l) _).mp
  rw [← Set.range_comp]
  have heq : (Subtype.val ∘ fun n : ℤ =>
      (cyclicOrbitEquiv G l ^ n) (cyclicGenerator G l)) = fun n : ℤ => (G ^ n) l := by
    funext n
    exact cyclicOrbitEquiv_zpow_coe G l n (cyclicGenerator G l)
  rw [heq]
  rfl

lemma Dissociated.of_injective_map {A B : Type*} [AddCommGroup A] [AddCommGroup B]
    (f : A →+ B) (hf : Function.Injective f) (a : ℕ → A)
    (h : Dissociated a) : Dissociated (fun n => f (a n)) := by
  intro s hs ε hzero
  apply h s hs ε
  apply hf
  rw [map_zero, map_sum]
  convert hzero using 1
  apply Finset.sum_congr rfl
  intro i _
  split <;> simp only [map_neg]

theorem orbit_alternatives :
    Dissociated (fun r : ℕ => (G ^ r) l) ∨
    (∃ p : ℕ, 0 < p ∧ ∀ j : ℕ, Dissociated (fun m => (G ^ (p * m + j)) l)) ∨
    (∃ p d : ℕ, 0 < p ∧ 0 < d ∧
      ((cyclicOrbitEquiv G l).toLinearMap ^ p - 1) ^ d = 0) := by
  classical
  by_cases hdiss : Dissociated (fun r : ℕ => (G ^ r) l)
  · exact Or.inl hdiss
  · right
    simp only [Dissociated, not_forall, exists_prop, not_ne_iff] at hdiss
    obtain ⟨s, hs, ε, hrel⟩ := hdiss
    have hfg := cyclicOrbit_fg_of_signed_relation G l s hs ε hrel
    have : Module.Finite ℤ (cyclicOrbit G l) := Module.Finite.of_fg hfg
    rcases fg_cyclic_orbit_alternative (cyclicOrbitEquiv G l) (cyclicGenerator G l)
        (cyclicGenerator_spans G l) with h | h
    · obtain ⟨φ, ζ, hφ, hζ, heigen⟩ := h
      obtain ⟨p, hp, hd⟩ := dissociated_progressions_of_eigenfunctional
        (cyclicOrbitEquiv G l) (cyclicGenerator G l) φ ζ hφ hζ heigen
      refine Or.inl ⟨p, hp, fun j => ?_⟩
      have hh := Dissociated.of_injective_map (cyclicOrbit G l).subtype.toAddMonoidHom
        (cyclicOrbit G l).injective_subtype _ (hd j)
      have heq (n : ℕ) : (((cyclicOrbitEquiv G l)^[n]) (cyclicGenerator G l) : L) =
          (G ^ n) l := by
        rw [← LinearEquiv.pow_apply]
        exact cyclicOrbitEquiv_pow_coe G l n (cyclicGenerator G l)
      change Dissociated (fun n => (((cyclicOrbitEquiv G l)^[p * n + j])
        (cyclicGenerator G l) : L)) at hh
      simpa only [heq] using hh
    · exact Or.inr h

end

section
open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate

theorem cesaro_zero_of_progressions (a : ℕ → ℝ) (ha : ∀ n, 0 ≤ a n)
    (p : ℕ) (hp : 0 < p)
    (h : ∀ j < p, Tendsto (fun N : ℕ =>
      (∑ m ∈ Finset.range N, a (p * m + j)) / N) atTop (𝓝 0)) :
    Tendsto (fun N : ℕ => (∑ m ∈ Finset.range N, a m) / N) atTop (𝓝 0) := by
  have hblock (N : ℕ) : (∑ m ∈ Finset.range (p * N), a m) =
      ∑ m ∈ Finset.range N, ∑ j ∈ Finset.range p, a (p * m + j) := by
    induction N with
    | zero => simp
    | succ N ih =>
      rw [Nat.mul_succ, Finset.sum_range_add, ih, Finset.sum_range_succ]
  have hsum := tendsto_finsetSum (Finset.range p) (fun j hj => h j (Finset.mem_range.mp hj))
  simp only [Finset.sum_const_zero] at hsum
  apply squeeze_zero (fun N => div_nonneg
    (Finset.sum_nonneg (fun m _ => ha m)) (Nat.cast_nonneg N)) (fun N => ?_) hsum
  rw [← Finset.sum_div, Finset.sum_comm, ← hblock]
  apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg N)
  exact Finset.sum_le_sum_of_subset_of_nonneg
    (Finset.range_mono (by simpa using Nat.mul_le_mul_right N hp))
    (fun m _ _ => ha m)

namespace DifferencePolynomial

theorem map {A B : Type*} [AddCommGroup A] [AddCommGroup B]
    (f : A →+ B) {d : ℕ} {P : ℕ → A} (h : DifferencePolynomial d P) :
    DifferencePolynomial d (fun m => f (P m)) := by
  induction d generalizing P with
  | zero => obtain ⟨l, hl⟩ := h; exact ⟨f l, fun m => congrArg f (hl m)⟩
  | succ d ih =>
    intro s hs
    simpa only [map_sub] using ih (h s hs)
end DifferencePolynomial

theorem wordEntropy_comp {X Y A : Type*} [MeasurableSpace X] [MeasurableSpace Y]
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]
    {μ : Measure X} [IsProbabilityMeasure μ] {η : Measure Y} [IsProbabilityMeasure η]
    (x : Y → X) (hx : MeasurePreserving x η μ)
    (F : ℕ → X → A) (hF : ∀ m, Measurable (F m)) (n : ℕ) :
    wordEntropy (η := η) (fun m y => F m (x y)) n = wordEntropy (η := μ) F n := by
  unfold wordEntropy shannonEntropy
  apply Finset.sum_congr rfl
  intro w _
  have he : η.real (entropyWord (fun m y => F m (x y)) n ⁻¹' {w}) =
      μ.real (entropyWord F n ⁻¹' {w}) := hx.measureReal_preimage
    ((Measurable.of_eval (fun _ => hF _)) (measurableSet_singleton w)).nullMeasurableSet
  dsimp only
  rw [he]


theorem orbit_cancellation_unit
    {X Y L A : Type*} [MeasurableSpace X] [MeasurableSpace Y] [AddCommGroup L]
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]
    {μ : Measure X} [IsProbabilityMeasure μ]
    {η : Measure Y} [IsProbabilityMeasure η]
    (x : Y → X) (hx : MeasurePreserving x η μ)
    (t : ℕ → X → X) (ht : ∀ m, MeasurePreserving (t m) μ μ)
    (htadd : ∀ a b z, t (a + b) z = t b (t a z))
    (hmix : ∀ A B : Set X, MeasurableSet A → MeasurableSet B →
      Tendsto (fun m => μ (A ∩ t m ⁻¹' B)) atTop (𝓝 (μ A * μ B)))
    (a : X → A) (ha : Measurable a) (v : A → ℂ) (hv : ∀ b, ‖v b‖ ≤ 1)
    (hcenter : ∫ z, v (a z) ∂μ = 0)
    (hH : Tendsto (fun n : ℕ => wordEntropy (η := μ) (fun m z => a (t m z)) n / n)
      atTop (𝓝 0))
    {χ : L → Y → ℂ} (hχ : ProjectiveCharacters η χ)
    (G : L ≃ₗ[ℤ] L) (l : L) :
    Tendsto (fun N : ℕ => (∑ m ∈ Finset.range N,
      ‖∫ y, v (a (t m (x y))) * conj (χ ((G ^ m) l) y) ∂η‖) / N)
      atTop (𝓝 0) := by
  have haw (m : ℕ) : Measurable (fun y => a (t m (x y))) :=
    ha.comp ((ht m).measurable.comp hx.measurable)
  have hHy : Tendsto (fun n : ℕ =>
      wordEntropy (η := η) (fun m y => a (t m (x y))) n / n) atTop (𝓝 0) := by
    have he (n : ℕ) := wordEntropy_comp x hx (fun m z => a (t m z))
      (fun m => ha.comp (ht m).measurable) n
    simpa only [he] using hH
  rcases orbit_alternatives G l with hd | ⟨p, hp, hd⟩ | ⟨p, d, hp, hd, hn⟩
  · exact entropy_cancellation hχ _ hd _ haw v hv hHy
  · apply cesaro_zero_of_progressions _ (fun _ => norm_nonneg _) p hp
    intro j _
    exact entropy_cancellation hχ _ (hd j) _ (fun m => haw (p * m + j)) v hv
      (zero_entropy_progression _ haw hHy p hp j)
  · obtain ⟨d, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hd.ne'
    have hpm : Tendsto (fun m : ℕ => p * m) atTop atTop :=
      tendsto_atTop_mono (fun m => by simpa using Nat.mul_le_mul_right m hp) tendsto_id
    apply cesaro_zero_of_progressions _ (fun _ => norm_nonneg _) p hp
    intro j _
    have hpoly := polynomial_progressions_of_nilpotent
      (cyclicOrbitEquiv G l).toLinearMap p d hn (cyclicGenerator G l) j
    have hmap := hpoly.map (cyclicOrbit G l).subtype.toAddMonoidHom
    have heq (m : ℕ) : ((cyclicOrbitEquiv G l).toLinearMap ^ m) (cyclicGenerator G l) =
        (cyclicOrbitEquiv G l ^ m) (cyclicGenerator G l) := by
      rw [Module.End.pow_apply, LinearEquiv.coe_coe, ← LinearEquiv.pow_apply]
    have hpolyl : DifferencePolynomial d (fun m => (G ^ (p * m + j)) l) := by
      convert hmap using 1
      funext m
      change (G ^ (p * m + j)) l =
        (((cyclicOrbitEquiv G l).toLinearMap ^ (p * m + j)) (cyclicGenerator G l) : L)
      rw [heq, cyclicOrbitEquiv_pow_coe]
      rfl
    have hfm : AEStronglyMeasurable (fun z => v (a z)) μ :=
      ((measurable_of_finite v).comp ha).aestronglyMeasurable
    have hfmj := hfm.comp_measurePreserving (ht j)
    have hfj0 : ∫ z, v (a (t j z)) ∂μ = 0 := by
      have hh := integral_map (μ := μ) (f := fun z => v (a z))
        (ht j).measurable.aemeasurable (by rw [(ht j).map_eq]; exact hfm)
      simpa only [(ht j).map_eq, hcenter] using hh.symm
    have hc := polynomial_cancellation x hx (fun m => t (p * m)) (fun m => ht (p * m)) hχ
      (fun b c z => by rw [Nat.mul_add, htadd])
      (fun A B hA hB => (hmix A B hA hB).comp hpm) d _ hpolyl hfmj zero_le_one
      (Eventually.of_forall (fun z => hv (a (t j z)))) hfj0
    simpa only [Function.comp_apply, htadd, div_eq_mul_inv, mul_comm] using hc

end

open MeasureTheory Filter
open scoped BigOperators Topology ComplexConjugate

theorem orbit_cancellation
    {X Y L A : Type*} [MeasurableSpace X] [MeasurableSpace Y] [AddCommGroup L]
    [Fintype A] [MeasurableSpace A] [MeasurableSingletonClass A]
    {μ : Measure X} [IsProbabilityMeasure μ]
    {η : Measure Y} [IsProbabilityMeasure η]
    (x : Y → X) (hx : MeasurePreserving x η μ)
    (t : ℕ → X → X) (ht : ∀ m, MeasurePreserving (t m) μ μ)
    (htadd : ∀ a b z, t (a + b) z = t b (t a z))
    (hmix : ∀ A B : Set X, MeasurableSet A → MeasurableSet B →
      Tendsto (fun m => μ (A ∩ t m ⁻¹' B)) atTop (𝓝 (μ A * μ B)))
    (a : X → A) (ha : Measurable a) (v : A → ℂ)
    (hcenter : ∫ z, v (a z) ∂μ = 0)
    (hH : Tendsto (fun n : ℕ => wordEntropy (η := μ) (fun m z => a (t m z)) n / n)
      atTop (𝓝 0))
    {χ : L → Y → ℂ} (hχ : ProjectiveCharacters η χ)
    (G : L ≃ₗ[ℤ] L) (l : L) :
    Tendsto (fun N : ℕ => (N : ℝ)⁻¹ * ∑ m ∈ Finset.range N,
      ‖∫ y, v (a (t m (x y))) * conj (χ ((G ^ m) l) y) ∂η‖)
      atTop (𝓝 0) := by
  let C : ℝ := (∑ b, ‖v b‖) + 1
  have hC : 0 < C := by
    have : 0 ≤ ∑ b, ‖v b‖ := Finset.sum_nonneg (fun _ _ => norm_nonneg _)
    dsimp only [C]
    linarith
  have hCn : (C : ℂ) ≠ 0 := by exact_mod_cast hC.ne'
  let w (b : A) : ℂ := (C : ℂ)⁻¹ * v b
  have hw (b : A) : ‖w b‖ ≤ 1 := by
    have hb := Finset.single_le_sum (fun b _ => norm_nonneg (v b)) (Finset.mem_univ b)
    change ‖(C : ℂ)⁻¹ * v b‖ ≤ 1
    rw [norm_mul, norm_inv, Complex.norm_real, Real.norm_of_nonneg hC.le, mul_comm,
      ← div_eq_mul_inv, div_le_one hC]
    dsimp only [C]
    linarith
  have hw0 : ∫ z, w (a z) ∂μ = 0 := by
    simp only [w, integral_const_mul, hcenter, mul_zero]
  have hlim := orbit_cancellation_unit x hx t ht htadd hmix a ha w hw hw0 hH hχ G l
  have he (b : A) : v b = (C : ℂ) * w b := by simp [w, hCn]
  have hecor (m : ℕ) : ‖∫ y, v (a (t m (x y))) * conj (χ ((G ^ m) l) y) ∂η‖ =
      C * ‖∫ y, w (a (t m (x y))) * conj (χ ((G ^ m) l) y) ∂η‖ := by
    simp_rw [he, mul_assoc, integral_const_mul]
    rw [norm_mul, Complex.norm_real, Real.norm_of_nonneg hC.le]
  have hh := hlim.const_mul C
  simp only [mul_zero] at hh
  convert hh using 1
  funext N
  simp only [hecor, ← Finset.mul_sum, div_eq_mul_inv]
  ring


end Rokhlin

end OAI