File size: 45,500 Bytes
785c727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import Mathlib
import OAI.Geometry.CubicTorus.Regularity.SmoothApproxLip

namespace OAI

section
section
noncomputable section
open MeasureTheory Set
open scoped ENNReal
namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

lemma cutoff_integration_by_parts {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (hb : ∀ x, f x ∈ Icc 0 1)
    {F : Cover → Cover} (hF : AdmissibleField F) :
    (∫ x in fundamentalCube, f x * divergence F x) =
      -(∫ x in fundamentalCube, ⟪gradient f x, F x⟫) := by
  have hi₁ : IntegrableOn (fun x ↦ f x * divergence F x) fundamentalCube :=
    integrableOn_periodic_continuous (hf.continuous.mul (continuous_divergence hF.1))
      (fun n x ↦ by rw [hp, divergence_periodic hF.2.1])
  have hi₂ : IntegrableOn (fun x ↦ ⟪gradient f x, F x⟫) fundamentalCube :=
    integrableOn_periodic_continuous ((gradient_contDiff hf).continuous.inner hF.1.continuous)
      (fun n x ↦ by rw [gradient_periodic hp, hF.2.1])
  have hz := integral_divergence_fundamentalCube (admissible_cutoff hf hp hb hF)
  simp_rw [divergence_smul_function (hf.differentiable (by simp)).differentiableAt
    (hF.1.differentiable (by simp)).differentiableAt] at hz
  rw [integral_add hi₁ hi₂] at hz
  linarith

def gradientCalibration (f : Cover → ℝ) (ε : ℝ) (x : Cover) : Cover :=
  -(Real.sqrt (⟪gradient f x, gradient f x⟫ + ε ^ 2))⁻¹ • gradient f x

lemma gradientCalibration_admissible {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) {ε : ℝ} (hε : 0 < ε) :
    AdmissibleField (gradientCalibration f ε) := by
  have hg := gradient_contDiff hf
  have hpos (x : Cover) : 0 < ⟪gradient f x, gradient f x⟫ + ε ^ 2 :=
    add_pos_of_nonneg_of_pos (real_inner_self_nonneg) (sq_pos_of_pos hε)
  refine ⟨?_, ?_, ?_⟩
  · exact (((ContDiff.inner ℝ hg hg).add contDiff_const).sqrt (fun x ↦ (hpos x).ne')).inv
      (fun x ↦ (Real.sqrt_pos.2 (hpos x)).ne') |>.neg |>.smul hg
  · intro n x
    dsimp only [gradientCalibration]
    rw [gradient_periodic hp]
  · intro x
    rw [gradientCalibration, norm_smul, Real.norm_eq_abs, abs_neg,
      abs_of_pos (inv_pos.2 (Real.sqrt_pos.2 (hpos x)))]
    rw [inv_mul_le_iff₀ (Real.sqrt_pos.2 (hpos x)), mul_one]
    apply Real.le_sqrt_of_sq_le
    rw [real_inner_self_eq_norm_sq]
    linarith [sq_nonneg ε]

lemma inner_gradientCalibration (f : Cover → ℝ) (ε : ℝ) (x : Cover) :
    ⟪gradient f x, gradientCalibration f ε x⟫ =
      -(‖gradient f x‖ ^ 2 / Real.sqrt (‖gradient f x‖ ^ 2 + ε ^ 2)) := by
  simp [gradientCalibration, inner_smul_right, div_eq_mul_inv, mul_comm]

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

theorem integral_norm_gradient_le {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (hb : ∀ x, f x ∈ Icc 0 1)
    {K : ℝ} (hK : ∀ F : Cover → Cover, AdmissibleField F →
      (∫ x in fundamentalCube, f x * divergence F x) ≤ K) :
    (∫ x in fundamentalCube, ‖gradient f x‖) ≤ K := by
  let ε : ℕ → ℝ := fun n ↦ 1 / ((n : ℝ) + 1)
  have hε (n) : 0 < ε n := by dsimp [ε]; positivity
  have hεlim : Tendsto ε atTop (𝓝 0) := tendsto_one_div_add_atTop_nhds_zero_nat
  let g : ℕ → Cover → ℝ := fun n x ↦
    ‖gradient f x‖ ^ 2 / Real.sqrt (‖gradient f x‖ ^ 2 + ε n ^ 2)
  have hgcont (n) : Continuous (g n) := by
    apply Continuous.div ((gradient_contDiff hf).continuous.norm.pow 2)
      (((gradient_contDiff hf).continuous.norm.pow 2).add continuous_const).sqrt
    intro x
    exact (Real.sqrt_pos.2 (add_pos_of_nonneg_of_pos (sq_nonneg _) (sq_pos_of_pos (hε n)))).ne'
  have hgbd (n) (x) : ‖g n x‖ ≤ ‖gradient f x‖ := by
    have hsq : 0 < ‖gradient f x‖ ^ 2 + ε n ^ 2 :=
      add_pos_of_nonneg_of_pos (sq_nonneg _) (sq_pos_of_pos (hε n))
    rw [Real.norm_eq_abs, abs_of_nonneg (by dsimp [g]; positivity)]
    dsimp only [g]
    apply (div_le_iff₀ (Real.sqrt_pos.2 hsq)).2
    calc
      _ = ‖gradient f x‖ * ‖gradient f x‖ := sq _
      _ ≤ _ := mul_le_mul_of_nonneg_left
        (Real.le_sqrt_of_sq_le (by linarith [sq_nonneg (ε n)])) (norm_nonneg _)
  have hglim (x) : Tendsto (fun n ↦ g n x) atTop (𝓝 ‖gradient f x‖) := by
    by_cases hz : gradient f x = 0
    · simp [g, hz]
    have hn : ‖gradient f x‖ ≠ 0 := norm_ne_zero_iff.2 hz
    have hl := (tendsto_const_nhds (x := ‖gradient f x‖ ^ 2)).div
      (Real.continuous_sqrt.tendsto _ |>.comp ((tendsto_const_nhds (x := ‖gradient f x‖ ^ 2)).add (hεlim.pow 2)))
      (by simpa only [zero_pow (by norm_num : 2 ≠ 0), add_zero, Real.sqrt_sq (norm_nonneg _)] using hn : Real.sqrt (‖gradient f x‖ ^ 2 + 0 ^ 2) ≠ 0)
    convert hl using 1
    · ext n
      rfl
    · simp [pow_two, hn]
  have hI : IntegrableOn (fun x ↦ ‖gradient f x‖) fundamentalCube :=
    integrableOn_periodic_continuous (gradient_contDiff hf).continuous.norm
      (fun n x ↦ by rw [gradient_periodic hp])
  have hconv := tendsto_integral_of_dominated_convergence (fun x ↦ ‖gradient f x‖)
    (fun n ↦ (hgcont n).aestronglyMeasurable) hI
    (fun n ↦ Eventually.of_forall (hgbd n)) (Eventually.of_forall hglim)
  apply le_of_tendsto hconv
  apply Eventually.of_forall
  intro n
  have hc := gradientCalibration_admissible hf hp (hε n)
  have hi := cutoff_integration_by_parts hf hp hb hc
  simp_rw [inner_gradientCalibration, integral_neg, neg_neg] at hi
  rw [← hi]
  exact hK _ hc

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology Convolution RealInnerProductSpace

lemma characteristic_nonneg (E : Set Torus) (x : Torus) : 0 ≤ characteristic E x := by
  rcases characteristic_dichotomy E x with h | h <;> simp [h]

lemma smoothApprox_characteristic_range (E : Set Torus) (n : ℕ) (x : Cover) :
    smoothApprox (characteristic E ∘ quotientMap) n x ∈ Icc (0 : ℝ) 1 := by
  refine ⟨?_, (le_abs_self _).trans (smoothApprox_bound
    (fun y ↦ characteristic_bound E (quotientMap y)) n x)⟩
  unfold smoothApprox
  rw [convolution_def]
  apply integral_nonneg
  intro y
  exact mul_nonneg ((mollifier n).nonneg_normed y) (characteristic_nonneg E _)

lemma characteristic_lift_periodic (E : Set Torus) (n : Fin 3 → ℤ) (x : Cover) :
    (characteristic E ∘ quotientMap) (x + latticeVector n) =
      (characteristic E ∘ quotientMap) x := by
  simp only [Function.comp_def, quotientMap_add, quotientMap_latticeVector, add_zero]

lemma torusApprox_eq_integral (E : Set Torus) (n : ℕ) (x : Torus) :
    torusApprox E n x = ∫ y : Cover, (mollifier n).normed volume y *
      characteristic E (x - quotientMap y) := by
  simp only [torusApprox, smoothApprox, convolution_def, ContinuousLinearMap.lsmul_apply,
    smul_eq_mul, Function.comp_def, quotientMap_sub, quotientMap_representative]

theorem smoothApprox_flux_le {E : Set Torus} (hE : MeasurableSet E)
    (hP : perimeter E ≠ ⊤) (n : ℕ) {F : Cover → Cover} (hF : AdmissibleField F) :
    (∫ x in fundamentalCube, smoothApprox (characteristic E ∘ quotientMap) n x *
      divergence F x) ≤ (perimeter E).toReal := by
  let φ : Cover → ℝ := (mollifier n).normed volume
  let D : Torus → ℝ := fun x ↦ divergence F (representative x)
  let d : Torus × Cover → ℝ := fun z ↦ characteristic E (z.1 - quotientMap z.2) * D z.1
  have hDm : Measurable D := (continuous_divergence hF.1).measurable.comp measurable_representative
  obtain ⟨M, _, hDb⟩ := periodic_bounded (continuous_divergence hF.1) (divergence_periodic hF.2.1)
  have hd : Measurable d :=
    (((measurable_characteristic hE).comp
      (measurable_fst.sub (measurable_quotientMap.comp measurable_snd))).mul
        (hDm.comp measurable_fst))
  have hdm (z : Torus × Cover) : |d z| ≤ M := by
    dsimp only [d]
    rw [abs_mul]
    calc
      _ ≤ 1 * |D z.1| := mul_le_mul_of_nonneg_right (characteristic_bound E _) (abs_nonneg _)
      _ ≤ M := by simpa [D, Real.norm_eq_abs] using hDb (representative z.1)
  have hφ : Integrable φ volume := (mollifier n).integrable_normed
  have hbase : Integrable (fun z : Torus × Cover ↦ φ z.2) (torusVolume.prod volume) := by
    simpa only [one_mul] using (integrable_const (1 : ℝ) (μ := torusVolume)).mul_prod hφ
  have hprod : Integrable (fun z : Torus × Cover ↦ φ z.2 * d z) (torusVolume.prod volume) :=
    hbase.mul_bdd hd.aestronglyMeasurable (Eventually.of_forall hdm)
  have hinner (y : Cover) : (∫ x, d (x, y) ∂torusVolume) ≤ (perimeter E).toReal := by
    let B : Set Torus := (fun x : Torus ↦ x + -(quotientMap y)) ⁻¹' E
    have hmB : MeasurableSet B := (measurable_id.add_const _) hE
    have hPB : perimeter B = perimeter E := perimeter_translation hE.nullMeasurableSet _
    have hEq : (fun x ↦ d (x, y)) = B.indicator D := by
      funext x
      classical
      by_cases hx : x ∈ B
      · have hx' : x - quotientMap y ∈ E := by simpa [B, sub_eq_add_neg] using hx
        simp [d, characteristic, hx, hx']
      · have hx' : x - quotientMap y ∉ E := by simpa [B, sub_eq_add_neg] using hx
        simp [d, characteristic, hx, hx']
    rw [hEq, integral_indicator hmB,
      setIntegral_lift (continuous_divergence hF.1) (divergence_periodic hF.2.1) hmB]
    have hh := abs_flux_le_perimeter (hPB ▸ hP) hF
    rw [hPB] at hh
    exact (le_abs_self _).trans hh
  have hSwap : (∫ x, torusApprox E n x * D x ∂torusVolume) =
      ∫ y : Cover, φ y * (∫ x, d (x, y) ∂torusVolume) := by
    simp_rw [torusApprox_eq_integral, ← integral_mul_const, mul_assoc]
    rw [integral_integral_swap hprod]
    congr 1
    funext y
    exact integral_const_mul _ _
  have hI : (∫ x, torusApprox E n x * D x ∂torusVolume) ≤ (perimeter E).toReal := by
    rw [hSwap]
    calc
      _ ≤ ∫ y : Cover, φ y * (perimeter E).toReal := by
        apply integral_mono
        · simpa only [Function.comp_def, Prod.swap_prod_mk, integral_const_mul] using hprod.swap.integral_prod_left
        · exact hφ.mul_const _
        · intro y
          exact mul_le_mul_of_nonneg_left (hinner y) ((mollifier n).nonneg_normed y)
      _ = _ := by rw [integral_mul_const, (mollifier n).integral_normed, one_mul]
  have hsc := smoothApprox_contDiff ((measurable_characteristic hE).comp measurable_quotientMap)
    (fun x ↦ characteristic_bound E (quotientMap x)) n
  have hsp := smoothApprox_periodic (characteristic_lift_periodic E) n
  have heq := setIntegral_lift (hsc.continuous.mul (continuous_divergence hF.1))
    (fun k x ↦ by simp only [Pi.mul_apply]; rw [hsp, divergence_periodic hF.2.1]) MeasurableSet.univ
  simp only [setIntegral_univ, preimage_univ, inter_univ] at heq
  exact heq ▸ hI

theorem smoothApprox_gradient_bound {E : Set Torus} (hE : MeasurableSet E)
    (hP : perimeter E ≠ ⊤) (n : ℕ) :
    (∫ x in fundamentalCube, ‖gradient (smoothApprox (characteristic E ∘ quotientMap) n) x‖)
      ≤ (perimeter E).toReal := by
  apply integral_norm_gradient_le
    (smoothApprox_contDiff ((measurable_characteristic hE).comp measurable_quotientMap)
      (fun x ↦ characteristic_bound E (quotientMap x)) n)
    (smoothApprox_periodic (characteristic_lift_periodic E) n)
    (smoothApprox_characteristic_range E n)
  intro F hF
  exact smoothApprox_flux_le hE hP n hF

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

lemma integrableOn_characteristic_mul {E : Set Torus}
    (hE : NullMeasurableSet E torusVolume) {g : Cover → ℝ}
    (hg : IntegrableOn g fundamentalCube) :
    IntegrableOn (fun x ↦ characteristic E (quotientMap x) * g x) fundamentalCube := by
  simp_rw [characteristic_mul]
  exact hg.indicator₀ (hE.preimage quotientMap_measurePreserving.quasiMeasurePreserving)

lemma gradient_const_sub (f : Cover → ℝ) (c : ℝ) (x : Cover) :
    gradient (fun y ↦ c - f y) x = -gradient f x := by
  simp only [gradient, fderiv_const_sub, map_neg]

lemma characteristic_union (E F : Set Torus) (x : Torus) :
    characteristic (E ∪ F) x = characteristic E x +
      (1 - characteristic E x) * characteristic F x := by
  classical
  by_cases he : x ∈ E <;> by_cases hf : x ∈ F <;> simp [characteristic, he, hf]

lemma cutoff_union_flux_le {E : Set Torus} (hE : NullMeasurableSet E torusVolume)
    (hP : perimeter E ≠ ⊤) {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (hb : ∀ x, f x ∈ Icc 0 1)
    {G : Cover → Cover} (hG : AdmissibleField G) :
    (∫ x in fundamentalCube, (characteristic E (quotientMap x) +
      (1 - characteristic E (quotientMap x)) * f x) * divergence G x) ≤
        (perimeter E).toReal + ∫ x in fundamentalCube, ‖gradient f x‖ := by
  let H : Cover → Cover := fun x ↦ (1 - f x) • G x
  have hH : AdmissibleField H := admissible_cutoff (contDiff_const.sub hf)
    (fun n x ↦ by rw [hp]) (fun x ↦ by constructor <;> linarith [(hb x).1, (hb x).2]) hG
  have hdH (x) : divergence H x = (1 - f x) * divergence G x -
      ⟪gradient f x, G x⟫ := by
    rw [divergence_smul_function ((contDiff_const.sub hf).differentiable (by simp)).differentiableAt
      (hG.1.differentiable (by simp)).differentiableAt, gradient_const_sub, inner_neg_left]
    rfl
  let a : Cover → ℝ := fun x ↦ characteristic E (quotientMap x) * divergence H x
  let b : Cover → ℝ := fun x ↦ (1 - characteristic E (quotientMap x)) * ⟪gradient f x, G x⟫
  let c : Cover → ℝ := fun x ↦ divergence (fun y ↦ f y • G y) x
  have hia : IntegrableOn a fundamentalCube := integrableOn_characteristic_mul hE
    (integrableOn_divergence hH.1)
  have hic : IntegrableOn c fundamentalCube :=
    integrableOn_divergence (admissible_cutoff hf hp hb hG).1
  have hii : IntegrableOn (fun x ↦ ⟪gradient f x, G x⟫) fundamentalCube :=
    integrableOn_periodic_continuous ((gradient_contDiff hf).continuous.inner hG.1.continuous)
      (fun n x ↦ by rw [gradient_periodic hp, hG.2.1])
  have hib : IntegrableOn b fundamentalCube := by
    have he := hii.sub (integrableOn_characteristic_mul hE hii)
    simpa only [b, Pi.sub_def, one_sub_mul] using he
  have hign : IntegrableOn (fun x ↦ ‖gradient f x‖) fundamentalCube :=
    integrableOn_periodic_continuous (gradient_contDiff hf).continuous.norm
      (fun n x ↦ by rw [gradient_periodic hp])
  have heq (x) : (characteristic E (quotientMap x) +
      (1 - characteristic E (quotientMap x)) * f x) * divergence G x =
        a x - b x + c x := by
    dsimp only [a, b, c]
    rw [hdH, divergence_smul_function (hf.differentiable (by simp)).differentiableAt
      (hG.1.differentiable (by simp)).differentiableAt]
    ring
  simp_rw [heq]
  have hiab : IntegrableOn (fun x ↦ a x - b x) fundamentalCube := by
    simpa only [Pi.sub_def] using hia.sub hib
  rw [integral_add hiab hic, integral_sub hia hib]
  have hc : (∫ x in fundamentalCube, c x) = 0 :=
    integral_divergence_fundamentalCube (admissible_cutoff hf hp hb hG)
  rw [hc, add_zero]
  have ha : (∫ x in fundamentalCube, a x) ≤ (perimeter E).toReal := by
    dsimp only [a]
    simp_rw [characteristic_mul]
    rw [lift_indicator_integral hE]
    exact (le_abs_self _).trans (abs_flux_le_perimeter hP hH)
  have hb' : -(∫ x in fundamentalCube, b x) ≤ ∫ x in fundamentalCube, ‖gradient f x‖ := by
    rw [← integral_neg]
    apply integral_mono hib.neg hign
    intro x
    have he : 0 ≤ 1 - characteristic E (quotientMap x) := by
      linarith [(le_abs_self _).trans (characteristic_bound E (quotientMap x))]
    have he' : 1 - characteristic E (quotientMap x) ≤ 1 := by
      linarith [characteristic_nonneg E (quotientMap x)]
    calc
      -b x ≤ |b x| := neg_le_abs _
      _ = (1 - characteristic E (quotientMap x)) * |⟪gradient f x, G x⟫| := by
        dsimp only [b]
        rw [abs_mul, abs_of_nonneg he]
      _ ≤ 1 * (‖gradient f x‖ * ‖G x‖) := mul_le_mul he'
        (abs_real_inner_le_norm _ _) (abs_nonneg _) (by norm_num)
      _ ≤ ‖gradient f x‖ := by simpa using mul_le_of_le_one_right (norm_nonneg _) (hG.2.2 x)
  linarith

theorem perimeter_union_le_of_measurable {E F : Set Torus}
    (hE : MeasurableSet E) (hF : MeasurableSet F) :
    perimeter (E ∪ F) ≤ perimeter E + perimeter F := by
  by_cases hPE : perimeter E = ⊤
  · simp [hPE]
  by_cases hPF : perimeter F = ⊤
  · simp [hPF]
  have hg := (measurable_characteristic hF).comp measurable_quotientMap
  have hb := fun x ↦ characteristic_bound F (quotientMap x)
  let f : ℕ → Cover → ℝ := smoothApprox (characteristic F ∘ quotientMap)
  have hf (n) := smoothApprox_contDiff hg hb n
  have hp (n) := smoothApprox_periodic (characteristic_lift_periodic F) n
  have hfb (n) := smoothApprox_characteristic_range F n
  apply iSup_le
  intro G
  apply iSup_le
  intro hG
  rw [← ENNReal.ofReal_toReal hPE, ← ENNReal.ofReal_toReal hPF, ← ENNReal.ofReal_add
    ENNReal.toReal_nonneg ENNReal.toReal_nonneg]
  apply ENNReal.ofReal_le_ofReal
  have hiG := integrableOn_divergence hG.1
  let u : ℕ → Cover → ℝ := fun n x ↦ (characteristic E (quotientMap x) +
    (1 - characteristic E (quotientMap x)) * f n x) * divergence G x
  have hm (n) : AEStronglyMeasurable (u n) (volume.restrict fundamentalCube) := by
    exact (((((measurable_characteristic hE).comp measurable_quotientMap).add
      ((measurable_const.sub ((measurable_characteristic hE).comp measurable_quotientMap)).mul
        (hf n).continuous.measurable)).mul (continuous_divergence hG.1).measurable)).aestronglyMeasurable
  have hbound (n) : ∀ᵐ x ∂volume.restrict fundamentalCube, ‖u n x‖ ≤ |divergence G x| := by
    apply Eventually.of_forall
    intro x
    have hx := characteristic_dichotomy E (quotientMap x)
    rcases hx with hx | hx
    · simpa [u, f, hx, Real.norm_eq_abs, abs_mul, Function.comp_def] using
        mul_le_of_le_one_left (abs_nonneg (divergence G x)) (smoothApprox_bound hb n x)
    · simp [u, hx, Real.norm_eq_abs]
  have hlim : ∀ᵐ x ∂volume.restrict fundamentalCube,
      Tendsto (fun n ↦ u n x) atTop (𝓝 (characteristic (E ∪ F) (quotientMap x) * divergence G x)) := by
    filter_upwards [ae_restrict_of_ae (smoothApprox_ae_tendsto hg hb)] with x hx
    rw [characteristic_union]
    exact (tendsto_const_nhds.add (tendsto_const_nhds.mul hx)).mul_const _
  have ht := tendsto_integral_of_dominated_convergence _ hm hiG.abs hbound hlim
  have hh : (∫ x in fundamentalCube, characteristic (E ∪ F) (quotientMap x) * divergence G x) ≤
      (perimeter E).toReal + (perimeter F).toReal := by
    apply le_of_tendsto ht
    apply Eventually.of_forall
    intro n
    exact (cutoff_union_flux_le hE.nullMeasurableSet hPE (hf n) (hp n) (hfb n) hG).trans
      (add_le_add_right (smoothApprox_gradient_bound hF hPF n) _)
  simpa only [characteristic_mul, lift_indicator_integral (hE.union hF).nullMeasurableSet] using hh

end CubicTorus

namespace CubicTorus

theorem perimeter_union_le {E F : Set Torus}
    (hE : NullMeasurableSet E torusVolume) (hF : NullMeasurableSet F torusVolume) :
    perimeter (E ∪ F) ≤ perimeter E + perimeter F := by
  have he := hE.toMeasurable_ae_eq
  have hf := hF.toMeasurable_ae_eq
  have hef : (toMeasurable torusVolume E ∪ toMeasurable torusVolume F : Set Torus) =ᵐ[torusVolume] (E ∪ F : Set Torus) := by
    filter_upwards [he, hf] with x hx hy
    change (x ∈ toMeasurable torusVolume E ∨ x ∈ toMeasurable torusVolume F) = (x ∈ E ∨ x ∈ F)
    rw [show (x ∈ toMeasurable torusVolume E) = (x ∈ E) from hx,
      show (x ∈ toMeasurable torusVolume F) = (x ∈ F) from hy]
  rw [← perimeter_congr_ae hef, ← perimeter_congr_ae he, ← perimeter_congr_ae hf]
  exact perimeter_union_le_of_measurable (measurableSet_toMeasurable _ _) (measurableSet_toMeasurable _ _)

theorem perimeter_diff_le {E F : Set Torus}
    (hE : NullMeasurableSet E torusVolume) (hF : NullMeasurableSet F torusVolume) :
    perimeter (E \ F) ≤ perimeter E + perimeter F := by
  have heq : E \ F = (Eᶜ ∪ F)ᶜ := by ext x; simp
  rw [heq, perimeter_compl (hE.compl.union hF)]
  exact (perimeter_union_le hE.compl hF).trans_eq (by rw [perimeter_compl hE])

theorem FinitePerimeter.union {E F : Set Torus} (hE : FinitePerimeter E) (hF : FinitePerimeter F) :
    FinitePerimeter (E ∪ F) :=
  ⟨hE.1.union hF.1, (perimeter_union_le hE.1 hF.1).trans_lt (ENNReal.add_lt_top.2 ⟨hE.2, hF.2⟩)⟩

theorem FinitePerimeter.diff {E F : Set Torus} (hE : FinitePerimeter E) (hF : FinitePerimeter F) :
    FinitePerimeter (E \ F) :=
  ⟨hE.1.diff hF.1, (perimeter_diff_le hE.1 hF.1).trans_lt (ENNReal.add_lt_top.2 ⟨hE.2, hF.2⟩)⟩

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

lemma smoothApprox_flux_tendsto {E : Set Torus} (hE : MeasurableSet E)
    {F : Cover → Cover} (hF : AdmissibleField F) :
    Tendsto (fun n ↦ ∫ x in fundamentalCube,
      smoothApprox (characteristic E ∘ quotientMap) n x * divergence F x) atTop
      (𝓝 (∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x)) := by
  have hg := (measurable_characteristic hE).comp measurable_quotientMap
  have hb := fun x ↦ characteristic_bound E (quotientMap x)
  have hf n := smoothApprox_contDiff hg hb n
  have ht := tendsto_integral_of_dominated_convergence (fun x ↦ |divergence F x|)
    (fun n ↦ ((hf n).continuous.mul (continuous_divergence hF.1)).aestronglyMeasurable)
    (integrableOn_divergence hF.1).abs
    (fun n ↦ Eventually.of_forall (fun x ↦ by
      change ‖smoothApprox (characteristic E ∘ quotientMap) n x * divergence F x‖ ≤ _
      rw [norm_mul, Real.norm_eq_abs, Real.norm_eq_abs]
      exact mul_le_of_le_one_left (abs_nonneg _) (smoothApprox_bound hb n x)))
    (by
      filter_upwards [ae_restrict_of_ae (smoothApprox_ae_tendsto hg hb)] with x hx
      exact hx.mul_const (divergence F x))
  simpa! only [Pi.mul_apply, Function.comp_def, characteristic_mul,
    lift_indicator_integral hE.nullMeasurableSet] using ht

lemma smooth_flux_le_gradient {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (hb : ∀ x, f x ∈ Icc 0 1)
    {F : Cover → Cover} (hF : AdmissibleField F) :
    (∫ x in fundamentalCube, f x * divergence F x) ≤
      ∫ x in fundamentalCube, ‖gradient f x‖ := by
  rw [cutoff_integration_by_parts hf hp hb hF, ← integral_neg]
  apply integral_mono
  · exact (integrableOn_periodic_continuous
      ((gradient_contDiff hf).continuous.inner hF.1.continuous)
      (fun n x ↦ by rw [gradient_periodic hp, hF.2.1])).neg
  · exact integrableOn_periodic_continuous (gradient_contDiff hf).continuous.norm
      (fun n x ↦ by rw [gradient_periodic hp])
  · intro x
    exact (neg_le_abs _).trans ((abs_real_inner_le_norm _ _).trans
      (mul_le_of_le_one_right (norm_nonneg _) (hF.2.2 x)))

theorem smoothApprox_gradient_tendsto {E : Set Torus} (hE : MeasurableSet E)
    (hP : perimeter E ≠ ⊤) :
    Tendsto (fun n ↦ ∫ x in fundamentalCube,
      ‖gradient (smoothApprox (characteristic E ∘ quotientMap) n) x‖) atTop
      (𝓝 (perimeter E).toReal) := by
  apply tendsto_order.2
  constructor
  · intro a ha
    by_cases ha0 : a < 0
    · exact Eventually.of_forall fun n ↦ ha0.trans_le (integral_nonneg fun x ↦ norm_nonneg _)
    have ha0' : 0 ≤ a := le_of_not_gt ha0
    have hh : ENNReal.ofReal a < perimeter E := by
      rw [← ENNReal.ofReal_toReal hP]
      exact (ENNReal.ofReal_lt_ofReal_iff_of_nonneg ha0').2 ha
    obtain ⟨F, hF⟩ := lt_iSup_iff.1 hh
    obtain ⟨hF, hflux⟩ := lt_iSup_iff.1 hF
    have hflux' : a < ∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x :=
      (ENNReal.ofReal_lt_ofReal_iff_of_nonneg ha0').1 hflux
    filter_upwards [(smoothApprox_flux_tendsto hE hF).eventually (eventually_gt_nhds hflux')] with n hn
    exact hn.trans_le (smooth_flux_le_gradient
      (smoothApprox_contDiff ((measurable_characteristic hE).comp measurable_quotientMap)
        (fun x ↦ characteristic_bound E (quotientMap x)) n)
      (smoothApprox_periodic (characteristic_lift_periodic E) n)
      (smoothApprox_characteristic_range E n) hF)
  · intro a ha
    exact Eventually.of_forall fun n ↦ (smoothApprox_gradient_bound hE hP n).trans_lt ha

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

abbrev NormalSphere := {v : Cover // ‖v‖ = 1}

instance : CompactSpace NormalSphere := by
  apply isCompact_iff_compactSpace.mp
  have hK : IsCompact ((WithLp.toLp 2) '' (Icc (-1 : Fin 3 → ℝ) 1)) :=
    isCompact_Icc.image (EuclideanSpace.equiv (Fin 3) ℝ).symm.continuous
  apply hK.of_isClosed_subset (isClosed_eq continuous_norm continuous_const)
  intro v hv
  change ‖v‖ = 1 at hv
  refine ⟨WithLp.ofLp v, ⟨?_, ?_⟩, rfl⟩
  · intro i
    have hh : |v i| ≤ 1 := by simpa only [Real.norm_eq_abs, hv] using PiLp.norm_apply_le v i
    exact (abs_le.mp hh).1
  · intro i
    have hh : |v i| ≤ 1 := by simpa only [Real.norm_eq_abs, hv] using PiLp.norm_apply_le v i
    exact (abs_le.mp hh).2

abbrev NormalBundle := CompactCell × NormalSphere

def normalizedVector (v : Cover) : Cover :=
  if v = 0 then EuclideanSpace.single 0 1 else ‖v‖⁻¹ • v

lemma normalizedVector_norm (v : Cover) : ‖normalizedVector v‖ = 1 := by
  unfold normalizedVector
  split_ifs with hv
  · simp
  · rw [norm_smul, Real.norm_of_nonneg (inv_nonneg.mpr (norm_nonneg _)),
      inv_mul_cancel₀ (norm_ne_zero_iff.mpr hv)]

lemma measurable_normalizedVector : Measurable normalizedVector := by
  exact Measurable.ite (measurableSet_singleton (0 : Cover)) measurable_const
    (measurable_id.norm.inv.smul measurable_id)

def unitNormal (v : Cover) : NormalSphere := ⟨normalizedVector v, normalizedVector_norm v⟩

lemma measurable_unitNormal : Measurable unitNormal := measurable_normalizedVector.subtype_mk

lemma norm_smul_normalizedVector (v : Cover) : ‖v‖ • normalizedVector v = v := by
  unfold normalizedVector
  split_ifs with hv
  · simp [hv]
  · rw [smul_smul, mul_inv_cancel₀ (norm_ne_zero_iff.mpr hv), one_smul]

def smoothNormalMap (f : Cover → ℝ) (x : Cover) : NormalBundle :=
  (cubeRepresentative (quotientMap x), unitNormal (-gradient f x))

lemma measurable_smoothNormalMap {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f) :
    Measurable (smoothNormalMap f) :=
  (measurable_cubeRepresentative.comp measurable_quotientMap).prodMk
    (measurable_unitNormal.comp (gradient_contDiff hf).continuous.measurable.neg)

def smoothNormalMeasure (f : Cover → ℝ) (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) : FiniteMeasure NormalBundle := by
  let μ := (volume.restrict fundamentalCube).withDensity (fun x ↦ ENNReal.ofReal ‖gradient f x‖)
  haveI : IsFiniteMeasure μ := isFiniteMeasure_withDensity_ofReal
    (integrableOn_periodic_continuous (gradient_contDiff hf).continuous.norm
      (fun n x ↦ by rw [gradient_periodic hp])).hasFiniteIntegral
  exact ⟨Measure.map (smoothNormalMap f) μ, inferInstance⟩

lemma integral_smoothNormalMeasure {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (g : C(NormalBundle, ℝ)) :
    (∫ z, g z ∂(smoothNormalMeasure f hf hp : Measure NormalBundle)) =
      ∫ x in fundamentalCube, ‖gradient f x‖ * g (smoothNormalMap f x) := by
  change (∫ z, g z ∂Measure.map (smoothNormalMap f) _) = _
  rw [integral_map (measurable_smoothNormalMap hf).aemeasurable g.continuous.aestronglyMeasurable]
  rw [integral_withDensity_eq_integral_toReal_smul
    (gradient_contDiff hf).continuous.norm.measurable.ennreal_ofReal
    (Eventually.of_forall fun x ↦ ENNReal.ofReal_lt_top)]
  simp only [ENNReal.toReal_ofReal (norm_nonneg _), smul_eq_mul]

lemma smoothNormalMeasure_mass {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) :
    ((smoothNormalMeasure f hf hp).mass : ℝ) =
      ∫ x in fundamentalCube, ‖gradient f x‖ := by
  have hh := integral_smoothNormalMeasure hf hp (ContinuousMap.const _ (1 : ℝ))
  simpa only [ContinuousMap.const_apply, integral_const, smul_eq_mul, mul_one,
    FiniteMeasure.mass, FiniteMeasure.coeFn_def, Measure.real, ENNReal.toReal] using hh

def normalTest (F : Cover → Cover) (hF : Continuous F) : C(NormalBundle, ℝ) :=
  ⟨fun z ↦ ⟪(z.2 : Cover), F (z.1 : Cover)⟫,
    (continuous_subtype_val.comp continuous_snd).inner
      (hF.comp (continuous_subtype_val.comp continuous_fst))⟩

lemma smoothNormalMeasure_flux {f : Cover → ℝ} (hf : ContDiff ℝ (⊤ : ℕ∞) f)
    (hp : ∀ n x, f (x + latticeVector n) = f x) (hb : ∀ x, f x ∈ Icc 0 1)
    {F : Cover → Cover} (hF : AdmissibleField F) :
    (∫ z, normalTest F hF.1.continuous z ∂(smoothNormalMeasure f hf hp : Measure NormalBundle)) =
      ∫ x in fundamentalCube, f x * divergence F x := by
  rw [integral_smoothNormalMeasure hf hp, cutoff_integration_by_parts hf hp hb hF,
    ← integral_neg]
  apply integral_congr_ae
  exact Eventually.of_forall fun x ↦ by
    change ‖gradient f x‖ * ⟪normalizedVector (-gradient f x),
      F (representative (quotientMap x))⟫ = -⟪gradient f x, F x⟫
    rw [periodic_representative hF.2.1, ← real_inner_smul_left,
      ← norm_neg (gradient f x), norm_smul_normalizedVector, inner_neg_left]

end CubicTorus

namespace CubicTorus
open Filter
open scoped Topology RealInnerProductSpace

theorem exists_normalMeasure {E : Set Torus} (hE : MeasurableSet E)
    (hP : perimeter E ≠ ⊤) :
    ∃ μ : FiniteMeasure NormalBundle,
      (μ.mass : ℝ) = (perimeter E).toReal ∧
      ∀ (F : Cover → Cover) (hF : AdmissibleField F),
        (∫ z, normalTest F hF.1.continuous z ∂(μ : Measure NormalBundle)) =
          ∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x := by
  let f n := smoothApprox (characteristic E ∘ quotientMap) n
  have hf n : ContDiff ℝ (⊤ : ℕ∞) (f n) := smoothApprox_contDiff
    ((measurable_characteristic hE).comp measurable_quotientMap)
    (fun x ↦ characteristic_bound E (quotientMap x)) n
  have hp n : ∀ k x, f n (x + latticeVector k) = f n x :=
    smoothApprox_periodic (characteristic_lift_periodic E) n
  let μn n := smoothNormalMeasure (f n) (hf n) (hp n)
  let P : NNReal := ⟨(perimeter E).toReal, ENNReal.toReal_nonneg⟩
  have hbound n : (μn n).mass ≤ P := by
    rw [← NNReal.coe_le_coe]
    change ((smoothNormalMeasure (f n) (hf n) (hp n)).mass : ℝ) ≤ (perimeter E).toReal
    rw [smoothNormalMeasure_mass]
    exact smoothApprox_gradient_bound hE hP n
  obtain ⟨μ, _, hμ⟩ := (isCompact_setOfPred_finiteMeasure_le_of_compactSpace NormalBundle P).exists_mapClusterPt (show Filter.map μn atTop ≤ 𝓟 {μ | μ.mass ≤ P} from
      tendsto_principal.mpr (Eventually.of_forall hbound))
  obtain ⟨U, hUa, hU⟩ := mapClusterPt_iff_ultrafilter.mp hμ
  refine ⟨μ, ?_, ?_⟩
  · have hmass : Tendsto (fun n ↦ ((μn n).mass : ℝ)) U (𝓝 (μ.mass : ℝ)) :=
      (continuous_subtype_val.comp FiniteMeasure.continuous_mass).continuousAt.tendsto.comp hU
    have henergy : Tendsto (fun n ↦ ((μn n).mass : ℝ)) U (𝓝 (perimeter E).toReal) := by
      simpa only [μn, smoothNormalMeasure_mass, f] using
        (smoothApprox_gradient_tendsto hE hP).mono_left hUa
    exact tendsto_nhds_unique hmass henergy
  · intro F hF
    have hinter : Tendsto (fun n ↦ ∫ z, normalTest F hF.1.continuous z
        ∂(μn n : Measure NormalBundle)) U
        (𝓝 (∫ z, normalTest F hF.1.continuous z ∂(μ : Measure NormalBundle))) :=
      (FiniteMeasure.continuous_integral_continuousMap (normalTest F hF.1.continuous)).continuousAt.tendsto.comp hU
    have hflux : Tendsto (fun n ↦ ∫ z, normalTest F hF.1.continuous z
        ∂(μn n : Measure NormalBundle)) U
        (𝓝 (∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x)) := by
      have heq n := smoothNormalMeasure_flux (hf n) (hp n)
        (smoothApprox_characteristic_range E n) hF
      simp_rw [show (fun n ↦ ∫ z, normalTest F hF.1.continuous z
          ∂(μn n : Measure NormalBundle)) = (fun n ↦ ∫ x in fundamentalCube, f n x * divergence F x)
        from funext heq]
      exact (smoothApprox_flux_tendsto hE hF).mono_left hUa
    exact tendsto_nhds_unique hinter hflux

end CubicTorus

namespace CubicTorus
open scoped RealInnerProductSpace

def IsNormalMeasure (E : Set Torus) (μ : FiniteMeasure NormalBundle) : Prop :=
  (μ.mass : ℝ) = (perimeter E).toReal ∧
  ∀ (F : Cover → Cover) (hF : AdmissibleField F),
    (∫ z, normalTest F hF.1.continuous z ∂(μ : Measure NormalBundle)) =
      ∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x

lemma normalMeasure_flux {E : Set Torus} {μ : FiniteMeasure NormalBundle}
    (hμ : IsNormalMeasure E μ) {F : Cover → Cover}
    (hF : ContDiff ℝ (⊤ : ℕ∞) F) (hp : ∀ n x, F (x + latticeVector n) = F x)
    {k : ℝ} (hk : 0 < k) (hb : ∀ x, ‖F x‖ ≤ k) :
    (∫ z, normalTest F hF.continuous z ∂(μ : Measure NormalBundle)) =
      ∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x := by
  have hG : AdmissibleField (fun x ↦ k⁻¹ • F x) := by
    refine ⟨hF.const_smul (k⁻¹ : ℝ), ?_, ?_⟩
    · intro n x
      change k⁻¹ • F (x + latticeVector n) = k⁻¹ • F x
      rw [hp]
    · intro x
      rw [norm_smul, Real.norm_eq_abs, abs_of_pos (inv_pos.mpr hk)]
      exact (mul_le_mul_of_nonneg_left (hb x) (inv_nonneg.mpr hk.le)).trans_eq
        (inv_mul_cancel₀ hk.ne')
  have hh := hμ.2 _ hG
  simp only [normalTest, ContinuousMap.coe_mk, real_inner_smul_right,
    integral_const_mul] at hh ⊢
  simp_rw [divergence_const_smul (hF.differentiable (by simp)).differentiableAt,
    integral_const_mul] at hh
  exact mul_left_cancel₀ (inv_ne_zero hk.ne') hh

end CubicTorus

open scoped RealInnerProductSpace

namespace CubicTorus
open Filter
open scoped Topology

def coordinateMove (i : Fin 3) (f : Cover → ℝ) (t : ℝ) (x : Cover) : Cover :=
  x + (t * f x) • EuclideanSpace.single i 1

def coordinateMoveDeriv (i : Fin 3) (f : Cover → ℝ) (t : ℝ) (x : Cover) :
    Cover →L[ℝ] Cover :=
  ContinuousLinearMap.id ℝ Cover + (fderiv ℝ f x).smulRight (t • EuclideanSpace.single i 1)

def coordinateJacobian (i : Fin 3) (f : Cover → ℝ) (t : ℝ) (x : Cover) : ℝ :=
  1 + t * fderiv ℝ f x (EuclideanSpace.single i 1)

lemma coordinateMove_contDiff (i : Fin 3) {f : Cover → ℝ}
    (hf : ContDiff ℝ (⊤ : ℕ∞) f) (t : ℝ) :
    ContDiff ℝ (⊤ : ℕ∞) (coordinateMove i f t) := by
  unfold coordinateMove
  fun_prop

lemma coordinateMove_hasFDerivAt (i : Fin 3) {f : Cover → ℝ} {point : Cover}
    (hf : DifferentiableAt ℝ f point) (t : ℝ) :
    HasFDerivAt (coordinateMove i f t) (coordinateMoveDeriv i f t point) point := by
  have h₁ : HasFDerivAt (fun y : Cover ↦ y) (ContinuousLinearMap.id ℝ Cover) point :=
    hasFDerivAt_id point
  have h₂ := (hf.hasFDerivAt.const_mul t).smul_const
    (EuclideanSpace.single i (1 : ℝ) : Cover)
  have he : coordinateMoveDeriv i f t point = ContinuousLinearMap.id ℝ Cover +
      (t • fderiv ℝ f point).smulRight (EuclideanSpace.single i (1 : ℝ) : Cover) := by
    ext y j
    simp [coordinateMoveDeriv, mul_comm]
  rw [he]
  exact h₁.add h₂

lemma coordinateMove_periodic (i : Fin 3) {f : Cover → ℝ}
    (hp : ∀ n x, f (x + latticeVector n) = f x) (t : ℝ) (n : Fin 3 → ℤ) (x : Cover) :
    coordinateMove i f t (x + latticeVector n) = coordinateMove i f t x + latticeVector n := by
  simp only [coordinateMove, hp]
  abel

lemma coordinateMove_apply (i j : Fin 3) (f : Cover → ℝ) (t : ℝ) (x : Cover) :
    coordinateMove i f t x j = x j + if i = j then t * f x else 0 := by
  by_cases h : i = j <;> simp [coordinateMove, h, eq_comm]

lemma coordinateMoveDeriv_det (i : Fin 3) (f : Cover → ℝ) (t : ℝ) (x : Cover) :
    (coordinateMoveDeriv i f t x).det = coordinateJacobian i f t x := by
  let B := (EuclideanSpace.basisFun (Fin 3) ℝ).toBasis
  have he : LinearMap.toMatrix B B (coordinateMoveDeriv i f t x).toLinearMap =
      Matrix.of (fun j k ↦ (if j = k then 1 else 0) +
        (if j = i then t * fderiv ℝ f x (EuclideanSpace.single k 1) else 0)) := by
    ext j k
    rw [LinearMap.toMatrix_apply]
    change (EuclideanSpace.basisFun (Fin 3) ℝ).toBasis.repr
      (coordinateMoveDeriv i f t x ((EuclideanSpace.basisFun (Fin 3) ℝ) k)) j = _
    rw [OrthonormalBasis.coe_toBasis_repr_apply, EuclideanSpace.basisFun_repr,
      EuclideanSpace.basisFun_apply]
    by_cases h : j = i <;> simp [coordinateMoveDeriv, h, mul_comm]
  rw [ContinuousLinearMap.det, ← LinearMap.det_toMatrix B, he]
  rw [Matrix.det_fin_three]
  fin_cases i <;> simp [coordinateJacobian]

lemma coordinateMove_injective (i : Fin 3) {f : Cover → ℝ}
    (hf : Differentiable ℝ f) {M : NNReal} (hM : ∀ x, ‖fderiv ℝ f x‖₊ ≤ M)
    {t : ℝ} (ht : |t| * M < 1) : Function.Injective (coordinateMove i f t) := by
  have hLip := lipschitzWith_of_nnnorm_fderiv_le hf hM
  intro x y hxy
  have he : x - y = -(t * (f x - f y)) • EuclideanSpace.single i 1 := by
    calc
      x - y = coordinateMove i f t x - coordinateMove i f t y -
          (t * (f x - f y)) • EuclideanSpace.single i 1 := by
        unfold coordinateMove
        module
      _ = _ := by rw [hxy, sub_self, zero_sub, neg_smul]
  have hn : ‖x - y‖ = |t| * ‖f x - f y‖ := by
    rw [he, norm_smul, norm_neg, Real.norm_eq_abs, abs_mul]
    simp [Real.norm_eq_abs]
  have hh : ‖x - y‖ ≤ |t| * M * ‖x - y‖ := by
    have hz := hLip.norm_sub_le x y
    calc
      ‖x - y‖ = |t| * ‖f x - f y‖ := hn
      _ ≤ |t| * (M * ‖x - y‖) :=
        mul_le_mul_of_nonneg_left hz (abs_nonneg _)
      _ = _ := by ring
  have : ‖x - y‖ = 0 := by nlinarith [norm_nonneg (x - y)]
  exact sub_eq_zero.1 (norm_eq_zero.1 this)

end CubicTorus

namespace CubicTorus
open scoped RealInnerProductSpace

lemma divergence_sub_fields {F G : Cover → Cover} {point : Cover}
    (hF : DifferentiableAt ℝ F point) (hG : DifferentiableAt ℝ G point) :
    divergence (fun y ↦ F y - G y) point = divergence F point - divergence G point := by
  change (∑ i : Fin 3, (fderiv ℝ (F - G) point (EuclideanSpace.single i 1)) i) = _
  rw [fderiv_sub hF hG]
  simp [divergence, Finset.sum_sub_distrib]

lemma linearForm_apply_basis (L : Cover →L[ℝ] ℝ) (v : Cover) :
    L v = ∑ j : Fin 3, v j * L (EuclideanSpace.single j 1) := by
  have hv : (∑ j : Fin 3, v j • EuclideanSpace.single j 1) = v := by
    ext k
    simp [Pi.single_apply]
  conv_lhs => rw [← hv, map_sum]
  simp

lemma divergence_comp_coordinateMove (i : Fin 3) {f : Cover → ℝ} {point : Cover}
    (hf : DifferentiableAt ℝ f point) {G : Cover → Cover} {time : ℝ}
    (hG : DifferentiableAt ℝ G (coordinateMove i f time point)) :
    divergence (fun y ↦ G (coordinateMove i f time y)) point =
      divergence G (coordinateMove i f time point) +
        time * fderiv ℝ f point
          (fderiv ℝ G (coordinateMove i f time point) (EuclideanSpace.single i 1)) := by
  have hm := coordinateMove_hasFDerivAt i hf time
  have hd := (hG.hasFDerivAt.comp point hm).fderiv
  change fderiv ℝ (fun y ↦ G (coordinateMove i f time y)) point = _ at hd
  simp only [divergence, hd,
    coordinateMoveDeriv, ContinuousLinearMap.comp_apply, add_apply,
    ContinuousLinearMap.id_apply, ContinuousLinearMap.smulRight_apply,
    map_add, map_smul, PiLp.add_apply, PiLp.smul_apply, smul_eq_mul,
    Finset.sum_add_distrib]
  congr 1
  rw [linearForm_apply_basis, Finset.mul_sum]
  apply Finset.sum_congr rfl
  intro j _
  ring

def coordinatePullback (i : Fin 3) (f : Cover → ℝ) (t : ℝ) (G : Cover → Cover)
    (x : Cover) : Cover :=
  coordinateJacobian i f t x • G (coordinateMove i f t x) -
    (t * fderiv ℝ f x (G (coordinateMove i f t x))) • EuclideanSpace.single i 1

lemma coordinateJacobian_contDiff (i : Fin 3) {f : Cover → ℝ}
    (hf : ContDiff ℝ (⊤ : ℕ∞) f) (t : ℝ) :
    ContDiff ℝ (⊤ : ℕ∞) (coordinateJacobian i f t) := by
  have hd := hf.fderiv_right (m := (⊤ : ℕ∞)) (by simp)
  unfold coordinateJacobian
  fun_prop

lemma coordinatePullback_contDiff (i : Fin 3) {f : Cover → ℝ}
    (hf : ContDiff ℝ (⊤ : ℕ∞) f) (t : ℝ) {G : Cover → Cover}
    (hG : ContDiff ℝ (⊤ : ℕ∞) G) :
    ContDiff ℝ (⊤ : ℕ∞) (coordinatePullback i f t G) := by
  have hd := hf.fderiv_right (m := (⊤ : ℕ∞)) (by simp)
  have hm := coordinateMove_contDiff i hf t
  have hj := coordinateJacobian_contDiff i hf t
  unfold coordinatePullback
  exact (hj.smul (hG.comp hm)).sub
    ((contDiff_const.mul (hd.clm_apply (hG.comp hm))).smul contDiff_const)

lemma coordinatePullback_periodic (i : Fin 3) {f : Cover → ℝ}
    (hp : ∀ n x, f (x + latticeVector n) = f x) (t : ℝ) {G : Cover → Cover}
    (hG : ∀ n x, G (x + latticeVector n) = G x) (n : Fin 3 → ℤ) (x : Cover) :
    coordinatePullback i f t G (x + latticeVector n) = coordinatePullback i f t G x := by
  simp only [coordinatePullback, coordinateJacobian, fderiv_periodic hp,
    coordinateMove_periodic i hp, hG]

lemma coordinatePullback_divergence (i : Fin 3) {f : Cover → ℝ}
    (hf : ContDiff ℝ (⊤ : ℕ∞) f) (t : ℝ) {G : Cover → Cover}
    (hG : ContDiff ℝ (⊤ : ℕ∞) G) (x : Cover) :
    divergence (coordinatePullback i f t G) x =
      coordinateJacobian i f t x * divergence G (coordinateMove i f t x) := by
  have hfd := (hf.differentiable (by simp)).differentiableAt (x := x)
  have hdf := ((hf.fderiv_right (m := (⊤ : ℕ∞)) (by simp)).differentiable
    (by simp)).differentiableAt (x := x)
  have hm := coordinateMove_hasFDerivAt i hfd t
  have hg := (hG.differentiable (by simp)).differentiableAt (x := coordinateMove i f t x)
  have hu := hg.hasFDerivAt.comp x hm
  have hj := ((hdf.hasFDerivAt.clm_apply (hasFDerivAt_const
    (EuclideanSpace.single i (1 : ℝ) : Cover) x)).const_mul t).const_add 1
  have hb := (hdf.hasFDerivAt.clm_apply hu).const_mul t
  have he := ((hf.contDiffAt (x := x)).isSymmSndFDerivAt (by
    simp only [minSmoothness_of_isRCLikeNormedField]
    change ((2 : ℕ∞) : WithTop ℕ∞) ≤ ((⊤ : ℕ∞) : WithTop ℕ∞)
    exact WithTop.coe_le_coe.mpr le_top))
    (EuclideanSpace.single i 1) (G (coordinateMove i f t x))
  change divergence (fun y ↦ coordinateJacobian i f t y • G (coordinateMove i f t y) -
    (t * fderiv ℝ f y (G (coordinateMove i f t y))) • EuclideanSpace.single i 1) x = _
  have hjf := hj.fderiv
  change fderiv ℝ (coordinateJacobian i f t) x = _ at hjf
  dsimp only [Function.comp_def] at hb
  have hJ : DifferentiableAt ℝ (coordinateJacobian i f t) x := hj.differentiableAt
  have hU : DifferentiableAt ℝ (fun y ↦ G (coordinateMove i f t y)) x := hu.differentiableAt
  have hB : DifferentiableAt ℝ
      (fun y ↦ t * fderiv ℝ f y (G (coordinateMove i f t y))) x := hb.differentiableAt
  have hA : DifferentiableAt ℝ
      (fun y ↦ coordinateJacobian i f t y • G (coordinateMove i f t y)) x := hJ.smul hU
  have hC : DifferentiableAt ℝ
      (fun y ↦ (t * fderiv ℝ f y (G (coordinateMove i f t y))) •
        (EuclideanSpace.single i 1 : Cover)) x := hB.smul_const _
  rw [divergence_sub_fields hA hC,
    divergence_smul_function hJ hU,
    divergence_smul_const hB, inner_gradient_left,
    hjf, hb.fderiv, divergence_comp_coordinateMove i hfd hg]
  simp only [smul_apply, add_apply,
    ContinuousLinearMap.comp_apply, zero_apply,
    ContinuousLinearMap.flip_apply, smul_eq_mul, zero_add,
    coordinateMoveDeriv, ContinuousLinearMap.id_apply, ContinuousLinearMap.smulRight_apply,
    map_add, map_smul, map_zero]
  dsimp only [coordinateJacobian, Function.comp_def]
  rw [← he]
  ring

end CubicTorus

namespace CubicTorus

lemma coordinateJacobian_norm_le (i : Fin 3) {f : Cover → ℝ} {M : ℝ}
    (hM : ∀ x, ‖fderiv ℝ f x‖ ≤ M) (t : ℝ) (x : Cover) :
    ‖coordinateJacobian i f t x‖ ≤ 1 + |t| * M := by
  have hd : ‖fderiv ℝ f x (EuclideanSpace.single i 1)‖ ≤ M := by
    simpa using (ContinuousLinearMap.le_opNorm (fderiv ℝ f x) (EuclideanSpace.single i 1)).trans
      (mul_le_mul_of_nonneg_right (hM x) (norm_nonneg _))
  calc
    _ ≤ ‖(1 : ℝ)‖ + ‖t * fderiv ℝ f x (EuclideanSpace.single i 1)‖ := norm_add_le _ _
    _ ≤ 1 + |t| * M := by
      rw [norm_one, norm_mul, Real.norm_eq_abs t]
      exact add_le_add_right (mul_le_mul_of_nonneg_left hd (abs_nonneg _)) 1

lemma coordinateJacobian_pos (i : Fin 3) {f : Cover → ℝ} {M : ℝ}
    (hM : ∀ x, ‖fderiv ℝ f x‖ ≤ M) {t : ℝ} (ht : |t| * M < 1) (x : Cover) :
    0 < coordinateJacobian i f t x := by
  have hd : |fderiv ℝ f x (EuclideanSpace.single i 1)| ≤ M := by
    simpa [Real.norm_eq_abs] using
      (ContinuousLinearMap.le_opNorm (fderiv ℝ f x) (EuclideanSpace.single i 1)).trans
        (mul_le_mul_of_nonneg_right (hM x) (norm_nonneg _))
  have hb := mul_le_mul_of_nonneg_left hd (abs_nonneg t)
  rw [← abs_mul] at hb
  have := (abs_le.1 hb).1
  unfold coordinateJacobian
  linarith

end CubicTorus
end
end
end

end OAI