Nullius Labs
No. 009● LEAN-VERIFIED2026-11-26

Proved: Randic index is at least second adjacency eigenvalue plus one (conjecture #643)

Proved in Lean 4 with Mathlib. One AI model wrote the proof; a different model, without seeing it, wrote the formal statement; Lean's kernel then accepted a proof of that independent statement, with no unproved steps and only the standard axioms. Machine-checked; not peer reviewed.

Source paper · Credits and what is new

Rerun it yourself: download Combined.lean, then

lake env lean Combined.lean (inside a Lean 4 project with Mathlib)

Credits: what this result builds on, and what is new

Download CREDITS.md
# Credits for entry No. 009: R ≥ λ₂ + 1 for every connected graph

Written 26 November 2026 from the published `PROOF.md` and `Proof.lean`.

## Builds on

- **The conjecture.** Tristan Cazenave, "Lemmas and Conjectures in Spectral Graph Theory",
  arXiv:2611.03879 (4 November 2026). Conjecture 1 (#643), Section 7, drawn from the Duhamel-Cazenave
  corpus of automatically generated conjectures. The paper proves the bipartite case and proposes the
  strengthening m ≥ λ₁(λ₂ + 1), which is the route this proof takes.
- **The main ingredient.** Yinchen Liu, Quanyu Tang and Shengtong Zhang, "The positive and negative
  square-energy conjecture", arXiv:2607.18031: for a connected graph, min(s⁺, s⁻) ≥ n − 1. With
  s⁺ + s⁻ = 2m this gives s⁺ ≤ 2m − n + 1, which is step 2 of the proof. This theorem carries almost
  all of the difficulty.
- **A classical inequality.** O. Favaron, M. Mahéo and J.-F. Saclé: m ≤ λ₁R. Used in step 4.
- **Mathlib**, the Lean 4 mathematical library, by the Mathlib community (Apache 2.0).

## Adapted code

- **Lines 1 to 3969 of `Proof.lean` (about 93% of the file)** are the Lean formalization of the
  square-energy theorem by its authors, taken from
  https://github.com/ShengtongZhang-alt/Sq at revision df80e517f78202298f02f2637a39ff4ad3f6b4c5.
  Copyright (c) 2026 Shengtong Zhang, released under the Apache 2.0 licence. The modules were merged
  into one file and updated to Lean 4.37.0-rc1. The original copyright and licence notices are kept
  in the file.
- **Lines 3975 to 4142 (namespace `Spectral`)**, including the Favaron-Mahéo-Saclé inequality
  `l1_R_ge_m`, are adapted from Tristan Cazenave's Lean archive accompanying arXiv:2611.03879
  (files `SpectralLean/Invariants.lean` and `Empirical/RandicL1.lean`).
  The licence of that archive is not recorded in our file and is still to be confirmed with the author.

## What is new

About 125 lines (4148 to 4272): the bound λ₂ + 1 ≤ n/2, and the observation that the Liu-Tang-Zhang
theorem, one step of completing the square, and the Favaron-Mahéo-Saclé inequality together give
λ₁(λ₂ + 1) ≤ m ≤ λ₁R, hence R ≥ λ₂ + 1. The result is a short consequence of the square-energy
theorem. Nullius Labs did not prove that theorem.

The formal statement the proof was checked against (`Statement.lean`) was written by a second AI
model that had not seen the proof.

## Prior work

The search for an existing proof was limited: on 26 November 2026 the arXiv page for 2611.03879
listed only version 1, with no note of a proof, and one web search for the inequality found no
published proof. This is not an exhaustive literature search, and no mathematician has reviewed the
result. If you know of an earlier proof, please tell us and this page will be corrected.

Statement, as tested

Download statement.md
# Randic index is at least second adjacency eigenvalue plus one (conjecture #643)

Source: https://arxiv.org/abs/2611.03879

Let G be a finite simple undirected connected graph with n >= 2 vertices and m edges. Let A be its adjacency matrix, with eigenvalues lambda_1 >= lambda_2 >= ... >= lambda_n (counted with multiplicity), and let R = sum over edges uv of (d_u d_v)^(-1/2) be the Randic index, where d_v is the degree of v. Conjecture (#643 in the Duhamel-Cazenave corpus, listed as unrefuted in Section 'The most interesting unrefuted conjectures'): R >= lambda_2 + 1. The paper proves it for all connected bipartite graphs (so any counterexample is non-bipartite), reports it tested on all connected graphs with at most 10 vertices (including all 11.7 million connected graphs on 10 vertices) and on structured families up to n = 2000, and notes it is asymptotically tight for two copies of K_k joined by one edge (R - lambda_2 - 1 is about 0.012 at k = 80). The authors also propose the stronger statements 2m >= lambda_1^2 + (lambda_2+1)^2 and m >= lambda_1(lambda_2+1), unrefuted up to n = 10.

The proof, in plain language

Download PROOF.md
# Randić index and the second adjacency eigenvalue: R ≥ λ₂ + 1

**Result.** The conjecture is TRUE. `Proof.lean` (Lean 4 + Mathlib, single `import Mathlib`, no `sorry`,
axioms used: `propext`, `Classical.choice`, `Quot.sound`) proves

    theorem nullius_main {n : ℕ} (hn : 2 ≤ n) (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]
        (hc : G.Connected) :
        (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, _⟩ + 1 ≤ Spectral.randic G

**Reading the Lean statement.** Every finite simple graph on n vertices can be labelled by `Fin n`, and
connectivity, spectrum and Randić index do not depend on the labelling. Mathlib's `eigenvalues₀` lists the
eigenvalues of the (real symmetric) adjacency matrix in decreasing order with multiplicity
(`Matrix.IsHermitian.eigenvalues₀_antitone`), so index 0 is λ₁ and index 1 is λ₂. `Spectral.randic G` is
the sum over the unordered edges uv of G, each once, of 1/√(d_u d_v).

## The proof

Let G be connected with n ≥ 2 vertices, m edges, adjacency matrix A, Randić index R.
Write L = λ₁ and t = max(λ₂, 0). The proof gives the stronger bound L(t+1) ≤ m.

1. **λ₂ + 1 ≤ n/2** (`RandicSecondBound.randic_second_bound`; connectivity not needed).
   In the span of orthonormal eigenvectors for λ₁ and λ₂ pick a nonzero vector x whose coordinates sum to
   zero (possible since the span has dimension two). Its Rayleigh quotient is at least λ₂. With J the
   all-ones matrix, every entry of 2(A+I) − J is ±1 and Jx = 0, so
   2 xᵀ(A+I)x ≤ Σ_{i,j} |x_i x_j| ≤ ½ Σ_{i,j} (x_i² + x_j²) = n‖x‖².
   Dividing by 2‖x‖² gives λ₂ + 1 ≤ n/2. Since n ≥ 2 the same bound holds for t: 2t + 1 ≤ n − 1.

2. **Positive square energy: s⁺ := Σ_i max(λ_i, 0)² ≤ 2m − n + 1 for connected G**
   (`SquareEnergy.positiveSquareEnergy_le_graphQ`). This is the theorem of Liu, Tang and Zhang,
   "The positive and negative square-energy conjecture", arXiv:2607.18031 (min(s⁺, s⁻) ≥ n − 1 for
   connected graphs, together with s⁺ + s⁻ = tr A² = 2m). The Lean development in `Proof.lean`
   (namespace `SquareEnergy`, an induction over cut vertices / vertex deletion on a sparse
   matrix inequality) is adapted from the authors' formalization
   github.com/ShengtongZhang-alt/Sq at revision df80e517 (Apache 2.0), merged into one file.
   Because the two largest eigenvalues contribute L² and t² to s⁺ (L > 0 as G has an edge):
   L² + t² ≤ 2m − n + 1.

3. **Complete the square.** L² + (t+1)² = (L² + t²) + (2t+1) ≤ (2m − n + 1) + (n − 1) = 2m.
   Since (L − (t+1))² ≥ 0, this gives 2L(t+1) ≤ L² + (t+1)² ≤ 2m, i.e. L(t+1) ≤ m.

4. **Favaron–Mahéo–Saclé: m ≤ λ₁ R** (`Spectral.l1_R_ge_m`, adapted from Cazenave's Lean archive
   accompanying arXiv:2611.03879). For each edge uv let w_uv = √(d_u d_v) > 0. The vector
   y_u = √d_u has ‖y‖² = 2m and yᵀAy = 2 Σ_{uv∈E} w_uv, so the Rayleigh quotient gives
   Σ w_uv ≤ mL. Summing 2 ≤ w_uv/L + L/w_uv over the edges gives 2m ≤ m + LR.

5. **Conclude.** L(t+1) ≤ m ≤ LR and L > 0, so λ₂ + 1 ≤ t + 1 ≤ R. ∎

## Remarks

- Connectivity is used only in step 2 (and it is necessary: for two disjoint K_k the inequality of step 3
  fails by exactly 1).
- The same argument proves the paper's stronger statements m ≥ λ₁(λ₂+1) (always, since λ₂+1 ≤ t+1 and
  λ₁ > 0) and 2m ≥ λ₁² + (λ₂+1)² whenever λ₂ ≥ 0; these are not formalized as separate theorems.
- Checked with: `cd /opt/nullius/lean_project && lake env lean Proof.lean` → exit 0, two style-linter
  warnings (`letI`/`haveI`), no errors; `#print axioms nullius_main` → [propext, Classical.choice, Quot.sound].

Formal statement, written independently of the proof

Download Statement.lean
import Mathlib

open scoped Classical in
def NulliusClaim : Prop :=
  ∀ (V : Type*) [Fintype V] (G : SimpleGraph V) (hn : 2 ≤ Fintype.card V),
    G.Connected →
      let lambda₂ := (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, hn⟩
      let R := ∑ e ∈ G.edgeFinset, (Real.sqrt (↑((e.map (fun v => G.degree v)).mul) : ℝ))⁻¹
      lambda₂ + 1 ≤ R

How the formal statement matches the conjecture

Download FORMAL.md
# Conjecture 643

1. **Graph and vertex count.** `∀ (V : Type*) [Fintype V] (G : SimpleGraph V)` ranges over every finite vertex type and every simple undirected graph on it. Mathlib's `SimpleGraph` has symmetric, irreflexive adjacency. The paper's $n$ is `Fintype.card V`, so `hn : 2 ≤ Fintype.card V` imposes its lower bound. `G.Connected →` restricts the assertion to connected graphs. The local classical scope supplies decidability for the finite graph operations. [Paper, §1](https://arxiv.org/html/2611.03879v1#S1)

2. **Second adjacency eigenvalue.** `G.isHermitian_adjMatrix ℝ` supplies Mathlib's Hermitian witness for the real adjacency matrix `G.adjMatrix ℝ`. Its `eigenvalues₀` lists the real eigenvalues in decreasing order, allowing ties. Mathlib's `Matrix.IsHermitian.sort_roots_charpoly_eq_eigenvalues₀` identifies this list with the sorted roots of the characteristic polynomial, so it counts algebraic multiplicities. Lean indexes from zero, making `⟨1, hn⟩` the second position. The bound `hn` supplies exactly the required fact that the index is less than the vertex count.

3. **Randić index.** `G.edgeFinset` contains each unordered edge once. Its cardinality is the paper's $m$, which is determined by the graph. For an edge with endpoints $u$ and $v$, `e.map (fun v => G.degree v)` gives the unordered pair of endpoint degrees, and `.mul` gives their product. The cast to `ℝ`, followed by `Real.sqrt` and inversion, gives $1/\sqrt{d_u d_v}$. Summing these weights gives $R$. [Paper, §1](https://arxiv.org/html/2611.03879v1#S1)

4. **Conclusion.** `DIRECTION.txt` says `TRUE`, so `NulliusClaim` states `lambda₂ + 1 ≤ R` for every graph satisfying the hypotheses above. This is the inequality in Conjecture 1 (#643). [Paper, §7](https://arxiv.org/html/2611.03879v1#S7)
import Mathlib

/- The SquareEnergy development is adapted from Yinchen Liu, Quanyu Tang and Shengtong Zhang,
   https://github.com/ShengtongZhang-alt/Sq/tree/df80e517f78202298f02f2637a39ff4ad3f6b4c5 .
   The modules are combined here and updated to Lean 4.37.0-rc1. -/

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# Square-energy definitions

This file defines the adjacency eigenvalues of a finite simple graph and its
positive and negative square energies. Eigenvalues are indexed by the vertex
type and therefore counted with algebraic multiplicity; the strict sign
filters exclude zero eigenvalues from both energies.
-/

open scoped BigOperators

namespace SquareEnergy

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The adjacency eigenvalues of a finite simple graph, indexed with algebraic
multiplicity by its vertex type. -/
noncomputable def adjacencyEigenvalues
    (G : SimpleGraph V) [DecidableRel G.Adj] : V → ℝ :=
  (G.isHermitian_adjMatrix ℝ).eigenvalues

/-- The sum of the squares of the strictly positive adjacency eigenvalues. -/
noncomputable def positiveSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  ∑ i with 0 < adjacencyEigenvalues G i, (adjacencyEigenvalues G i) ^ 2

/-- The sum of the squares of the strictly negative adjacency eigenvalues. -/
noncomputable def negativeSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  ∑ i with adjacencyEigenvalues G i < 0, (adjacencyEigenvalues G i) ^ 2

end SquareEnergy

end

section


/-!
# Positive and negative square energy

This file fixes the spectral conventions used in the paper.  Eigenvalues are
the real eigenvalues of the real symmetric adjacency matrix, indexed with
algebraic multiplicity by the vertex type.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The positive spectral part of the adjacency matrix. -/
noncomputable def adjacencyPosPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix V V ℝ :=
  (G.isHermitian_adjMatrix ℝ).cfc (fun x ↦ max x 0)

/-- The absolute value of the negative spectral part of the adjacency matrix. -/
noncomputable def adjacencyNegPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix V V ℝ :=
  (G.isHermitian_adjMatrix ℝ).cfc (fun x ↦ max (-x) 0)

/-- The characteristic-polynomial roots are exactly the indexed adjacency
eigenvalues.  Since `Polynomial.roots` is a multiset, this records algebraic
multiplicity. -/
lemma roots_charpoly_adjMatrix_eq_adjacencyEigenvalues
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    (G.adjMatrix ℝ).charpoly.roots =
      Multiset.map (adjacencyEigenvalues G) Finset.univ.val := by
  simpa [adjacencyEigenvalues, Function.comp_def] using
    (G.isHermitian_adjMatrix ℝ).roots_charpoly_eq_eigenvalues

lemma positiveSquareEnergy_nonneg (G : SimpleGraph V) [DecidableRel G.Adj] :
    0 ≤ positiveSquareEnergy G := by
  classical
  exact Finset.sum_nonneg fun _ _ ↦ sq_nonneg _

lemma negativeSquareEnergy_nonneg (G : SimpleGraph V) [DecidableRel G.Adj] :
    0 ≤ negativeSquareEnergy G := by
  classical
  exact Finset.sum_nonneg fun _ _ ↦ sq_nonneg _

omit [DecidableEq V] in
lemma sum_sq_posPart_eq_filter (f : V → ℝ) :
    (∑ i, (max (f i) 0) ^ 2) = ∑ i with 0 < f i, (f i) ^ 2 := by
  classical
  rw [Finset.sum_filter]
  apply Finset.sum_congr rfl
  intro i _
  by_cases hi : 0 < f i
  · simp [hi, hi.le]
  · have hi' : f i ≤ 0 := le_of_not_gt hi
    simp [hi, hi']

omit [DecidableEq V] in
lemma sum_sq_negPart_eq_filter (f : V → ℝ) :
    (∑ i, (max (-f i) 0) ^ 2) = ∑ i with f i < 0, (f i) ^ 2 := by
  classical
  rw [Finset.sum_filter]
  apply Finset.sum_congr rfl
  intro i _
  by_cases hi : f i < 0
  · have hneg : 0 < -f i := neg_pos.mpr hi
    rw [ite_eq_left hi, max_eq_left hneg.le]
    ring
  · have hi' : 0 ≤ f i := le_of_not_gt hi
    simp [hi, hi']

open scoped MatrixOrder

/-- The explicitly diagonalized positive part agrees with the native CFC
positive part of the adjacency matrix. -/
lemma adjacencyPosPart_eq_posPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyPosPart G = (G.adjMatrix ℝ)⁺ := by
  rw [adjacencyPosPart, CFC.posPart_def, cfcₙ_eq_cfc,
    (G.isHermitian_adjMatrix ℝ).cfc_eq]
  congr 1

/-- The explicitly diagonalized negative part agrees with the native CFC
negative part of the adjacency matrix. -/
lemma adjacencyNegPart_eq_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyNegPart G = (G.adjMatrix ℝ)⁻ := by
  rw [adjacencyNegPart, CFC.negPart_def, cfcₙ_eq_cfc,
    (G.isHermitian_adjMatrix ℝ).cfc_eq]
  congr 1

lemma adjacencyPosPart_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj] :
    (adjacencyPosPart G).PosSemidef := by
  rw [adjacencyPosPart_eq_posPart]
  exact (CFC.posPart_nonneg (G.adjMatrix ℝ)).posSemidef

lemma adjacencyNegPart_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj] :
    (adjacencyNegPart G).PosSemidef := by
  rw [adjacencyNegPart_eq_negPart]
  exact (CFC.negPart_nonneg (G.adjMatrix ℝ)).posSemidef

lemma adjacency_eq_posPart_sub_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    G.adjMatrix ℝ = adjacencyPosPart G - adjacencyNegPart G := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact (CFC.posPart_sub_negPart (G.adjMatrix ℝ)
    (G.isHermitian_adjMatrix ℝ).isSelfAdjoint).symm

lemma adjacencyPosPart_mul_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyPosPart G * adjacencyNegPart G = 0 := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact CFC.posPart_mul_negPart (G.adjMatrix ℝ)

lemma adjacencyNegPart_mul_posPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyNegPart G * adjacencyPosPart G = 0 := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact CFC.negPart_mul_posPart (G.adjMatrix ℝ)

/-- Trace of the finite-dimensional Hermitian functional calculus. -/
lemma trace_hermitianCfc {A : Matrix V V ℝ} (hA : A.IsHermitian) (f : ℝ → ℝ) :
    Matrix.trace (hA.cfc f) = ∑ i, f (hA.eigenvalues i) := by
  rw [Matrix.IsHermitian.cfc, Unitary.conjStarAlgAut_apply,
    Matrix.trace_mul_cycle, Unitary.coe_star_mul_self, Matrix.one_mul,
    Matrix.trace_diagonal]
  simp

/-- The trace of the square of a Hermitian CFC value is the sum of the
corresponding squared scalar values. -/
lemma trace_sq_hermitianCfc {A : Matrix V V ℝ} (hA : A.IsHermitian) (f : ℝ → ℝ) :
    Matrix.trace (hA.cfc f ^ 2) = ∑ i, (f (hA.eigenvalues i)) ^ 2 := by
  have hf : ContinuousOn f (spectrum ℝ A) := by
    rw [continuousOn_iff_continuous_domRestrict]
    fun_prop
  calc
    Matrix.trace (hA.cfc f ^ 2) =
        Matrix.trace (hA.cfc (fun x ↦ f x * f x)) := by
      rw [pow_two, ← hA.cfc_eq f, ← cfc_mul f f A hf hf, hA.cfc_eq]
    _ = ∑ i, f (hA.eigenvalues i) * f (hA.eigenvalues i) :=
      trace_hermitianCfc hA _
    _ = ∑ i, (f (hA.eigenvalues i)) ^ 2 := by
      simp only [pow_two]

lemma trace_sq_adjacencyPosPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (adjacencyPosPart G ^ 2) = positiveSquareEnergy G := by
  rw [adjacencyPosPart, trace_sq_hermitianCfc, sum_sq_posPart_eq_filter]
  rfl

lemma trace_sq_adjacencyNegPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (adjacencyNegPart G ^ 2) = negativeSquareEnergy G := by
  rw [adjacencyNegPart, trace_sq_hermitianCfc, sum_sq_negPart_eq_filter]
  rfl

lemma sq_adjacency_eq_sq_posPart_add_sq_negPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    G.adjMatrix ℝ ^ 2 = adjacencyPosPart G ^ 2 + adjacencyNegPart G ^ 2 := by
  simp only [pow_two]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul, Matrix.mul_sub,
    Matrix.mul_sub, adjacencyPosPart_mul_negPart, adjacencyNegPart_mul_posPart]
  simp

lemma squareEnergies_add_eq_trace_sq_adjacency
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G + negativeSquareEnergy G =
      Matrix.trace (G.adjMatrix ℝ ^ 2) := by
  rw [sq_adjacency_eq_sq_posPart_add_sq_negPart, Matrix.trace_add,
    trace_sq_adjacencyPosPart, trace_sq_adjacencyNegPart]

lemma trace_sq_adjacency_eq_twice_card_edges
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (G.adjMatrix ℝ ^ 2) = (2 : ℝ) * G.edgeFinset.card := by
  simp only [pow_two, Matrix.trace, Matrix.diag_apply,
    G.adjMatrix_mul_self_apply_self]
  exact_mod_cast G.sum_degrees_eq_twice_card_edges

lemma squareEnergies_add_eq_twice_card_edges
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G + negativeSquareEnergy G =
      (2 : ℝ) * G.edgeFinset.card :=
  (squareEnergies_add_eq_trace_sq_adjacency G).trans
    (trace_sq_adjacency_eq_twice_card_edges G)

omit [DecidableEq V] in
lemma exists_pos_of_sum_eq_zero_of_ne_zero (f : V → ℝ)
    (hsum : ∑ i, f i = 0) (hf : f ≠ 0) :
    ∃ i, 0 < f i := by
  classical
  by_contra hpos
  apply hf
  funext i
  have hnonpos : ∀ j, f j ≤ 0 := fun j ↦
    le_of_not_gt fun hj ↦ hpos ⟨j, hj⟩
  exact (Finset.sum_eq_zero_iff_of_nonpos fun j _ ↦ hnonpos j).mp hsum
    i (Finset.mem_univ i)

omit [DecidableEq V] in
lemma exists_neg_of_sum_eq_zero_of_ne_zero (f : V → ℝ)
    (hsum : ∑ i, f i = 0) (hf : f ≠ 0) :
    ∃ i, f i < 0 := by
  classical
  by_contra hneg
  apply hf
  funext i
  have hnonneg : ∀ j, 0 ≤ f j := fun j ↦
    le_of_not_gt fun hj ↦ hneg ⟨j, hj⟩
  exact (Finset.sum_eq_zero_iff_of_nonneg fun j _ ↦ hnonneg j).mp hsum
    i (Finset.mem_univ i)

omit [DecidableEq V] in
lemma sum_sq_pos_filter_pos_of_exists_pos (f : V → ℝ)
    (h : ∃ i, 0 < f i) :
    0 < ∑ i with 0 < f i, (f i) ^ 2 := by
  classical
  apply Finset.sum_pos'
  · intro i _
    exact sq_nonneg (f i)
  · obtain ⟨i, hi⟩ := h
    exact ⟨i, by simp [hi], sq_pos_of_pos hi⟩

omit [DecidableEq V] in
lemma sum_sq_neg_filter_pos_of_exists_neg (f : V → ℝ)
    (h : ∃ i, f i < 0) :
    0 < ∑ i with f i < 0, (f i) ^ 2 := by
  classical
  apply Finset.sum_pos'
  · intro i _
    exact sq_nonneg (f i)
  · obtain ⟨i, hi⟩ := h
    exact ⟨i, by simp [hi], sq_pos_of_neg hi⟩

omit [Fintype V] [DecidableEq V] in
lemma exists_adj_of_connected_nontrivial
    (G : SimpleGraph V) [Nontrivial V]
    (hG : G.Connected) :
    ∃ u v, G.Adj u v := by
  let v : V := Classical.choice (inferInstance : Nonempty V)
  obtain ⟨u, hu⟩ := hG.preconnected.exists_adj_of_nontrivial v
  exact ⟨v, u, hu⟩

omit [Fintype V] [DecidableEq V] in
lemma adjacencyMatrix_ne_zero_of_exists_adj
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (h : ∃ u v, G.Adj u v) :
    G.adjMatrix ℝ ≠ 0 := by
  obtain ⟨u, v, huv⟩ := h
  intro hzero
  have huv_entry := congr_fun (congr_fun hzero u) v
  simp [huv] at huv_entry

omit [Fintype V] [DecidableEq V] in
lemma adjacencyMatrix_ne_zero_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    G.adjMatrix ℝ ≠ 0 :=
  adjacencyMatrix_ne_zero_of_exists_adj G
    (exists_adj_of_connected_nontrivial G hG)

lemma adjacencyEigenvalues_ne_zero_of_adjacencyMatrix_ne_zero
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hA : G.adjMatrix ℝ ≠ 0) :
    adjacencyEigenvalues G ≠ 0 := by
  intro hzero
  apply hA
  apply (G.isHermitian_adjMatrix ℝ).eigenvalues_eq_zero_iff.mp
  simpa only [adjacencyEigenvalues] using hzero

lemma adjacencyEigenvalues_ne_zero_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    adjacencyEigenvalues G ≠ 0 :=
  adjacencyEigenvalues_ne_zero_of_adjacencyMatrix_ne_zero G
    (adjacencyMatrix_ne_zero_of_connected G hG)

lemma sum_adjacencyEigenvalues_eq_zero
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    ∑ i, adjacencyEigenvalues G i = 0 := by
  calc
    ∑ i, adjacencyEigenvalues G i = Matrix.trace (G.adjMatrix ℝ) := by
      simpa [adjacencyEigenvalues] using
        (G.isHermitian_adjMatrix ℝ).trace_eq_sum_eigenvalues.symm
    _ = 0 := G.trace_adjMatrix ℝ

lemma exists_pos_adjacencyEigenvalue_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    ∃ i, 0 < adjacencyEigenvalues G i :=
  exists_pos_of_sum_eq_zero_of_ne_zero (adjacencyEigenvalues G)
    (sum_adjacencyEigenvalues_eq_zero G)
    (adjacencyEigenvalues_ne_zero_of_connected G hG)

lemma exists_neg_adjacencyEigenvalue_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    ∃ i, adjacencyEigenvalues G i < 0 :=
  exists_neg_of_sum_eq_zero_of_ne_zero (adjacencyEigenvalues G)
    (sum_adjacencyEigenvalues_eq_zero G)
    (adjacencyEigenvalues_ne_zero_of_connected G hG)

lemma positiveSquareEnergy_pos_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    0 < positiveSquareEnergy G := by
  exact sum_sq_pos_filter_pos_of_exists_pos (adjacencyEigenvalues G)
    (exists_pos_adjacencyEigenvalue_of_connected G hG)

lemma negativeSquareEnergy_pos_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    0 < negativeSquareEnergy G := by
  exact sum_sq_neg_filter_pos_of_exists_neg (adjacencyEigenvalues G)
    (exists_neg_adjacencyEigenvalue_of_connected G hG)

end SquareEnergy

end

section

/-!
# Basic definitions for the sparse matrix inequality

This file fixes the conventions used by the sparse-matrix part of the
square-energy argument.  In particular, `EntrywiseNonnegative` is an
entrywise condition; it is deliberately not notation from `MatrixOrder`.

The edge sums below are oriented: an undirected edge contributes once from
each endpoint.  Thus the paper's
`4 * (∑ uv ∈ E(G), √(M uv)) ^ 2` is represented by
`edgeSqrtMass G M ^ 2`.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*}

/-- Every entry of `M` is nonnegative.  This is not the Loewner order. -/
def EntrywiseNonnegative (M : Matrix V V ℝ) : Prop :=
  ∀ i j, 0 ≤ M i j

/-- A real matrix which is both positive semidefinite and entrywise nonnegative. -/
def DoublyNonnegative (M : Matrix V V ℝ) : Prop :=
  M.PosSemidef ∧ EntrywiseNonnegative M

/-- The off-diagonal support of `M` is contained in the edge set of `G`. -/
def SupportedOn (G : SimpleGraph V) (M : Matrix V V ℝ) : Prop :=
  ∀ ⦃u v⦄, u ≠ v → ¬G.Adj u v → M u v = 0

namespace EntrywiseNonnegative

lemma add {M N : Matrix V V ℝ} (hM : EntrywiseNonnegative M)
    (hN : EntrywiseNonnegative N) : EntrywiseNonnegative (M + N) :=
  fun i j ↦ add_nonneg (hM i j) (hN i j)

lemma zero : EntrywiseNonnegative (0 : Matrix V V ℝ) := by
  intro i j
  simp

lemma smul {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) {c : ℝ}
    (hc : 0 ≤ c) : EntrywiseNonnegative (c • M) := by
  intro i j
  exact mul_nonneg hc (hM i j)

end EntrywiseNonnegative

namespace DoublyNonnegative

lemma posSemidef {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.PosSemidef :=
  hM.1

lemma entrywise {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    EntrywiseNonnegative M :=
  hM.2

lemma entry_nonneg {M : Matrix V V ℝ} (hM : DoublyNonnegative M) (i j : V) :
    0 ≤ M i j :=
  hM.2 i j

lemma isHermitian {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.IsHermitian :=
  hM.1.isHermitian

lemma isSymm {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.IsSymm := by
  simpa using hM.isHermitian

lemma apply_symm {M : Matrix V V ℝ} (hM : DoublyNonnegative M) (i j : V) :
    M i j = M j i := by
  simpa using (hM.isSymm.apply j i)

end DoublyNonnegative

section Finite

variable [Fintype V]

/-- The graph parameter `2 |E(G)| - |V(G)| + 1`, with no truncation. -/
def graphQ (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  2 * (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1

@[simp]
lemma graphQ_eq (G : SimpleGraph V) [DecidableRel G.Adj] :
    graphQ G =
      2 * (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1 :=
  rfl

/-- A useful separation of `graphQ` into edge count and connected excess. -/
lemma graphQ_eq_card_edges_add_excess (G : SimpleGraph V) [DecidableRel G.Adj] :
    graphQ G =
      (G.edgeFinset.card : ℝ) +
        ((G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1) := by
  simp only [graphQ]
  ring

lemma connected_card_vertices_le_card_edges_add_one
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    (Fintype.card V : ℝ) ≤ (G.edgeFinset.card : ℝ) + 1 := by
  have hNat : Fintype.card V ≤ G.edgeFinset.card + 1 := by
    simpa only [Nat.card_eq_fintype_card, ← G.edgeFinset_card] using
      hG.card_vert_le_card_edgeSet_add_one
  exact_mod_cast hNat

/-- For a connected graph, its edge count is at most `graphQ`. -/
lemma card_edges_le_graphQ (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) :
    (G.edgeFinset.card : ℝ) ≤ graphQ G := by
  have h := connected_card_vertices_le_card_edges_add_one G hG
  simp only [graphQ]
  linarith

/-- The literal (nontruncated) `graphQ` is nonnegative on connected graphs. -/
lemma graphQ_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) :
    0 ≤ graphQ G :=
  (Nat.cast_nonneg G.edgeFinset.card).trans (card_edges_le_graphQ G hG)

/-- The sum of all entries of a matrix. -/
def totalMass (M : Matrix V V ℝ) : ℝ :=
  ∑ i, ∑ j, M i j

lemma totalMass_eq_one_dotProduct_mulVec_one (M : Matrix V V ℝ) :
    totalMass M = (1 : V → ℝ) ⬝ᵥ (M *ᵥ (1 : V → ℝ)) := by
  simp [totalMass, dotProduct, mulVec]

lemma totalMass_add (M N : Matrix V V ℝ) :
    totalMass (M + N) = totalMass M + totalMass N := by
  simp [totalMass, Finset.sum_add_distrib]

lemma totalMass_smul (c : ℝ) (M : Matrix V V ℝ) :
    totalMass (c • M) = c * totalMass M := by
  simp [totalMass, Finset.mul_sum]

lemma totalMass_finset_sum {ι : Type*} (s : Finset ι)
    (M : ι → Matrix V V ℝ) :
    totalMass (∑ k ∈ s, M k) = ∑ k ∈ s, totalMass (M k) := by
  classical
  induction s using Finset.induction_on with
  | empty => simp [totalMass]
  | @insert a s ha ih =>
      simp [ha, totalMass_add, ih]

/-- Positive semidefiniteness makes the total entry mass nonnegative. -/
lemma totalMass_nonneg_of_posSemidef {M : Matrix V V ℝ}
    (hM : M.PosSemidef) : 0 ≤ totalMass M := by
  rw [totalMass_eq_one_dotProduct_mulVec_one]
  simpa using hM.dotProduct_mulVec_nonneg (1 : V → ℝ)

lemma DoublyNonnegative.totalMass_nonneg {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) : 0 ≤ totalMass M :=
  totalMass_nonneg_of_posSemidef hM.posSemidef

/-- The oriented edge-entry mass.  Every undirected edge is counted twice. -/
def edgeMass (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, M u v

/--
The oriented square-root edge mass.  Every undirected edge is counted twice,
so the sparse theorem has the normalization
`edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M`.
-/
def edgeSqrtMass (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, Real.sqrt (M u v)

lemma edgeMass_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) :
    0 ≤ edgeMass G M := by
  exact Finset.sum_nonneg fun u _ ↦
    Finset.sum_nonneg fun v _ ↦ hM u v

lemma edgeSqrtMass_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) :
    0 ≤ edgeSqrtMass G M := by
  exact Finset.sum_nonneg fun u _ ↦
    Finset.sum_nonneg fun v _ ↦ Real.sqrt_nonneg _

lemma edgeMass_congr (G : SimpleGraph V) [DecidableRel G.Adj]
    {M N : Matrix V V ℝ}
    (h : ∀ ⦃u v⦄, G.Adj u v → M u v = N u v) :
    edgeMass G M = edgeMass G N := by
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v hv
  exact h ((G.mem_neighborFinset u v).mp hv)

lemma edgeSqrtMass_congr (G : SimpleGraph V) [DecidableRel G.Adj]
    {M N : Matrix V V ℝ}
    (h : ∀ ⦃u v⦄, G.Adj u v → M u v = N u v) :
    edgeSqrtMass G M = edgeSqrtMass G N := by
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v hv
  rw [h ((G.mem_neighborFinset u v).mp hv)]

end Finite

end

end SquareEnergy

end

section

/-!
# Scalar inequalities for the sparse square-energy argument

This file contains the graph-free real inequalities used in the induction for
the square-energy bound.  In particular, it does not depend on the graph or
matrix modules of this project.
-/

open scoped BigOperators

namespace SquareEnergy

/-- An oriented squared bound is equivalent to its square-root form when the
left side and the radicand are nonnegative. -/
lemma sq_le_mul_iff_le_sqrt_mul {S q T : ℝ} (hS : 0 ≤ S) (hprod : 0 ≤ q * T) :
    S ^ 2 ≤ q * T ↔ S ≤ √(q * T) :=
  (Real.le_sqrt hS hprod).symm

/-- The normalized square-energy bound is equivalent to the square-root bound
used when two inductive pieces are combined. -/
lemma four_mul_sq_le_iff_two_mul_le_sqrt_mul {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) :
    4 * S ^ 2 ≤ q * T ↔ 2 * S ≤ √(q * T) := by
  have htwoS : 0 ≤ 2 * S := by positivity
  rw [show 4 * S ^ 2 = (2 * S) ^ 2 by ring]
  exact (Real.le_sqrt htwoS hprod).symm

/-- Convert a normalized squared square-energy bound to its square-root form. -/
lemma two_mul_le_sqrt_mul_of_four_mul_sq_le {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) (h : 4 * S ^ 2 ≤ q * T) :
    2 * S ≤ √(q * T) :=
  (four_mul_sq_le_iff_two_mul_le_sqrt_mul hS hprod).mp h

/-- Convert a normalized square-root square-energy bound back to squared form. -/
lemma four_mul_sq_le_of_two_mul_le_sqrt_mul {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) (h : 2 * S ≤ √(q * T)) :
    4 * S ^ 2 ≤ q * T :=
  (four_mul_sq_le_iff_two_mul_le_sqrt_mul hS hprod).mpr h

/-- Finite-sum Cauchy--Schwarz in the form used for sums of inductive
square-root bounds. -/
lemma sum_sqrt_mul_le_sqrt_sum_mul_sum {ι : Type*} (s : Finset ι) (a b : ι → ℝ)
    (ha : ∀ i, 0 ≤ a i) (hb : ∀ i, 0 ≤ b i) :
    (∑ i ∈ s, √(a i * b i)) ≤
      √((∑ i ∈ s, a i) * (∑ i ∈ s, b i)) := by
  calc
    (∑ i ∈ s, √(a i * b i)) =
        ∑ i ∈ s, √(a i) * √(b i) := by
      apply Finset.sum_congr rfl
      intro i _
      rw [Real.sqrt_mul (ha i)]
    _ ≤ √(∑ i ∈ s, a i) * √(∑ i ∈ s, b i) :=
      Real.sum_sqrt_mul_sqrt_le s ha hb
    _ = √((∑ i ∈ s, a i) * (∑ i ∈ s, b i)) := by
      rw [Real.sqrt_mul (Finset.sum_nonneg fun i _ ↦ ha i)]

/-- The two-term scalar Cauchy--Schwarz inequality, written with one square
root around each product. -/
lemma sqrt_mul_add_sqrt_mul_le {q₁ q₂ T₁ T₂ : ℝ}
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂) (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂) :
    √(q₁ * T₁) + √(q₂ * T₂) ≤ √((q₁ + q₂) * (T₁ + T₂)) := by
  rw [Real.sqrt_mul hq₁, Real.sqrt_mul hq₂]
  apply Real.le_sqrt_of_sq_le
  nlinarith [Real.sq_sqrt hq₁, Real.sq_sqrt hq₂, Real.sq_sqrt hT₁,
    Real.sq_sqrt hT₂, sq_nonneg (√q₁ * √T₂ - √q₂ * √T₁)]

/-- Combine the normalized square-energy bounds for two nonnegative blocks. -/
lemma four_mul_sq_add_le_of_two_blocks {S₁ S₂ q₁ q₂ T₁ T₂ : ℝ}
    (hS₁ : 0 ≤ S₁) (hS₂ : 0 ≤ S₂)
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂) (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂)
    (h₁ : 4 * S₁ ^ 2 ≤ q₁ * T₁) (h₂ : 4 * S₂ ^ 2 ≤ q₂ * T₂) :
    4 * (S₁ + S₂) ^ 2 ≤ (q₁ + q₂) * (T₁ + T₂) := by
  have hroot₁ : 2 * S₁ ≤ √(q₁ * T₁) :=
    two_mul_le_sqrt_mul_of_four_mul_sq_le hS₁ (mul_nonneg hq₁ hT₁) h₁
  have hroot₂ : 2 * S₂ ≤ √(q₂ * T₂) :=
    two_mul_le_sqrt_mul_of_four_mul_sq_le hS₂ (mul_nonneg hq₂ hT₂) h₂
  apply (four_mul_sq_le_iff_two_mul_le_sqrt_mul
    (add_nonneg hS₁ hS₂) (mul_nonneg (add_nonneg hq₁ hq₂) (add_nonneg hT₁ hT₂))).mpr
  calc
    2 * (S₁ + S₂) = 2 * S₁ + 2 * S₂ := by ring
    _ ≤ √(q₁ * T₁) + √(q₂ * T₂) := add_le_add hroot₁ hroot₂
    _ ≤ √((q₁ + q₂) * (T₁ + T₂)) :=
      sqrt_mul_add_sqrt_mul_le hq₁ hq₂ hT₁ hT₂

/-- Cancel the common positive factor in the squared vertex-deletion estimate
and put the result into the paper's averaged form. -/
lemma averaged_estimate_of_scaled_bound {n q S T d₀ : ℝ} (hn : 2 < n)
    (hscaled :
      (2 * (n - 2) * S) ^ 2 ≤
        ((n - 2) * (q - 1)) * ((n - 2) * T + d₀)) :
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hfirst :
      (n - 2) * (4 * S ^ 2) ≤ (q - 1) * ((n - 2) * T + d₀) := by
    refine (mul_le_mul_iff_right₀ hn₂).mp ?_
    calc
      (n - 2) * ((n - 2) * (4 * S ^ 2)) =
          (2 * (n - 2) * S) ^ 2 := by ring
      _ ≤ ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) := hscaled
      _ = (n - 2) * ((q - 1) * ((n - 2) * T + d₀)) := by ring
  have hcancel :
      (n - 2) * ((q - 1) / (n - 2)) = q - 1 := by
    calc
      (n - 2) * ((q - 1) / (n - 2)) =
          (q - 1) / (n - 2) * (n - 2) := by ring
      _ = q - 1 := div_mul_cancel₀ _ hn₂.ne'
  refine (mul_le_mul_iff_right₀ hn₂).mp ?_
  calc
    (n - 2) * (4 * S ^ 2) ≤ (q - 1) * ((n - 2) * T + d₀) := hfirst
    _ = (n - 2) * ((q - 1) * T) + (q - 1) * d₀ := by ring
    _ = (n - 2) * ((q - 1) * T) +
        ((n - 2) * ((q - 1) / (n - 2))) * d₀ := by
      rw [hcancel]
    _ = (n - 2) * ((q - 1) * T) +
        (n - 2) * ((q - 1) / (n - 2) * d₀) := by ring
    _ = (n - 2) * ((q - 1) * T + (q - 1) / (n - 2) * d₀) := by
      rw [mul_add]

/-- Derive the averaged estimate directly from the square-root inequality
obtained after summing the vertex-deletion induction hypotheses. -/
lemma averaged_estimate_of_sqrt_bound {n q S T d₀ : ℝ}
    (hn : 2 < n) (hq : 1 ≤ q) (hS : 0 ≤ S) (hT : 0 ≤ T) (hd₀ : 0 ≤ d₀)
    (hbound :
      2 * (n - 2) * S ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀))) :
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hq₁ : 0 ≤ q - 1 := sub_nonneg.mpr hq
  have htail : 0 ≤ (n - 2) * T + d₀ :=
    add_nonneg (mul_nonneg hn₂.le hT) hd₀
  have hradicand :
      0 ≤ ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) :=
    mul_nonneg (mul_nonneg hn₂.le hq₁) htail
  have hleft : 0 ≤ 2 * (n - 2) * S := by positivity
  have hscaled :
      (2 * (n - 2) * S) ^ 2 ≤
        ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) :=
    (Real.le_sqrt hleft hradicand).mp hbound
  exact averaged_estimate_of_scaled_bound hn hscaled

/-- Cauchy--Schwarz for a flat finite edge sum:
the square of a sum of square roots is at most the number of terms times
their sum. -/
lemma sq_sum_sqrt_le_card_mul_sum {ι : Type*} (s : Finset ι) (a : ι → ℝ)
    (ha : ∀ i ∈ s, 0 ≤ a i) :
    (∑ i ∈ s, √(a i)) ^ 2 ≤ (s.card : ℝ) * ∑ i ∈ s, a i := by
  calc
    (∑ i ∈ s, √(a i)) ^ 2 ≤
        (s.card : ℝ) * ∑ i ∈ s, (√(a i)) ^ 2 :=
      sq_sum_le_card_mul_sum_sq (s := s) (f := fun i ↦ √(a i))
    _ = (s.card : ℝ) * ∑ i ∈ s, a i := by
      congr 1
      apply Finset.sum_congr rfl
      intro i hi
      rw [Real.sq_sqrt (ha i hi)]

/-- The flat finite edge Cauchy--Schwarz estimate with the factor `4` used in
the square-energy theorem. -/
lemma four_mul_sq_sum_sqrt_le_card_mul_sum {ι : Type*}
    (s : Finset ι) (a : ι → ℝ) (ha : ∀ i ∈ s, 0 ≤ a i) :
    4 * (∑ i ∈ s, √(a i)) ^ 2 ≤
      4 * (s.card : ℝ) * ∑ i ∈ s, a i := by
  calc
    4 * (∑ i ∈ s, √(a i)) ^ 2 ≤
        4 * ((s.card : ℝ) * ∑ i ∈ s, a i) :=
      mul_le_mul_of_nonneg_left (sq_sum_sqrt_le_card_mul_sum s a ha) (by positivity)
    _ = 4 * (s.card : ℝ) * ∑ i ∈ s, a i := by ring

/-- Paper Case 1: the edge-count identity, flat estimate, and low-edge-mass
threshold imply the target square-energy bound. -/
lemma paper_case_one {m n q S d₀ w : ℝ}
    (hcount : 4 * m = 2 * q + 2 * (n - 1))
    (hflat : 4 * S ^ 2 ≤ 4 * m * w)
    (hthreshold : 2 * (n - 1) * w ≤ q * d₀) :
    4 * S ^ 2 ≤ q * (d₀ + 2 * w) := by
  calc
    4 * S ^ 2 ≤ 4 * m * w := hflat
    _ = 2 * q * w + 2 * (n - 1) * w := by rw [hcount]; ring
    _ ≤ 2 * q * w + q * d₀ := add_le_add le_rfl hthreshold
    _ = q * (d₀ + 2 * w) := by ring

/-- In Paper Case 2, simplicity bounds the coefficient of `d₀` after the
identity `q - 1 = (n - 2) + 2β` is substituted. -/
lemma paper_case_two_coefficient_le {n q β : ℝ}
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2)) :
    2 * β * (n - 1) ≤ q * (n - 2) := by
  have hq : q = (n - 1) + 2 * β := by linarith
  have hgap : 0 ≤ (n - 1) * (n - 2) - 2 * β := sub_nonneg.mpr hsimple
  rw [hq]
  calc
    2 * β * (n - 1) ≤
        2 * β * (n - 1) + ((n - 1) * (n - 2) - 2 * β) :=
      le_add_of_nonneg_right hgap
    _ = ((n - 1) + 2 * β) * (n - 2) := by ring

/-- The strict Case 2 threshold gives the strict paper bound
`β d₀ < (n - 2) w`; all cancellations use an explicitly positive factor. -/
lemma paper_case_two_beta_mul_d_lt {n q β d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w) :
    β * d₀ < (n - 2) * w := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hn₁ : 0 < n - 1 := by linarith
  have hfactor : 0 < 2 * (n - 1) := mul_pos (by positivity) hn₁
  have hcoefficient :
      2 * β * (n - 1) ≤ q * (n - 2) :=
    paper_case_two_coefficient_le hqβ hsimple
  have hcoefficient_d :
      (2 * β * (n - 1)) * d₀ ≤ (q * (n - 2)) * d₀ :=
    mul_le_mul_of_nonneg_right hcoefficient hd₀
  have hthreshold_scaled :
      (q * d₀) * (n - 2) < (2 * (n - 1) * w) * (n - 2) :=
    mul_lt_mul_of_pos_right hthreshold hn₂
  have hscaled :
      (2 * (n - 1)) * (β * d₀) <
        (2 * (n - 1)) * ((n - 2) * w) := by
    calc
      (2 * (n - 1)) * (β * d₀) = (2 * β * (n - 1)) * d₀ := by ring
      _ ≤ (q * (n - 2)) * d₀ := hcoefficient_d
      _ = (q * d₀) * (n - 2) := by ring
      _ < (2 * (n - 1) * w) * (n - 2) := hthreshold_scaled
      _ = (2 * (n - 1)) * ((n - 2) * w) := by ring
  exact (mul_lt_mul_iff_right₀ hfactor).mp hscaled

/-- The weak Case 2 bound `β d₀ ≤ (n - 2) w` used by the averaged
correction estimate. -/
lemma paper_case_two_beta_mul_d_le {n q β d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w) :
    β * d₀ ≤ (n - 2) * w :=
  (paper_case_two_beta_mul_d_lt hn hd₀ hqβ hsimple hthreshold).le

/-- The Case 2 beta bound controls the correction term in the averaged
estimate by `T = d₀ + 2w`. -/
lemma paper_case_two_averaged_correction_le {n q β d₀ w : ℝ}
    (hn : 2 < n) (hqβ : q - 1 = (n - 2) + 2 * β)
    (hβd : β * d₀ ≤ (n - 2) * w) :
    (q - 1) / (n - 2) * d₀ ≤ d₀ + 2 * w := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have htwice :
      2 * (β * d₀) ≤ 2 * ((n - 2) * w) :=
    mul_le_mul_of_nonneg_left hβd (by positivity)
  have hnumerator :
      (q - 1) * d₀ ≤ (d₀ + 2 * w) * (n - 2) := by
    calc
      (q - 1) * d₀ = ((n - 2) + 2 * β) * d₀ := by rw [hqβ]
      _ = (n - 2) * d₀ + 2 * (β * d₀) := by ring
      _ ≤ (n - 2) * d₀ + 2 * ((n - 2) * w) :=
        add_le_add le_rfl htwice
      _ = (d₀ + 2 * w) * (n - 2) := by ring
  calc
    (q - 1) / (n - 2) * d₀ = ((q - 1) * d₀) / (n - 2) := by ring
    _ ≤ d₀ + 2 * w := (div_le_iff₀ hn₂).mpr hnumerator

/-- Once the averaged correction is at most `T`, the averaged estimate is the
target bound `4S² ≤ qT`. -/
lemma paper_case_two_final_averaged_target {n q S T d₀ : ℝ}
    (haverage :
      4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀)
    (hcorrection : (q - 1) / (n - 2) * d₀ ≤ T) :
    4 * S ^ 2 ≤ q * T := by
  calc
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := haverage
    _ ≤ (q - 1) * T + T := add_le_add le_rfl hcorrection
    _ = q * T := by ring

/-- Paper Case 2 in assembled scalar form: simplicity and the high-edge-mass
threshold turn the averaged estimate into the target bound. -/
lemma paper_case_two {n q β S d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w)
    (haverage :
      4 * S ^ 2 ≤
        (q - 1) * (d₀ + 2 * w) + (q - 1) / (n - 2) * d₀) :
    4 * S ^ 2 ≤ q * (d₀ + 2 * w) := by
  have hβd : β * d₀ ≤ (n - 2) * w :=
    paper_case_two_beta_mul_d_le hn hd₀ hqβ hsimple hthreshold
  have hcorrection :
      (q - 1) / (n - 2) * d₀ ≤ d₀ + 2 * w :=
    paper_case_two_averaged_correction_le hn hqβ hβd
  exact paper_case_two_final_averaged_target haverage hcorrection

/-- Cancel a positive `x` from `x² ≤ qx`; this is the final scalar step in
the spectral square-energy deduction. -/
lemma positive_cancel_sq_le_mul {x q : ℝ} (hx : 0 < x) (h : x ^ 2 ≤ q * x) :
    x ≤ q := by
  apply (mul_le_mul_iff_right₀ hx).mp
  calc
    x * x = x ^ 2 := by ring
    _ ≤ q * x := h
    _ = x * q := by ring

end SquareEnergy

end

section

/-!
# Folding off-diagonal nonedges onto the diagonal

For every unordered nonedge `{u, v}`, the folding operation adds

`M u v • (e_u - e_v) (e_u - e_v)ᵀ`.

The use of `Sym2 V` makes the sum genuinely unordered.  The Hermitian
hypothesis makes the displayed summand independent of which endpoint is
named first.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*} [DecidableEq V]

/-- The vector `e_u - e_v`. -/
def basisDiff (u v : V) : V → ℝ :=
  Pi.single u 1 - Pi.single v 1

@[simp]
lemma basisDiff_self (u : V) : basisDiff u u = 0 := by
  ext i
  simp [basisDiff]

lemma basisDiff_swap (u v : V) : basisDiff v u = -basisDiff u v := by
  ext i
  simp [basisDiff]

@[simp]
lemma basisDiff_apply_left {u v : V} (huv : u ≠ v) :
    basisDiff u v u = 1 := by
  simp [basisDiff, huv]

@[simp]
lemma basisDiff_apply_right {u v : V} (huv : u ≠ v) :
    basisDiff u v v = -1 := by
  simp [basisDiff, huv]

lemma basisDiff_apply_of_ne {u v i : V} (hiu : i ≠ u) (hiv : i ≠ v) :
    basisDiff u v i = 0 := by
  simp [basisDiff, hiu, hiv]

@[simp]
lemma sum_basisDiff [Fintype V] (u v : V) : ∑ i, basisDiff u v i = 0 := by
  simp [basisDiff, Pi.single_apply, Finset.sum_sub_distrib]

/--
The positive-semidefinite rank-one correction belonging to an unordered
pair.  For a Hermitian real matrix, the coefficient `M u v` is independent
of the orientation of the pair.
-/
def rankOneCorrection (M : Matrix V V ℝ) (hM : M.IsHermitian) :
    Sym2 V → Matrix V V ℝ :=
  Sym2.lift
    ⟨fun u v ↦
        M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)),
      by
        intro u v
        have huv : M u v = M v u := by
          simpa using hM.apply v u
        change
          M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) =
            M v u • Matrix.vecMulVec (basisDiff v u) (star (basisDiff v u))
        have hOuter :
            Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) =
              Matrix.vecMulVec (basisDiff v u) (star (basisDiff v u)) := by
          rw [basisDiff_swap u v]
          ext i j
          simp [Matrix.vecMulVec_apply]
        rw [huv, hOuter]⟩

@[simp]
lemma rankOneCorrection_mk (M : Matrix V V ℝ) (hM : M.IsHermitian)
    (u v : V) :
    rankOneCorrection M hM s(u, v) =
      M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) :=
  rfl

section Finite

variable [Fintype V]

/-- The finite set of unordered pairs of distinct, nonadjacent vertices. -/
def nonedgeFinset (G : SimpleGraph V) [DecidableRel G.Adj] : Finset (Sym2 V) :=
  Finset.univ.filter fun e ↦ ¬e.IsDiag ∧ e ∉ G.edgeFinset

@[simp]
lemma mk_mem_nonedgeFinset_iff (G : SimpleGraph V) [DecidableRel G.Adj]
    (u v : V) :
    s(u, v) ∈ nonedgeFinset G ↔ u ≠ v ∧ ¬G.Adj u v := by
  simp [nonedgeFinset, SimpleGraph.mem_edgeFinset]

/-- The sum of all unordered nonedge rank-one corrections. -/
def foldingCorrection (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) (hM : M.IsHermitian) : Matrix V V ℝ :=
  ∑ e ∈ nonedgeFinset G, rankOneCorrection M hM e

/-- Fold every off-diagonal nonedge entry of `M` onto the diagonal. -/
def foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) (hM : M.IsHermitian) : Matrix V V ℝ :=
  M + foldingCorrection G M hM

omit [Fintype V] in
lemma rankOneCorrection_posSemidef [Finite V] {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (hEntry : EntrywiseNonnegative M) (e : Sym2 V) :
    (rankOneCorrection M hM e).PosSemidef := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk]
  exact (Matrix.posSemidef_vecMulVec_self_star (basisDiff u v)).smul
    (hEntry u v)

lemma foldingCorrection_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) :
    (foldingCorrection G M hM).PosSemidef := by
  exact Matrix.posSemidef_sum (nonedgeFinset G) fun e _ ↦
    rankOneCorrection_posSemidef hM hEntry e

lemma foldNonedges_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hPSD : M.PosSemidef)
    (hEntry : EntrywiseNonnegative M) :
    (foldNonedges G M hPSD.isHermitian).PosSemidef :=
  hPSD.add (foldingCorrection_posSemidef G hPSD.isHermitian hEntry)

omit [Fintype V] in
/--
Away from the diagonal, one rank-one correction is nonzero only at the
ordered entries belonging to its own unordered pair.
-/
lemma rankOneCorrection_apply_offdiag {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (e : Sym2 V) {i j : V} (hij : i ≠ j) :
    rankOneCorrection M hM e i j =
      if e = s(i, j) then -M i j else 0 := by
  induction e using Sym2.inductionOn with | hf u v
  have huv : M u v = M v u := by
    simpa using hM.apply v u
  by_cases heq : s(u, v) = s(i, j)
  · rw [ite_eq_left heq]
    rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
    · simp [basisDiff, Matrix.vecMulVec_apply, hij]
    · simp [basisDiff, Matrix.vecMulVec_apply, hij, huv]
  · rw [ite_eq_right heq]
    have hz :
        (i ≠ u ∧ i ≠ v) ∨ (j ≠ u ∧ j ≠ v) := by
      by_cases hi : i = u ∨ i = v
      · by_cases hj : j = u ∨ j = v
        · rcases hi with rfl | rfl <;> rcases hj with rfl | rfl
          · exact (hij rfl).elim
          · exact (heq rfl).elim
          · exact (heq Sym2.eq_swap).elim
          · exact (hij rfl).elim
        · exact Or.inr ⟨fun h ↦ hj (Or.inl h), fun h ↦ hj (Or.inr h)⟩
      · exact Or.inl ⟨fun h ↦ hi (Or.inl h), fun h ↦ hi (Or.inr h)⟩
    rcases hz with hi | hj
    · simp [rankOneCorrection_mk, Matrix.vecMulVec_apply,
        basisDiff_apply_of_ne hi.1 hi.2]
    · simp [rankOneCorrection_mk, Matrix.vecMulVec_apply,
        basisDiff_apply_of_ne hj.1 hj.2]

/-- Entry formula for the whole correction sum away from the diagonal. -/
lemma foldingCorrection_apply_offdiag (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    {i j : V} (hij : i ≠ j) :
    foldingCorrection G M hM i j =
      if G.Adj i j then 0 else -M i j := by
  classical
  by_cases hadj : G.Adj i j
  · have hnot : s(i, j) ∉ nonedgeFinset G := by
      simp [hij, hadj]
    rw [foldingCorrection, Matrix.sum_apply]
    simp_rw [rankOneCorrection_apply_offdiag hM _ hij]
    simp [hnot, hadj]
  · have hmem : s(i, j) ∈ nonedgeFinset G := by
      simp [hij, hadj]
    rw [foldingCorrection, Matrix.sum_apply]
    simp_rw [rankOneCorrection_apply_offdiag hM _ hij]
    simp [hmem, hadj]

/-- Complete off-diagonal entry formula for the folded matrix. -/
lemma foldNonedges_apply_offdiag (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) {i j : V} (hij : i ≠ j) :
    foldNonedges G M hM i j =
      if G.Adj i j then M i j else 0 := by
  rw [foldNonedges, Matrix.add_apply,
    foldingCorrection_apply_offdiag G hM hij]
  by_cases hadj : G.Adj i j <;> simp [hadj]

/-- Folding preserves every edge entry. -/
lemma foldNonedges_apply_of_adj (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) {i j : V}
    (hij : G.Adj i j) :
    foldNonedges G M hM i j = M i j := by
  rw [foldNonedges_apply_offdiag G hM hij.ne]
  simp [hij]

/-- Folding zeros every off-diagonal nonedge entry. -/
lemma foldNonedges_apply_of_nonedge (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    {i j : V} (hne : i ≠ j) (hij : ¬G.Adj i j) :
    foldNonedges G M hM i j = 0 := by
  rw [foldNonedges_apply_offdiag G hM hne]
  simp [hij]

omit [Fintype V] in
lemma rankOneCorrection_apply_diag_nonneg {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (hEntry : EntrywiseNonnegative M)
    (e : Sym2 V) (i : V) :
    0 ≤ rankOneCorrection M hM e i i := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk]
  simp only [Matrix.smul_apply, smul_eq_mul, Matrix.vecMulVec_apply,
    star_trivial]
  exact mul_nonneg (hEntry u v) (mul_self_nonneg (basisDiff u v i))

lemma foldingCorrection_apply_diag_nonneg (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) (i : V) :
    0 ≤ foldingCorrection G M hM i i := by
  rw [foldingCorrection, Matrix.sum_apply]
  exact Finset.sum_nonneg fun e _ ↦
    rankOneCorrection_apply_diag_nonneg hM hEntry e i

/-- Folding preserves entrywise nonnegativity. -/
lemma foldNonedges_entrywiseNonnegative (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) :
    EntrywiseNonnegative (foldNonedges G M hM) := by
  intro i j
  by_cases hij : i = j
  · subst j
    rw [foldNonedges, Matrix.add_apply]
    exact add_nonneg (hEntry i i)
      (foldingCorrection_apply_diag_nonneg G hM hEntry i)
  · rw [foldNonedges_apply_offdiag G hM hij]
    by_cases hadj : G.Adj i j
    · simp [hadj, hEntry i j]
    · simp [hadj]

/-- The folded matrix is supported on the graph. -/
lemma foldNonedges_supportedOn (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    SupportedOn G (foldNonedges G M hM) := by
  intro i j hij hnonedge
  exact foldNonedges_apply_of_nonedge G hM hij hnonedge

/-- Folding a DNN matrix produces a graph-supported DNN matrix. -/
lemma foldNonedges_doublyNonnegative (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) :
    DoublyNonnegative (foldNonedges G M hM.isHermitian) :=
  ⟨foldNonedges_posSemidef G hM.posSemidef hM.entrywise,
    foldNonedges_entrywiseNonnegative G hM.isHermitian hM.entrywise⟩

/-- Each rank-one correction has zero total mass. -/
lemma totalMass_rankOneCorrection {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (e : Sym2 V) :
    totalMass (rankOneCorrection M hM e) = 0 := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk, totalMass_smul]
  change
    M u v *
      totalMass (Matrix.vecMulVec (basisDiff u v) (basisDiff u v)) = 0
  unfold totalMass
  simp only [Matrix.vecMulVec_apply]
  simp_rw [← Finset.mul_sum]
  rw [← Finset.sum_mul, sum_basisDiff]
  simp

lemma totalMass_foldingCorrection (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass (foldingCorrection G M hM) = 0 := by
  rw [foldingCorrection, totalMass_finset_sum]
  simp [totalMass_rankOneCorrection hM]

/-- Folding preserves the sum of all matrix entries. -/
lemma totalMass_foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass (foldNonedges G M hM) = totalMass M := by
  rw [foldNonedges, totalMass_add, totalMass_foldingCorrection]
  simp

/-- Folding preserves the oriented edge-entry mass. -/
lemma edgeMass_foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    edgeMass G (foldNonedges G M hM) = edgeMass G M := by
  apply edgeMass_congr G
  intro i j hij
  exact foldNonedges_apply_of_adj G hM hij

/-- Folding preserves the oriented square-root edge mass. -/
lemma edgeSqrtMass_foldNonedges (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    edgeSqrtMass G (foldNonedges G M hM) = edgeSqrtMass G M := by
  apply edgeSqrtMass_congr G
  intro i j hij
  exact foldNonedges_apply_of_adj G hM hij

omit [DecidableEq V] in
/--
Reduction from the graph-supported sparse inequality to the same inequality
for arbitrary DNN matrices.  The sparse theorem itself is supplied as a
higher-order hypothesis, so this statement is independent of its eventual
name and proof.
-/
theorem supported_sparse_inequality_implies_unrestricted
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hSupported :
      ∀ (N : Matrix V V ℝ),
        DoublyNonnegative N →
        SupportedOn G N →
        edgeSqrtMass G N ^ 2 ≤ graphQ G * totalMass N)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  have hFold :=
    hSupported (foldNonedges G M hM.isHermitian)
      (foldNonedges_doublyNonnegative G hM)
      (foldNonedges_supportedOn G hM.isHermitian)
  rwa [edgeSqrtMass_foldNonedges G hM.isHermitian,
    totalMass_foldNonedges G hM.isHermitian] at hFold

end Finite

end

end SquareEnergy

end

section

/-!
# The cut-vertex induction step

This file proves the cut-vertex branch of the induction for the supported
sparse square-energy inequality.  The convention from `Sq.Sparse.Basic` is
used throughout: `edgeSqrtMass` is an oriented sum, so every unoriented edge
is counted twice.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

universe u

variable {V : Type u}

/-- The graph obtained by deleting `v`.  Its vertices remember that they are
different from `v`. -/
def deleteVertex (G : SimpleGraph V) (v : V) :
    SimpleGraph {x : V // x ≠ v} :=
  G.induce {x | x ≠ v}

@[simp]
lemma deleteVertex_adj (G : SimpleGraph V) (v : V)
    (x y : {x : V // x ≠ v}) :
    (deleteVertex G v).Adj x y ↔ G.Adj x.1 y.1 :=
  Iff.rfl

/-- The vertices of a component of `G - v`, viewed back in `V`. -/
def deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) : Set V :=
  {x | ∃ hx : x ≠ v, (⟨x, hx⟩ : {x : V // x ≠ v}) ∈ C.supp}

@[simp]
lemma mem_deletionComponentVertices_iff (G : SimpleGraph V) (v x : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    x ∈ deletionComponentVertices G v C ↔
      ∃ hx : x ≠ v, (⟨x, hx⟩ : {x : V // x ≠ v}) ∈ C.supp :=
  Iff.rfl

lemma deletionComponentVertices_nonempty (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    (deletionComponentVertices G v C).Nonempty := by
  obtain ⟨x, hx⟩ := C.nonempty_supp
  exact ⟨x.1, x.2, hx⟩

lemma vertex_not_mem_deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    v ∉ deletionComponentVertices G v C := by
  rintro ⟨h, -⟩
  exact h rfl

/-- A component of the deletion, lifted to the original vertex type, still
induces a connected graph. -/
lemma connected_induce_deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    (G.induce (deletionComponentVertices G v C)).Connected := by
  let f :
      C.toSimpleGraph →g G.induce (deletionComponentVertices G v C) := {
    toFun x := ⟨x.1.1, ⟨x.1.2, x.2⟩⟩
    map_rel' := by
      intro x y hxy
      exact hxy
  }
  apply C.connected_toSimpleGraph.map f
  intro x
  rcases x with ⟨x, hx, hC⟩
  exact ⟨⟨⟨x, hx⟩, hC⟩, rfl⟩

/-- In a connected graph, every component left after deleting `v` has a
neighbor of `v`. -/
lemma deletionComponent_has_vertex_neighbor (G : SimpleGraph V) (v : V)
    (hG : G.Connected) (C : (deleteVertex G v).ConnectedComponent) :
    ∃ x ∈ deletionComponentVertices G v C, G.Adj v x := by
  obtain ⟨c, hc⟩ := C.nonempty_supp
  obtain ⟨p, hp⟩ := hG.exists_isPath v c.1
  obtain ⟨w, hvw, q, rfl⟩ := p.exists_eq_cons_of_ne c.2.symm
  have hvq : v ∉ q.support := by
    exact (List.nodup_cons.mp hp.support_nodup).1
  have hall : ∀ x ∈ q.support, x ∈ ({x : V | x ≠ v} : Set V) := by
    intro x hx hxv
    exact hvq (hxv ▸ hx)
  have hreach :
      (deleteVertex G v).Reachable
        (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) c := by
    refine ⟨?_⟩
    simpa [deleteVertex] using q.induce ({x : V | x ≠ v}) hall
  have hwC :
      (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) ∈ C.supp := by
    rw [SimpleGraph.ConnectedComponent.mem_supp_iff]
    calc
      (deleteVertex G v).connectedComponentMk
            (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) =
          (deleteVertex G v).connectedComponentMk c :=
        SimpleGraph.ConnectedComponent.sound hreach
      _ = C := (SimpleGraph.ConnectedComponent.mem_supp_iff C c).mp hc
  exact ⟨w, ⟨hvw.ne.symm, hwC⟩, hvw⟩

/-- Adding the deleted vertex back to one deletion component gives a
connected induced graph. -/
lemma connected_induce_component_insert_vertex (G : SimpleGraph V) (v : V)
    (hG : G.Connected) (C : (deleteVertex G v).ConnectedComponent) :
    (G.induce (deletionComponentVertices G v C ∪ {v})).Connected := by
  obtain ⟨x, hxC, hvx⟩ := deletionComponent_has_vertex_neighbor G v hG C
  have hsingle : (G.induce ({v} : Set V)).Preconnected := by
    intro a b
    have hab : a = b := Subtype.ext (by simpa using a.2.trans b.2.symm)
    subst b
    exact SimpleGraph.Reachable.rfl
  exact G.connected_induce_union
    (connected_induce_deletionComponentVertices G v C).preconnected
    hsingle hxC (by simp) hvx.symm

section FiniteGraph

variable [Fintype V] [DecidableEq V]

/-- Data of the two sides of a cut vertex.  `U` and `W` partition all
vertices other than `v`; the two side graphs overlap only at `v`. -/
structure CutPartition (G : SimpleGraph V) (v : V) where
  U : Finset V
  W : Finset V
  v_not_mem_U : v ∉ U
  v_not_mem_W : v ∉ W
  disjoint : Disjoint U W
  union_eq : U ∪ W = Finset.univ.erase v
  U_nonempty : U.Nonempty
  W_nonempty : W.Nonempty
  no_cross : ∀ ⦃u w⦄, u ∈ U → w ∈ W → ¬G.Adj u w
  left_connected :
    (G.induce (↑(insert v U) : Set V)).Connected
  right_connected :
    (G.induce (↑(insert v W) : Set V)).Connected
  left_card_lt : (insert v U).card < Fintype.card V
  right_card_lt : (insert v W).card < Fintype.card V

namespace CutPartition

variable {G : SimpleGraph V} {v : V}

/-- The vertices of the left side graph. -/
def leftVertices (P : CutPartition G v) : Finset V :=
  insert v P.U

/-- The vertices of the right side graph. -/
def rightVertices (P : CutPartition G v) : Finset V :=
  insert v P.W

/-- The graph induced by the left side and the separator. -/
def leftGraph (P : CutPartition G v) : SimpleGraph {x // x ∈ P.leftVertices} :=
  G.induce (↑P.leftVertices : Set V)

/-- The graph induced by the right side and the separator. -/
def rightGraph (P : CutPartition G v) : SimpleGraph {x // x ∈ P.rightVertices} :=
  G.induce (↑P.rightVertices : Set V)

instance instDecidableRelLeftGraph (P : CutPartition G v)
    [DecidableRel G.Adj] : DecidableRel P.leftGraph.Adj := by
  intro x y
  change Decidable (G.Adj x.1 y.1)
  infer_instance

instance instDecidableRelRightGraph (P : CutPartition G v)
    [DecidableRel G.Adj] : DecidableRel P.rightGraph.Adj := by
  intro x y
  change Decidable (G.Adj x.1 y.1)
  infer_instance

@[simp]
lemma leftVertices_eq (P : CutPartition G v) :
    P.leftVertices = insert v P.U :=
  rfl

@[simp]
lemma rightVertices_eq (P : CutPartition G v) :
    P.rightVertices = insert v P.W :=
  rfl

@[simp]
lemma mem_leftVertices (P : CutPartition G v) (x : V) :
    x ∈ P.leftVertices ↔ x = v ∨ x ∈ P.U := by
  simp [leftVertices]

@[simp]
lemma mem_rightVertices (P : CutPartition G v) (x : V) :
    x ∈ P.rightVertices ↔ x = v ∨ x ∈ P.W := by
  simp [rightVertices]

@[simp]
lemma separator_mem_leftVertices (P : CutPartition G v) :
    v ∈ P.leftVertices := by
  simp

@[simp]
lemma separator_mem_rightVertices (P : CutPartition G v) :
    v ∈ P.rightVertices := by
  simp

lemma leftGraph_connected (P : CutPartition G v) :
    P.leftGraph.Connected :=
  P.left_connected

lemma rightGraph_connected (P : CutPartition G v) :
    P.rightGraph.Connected :=
  P.right_connected

lemma card_left_lt (P : CutPartition G v) :
    Fintype.card {x // x ∈ P.leftVertices} < Fintype.card V := by
  rw [Fintype.card_coe]
  exact P.left_card_lt

lemma card_right_lt (P : CutPartition G v) :
    Fintype.card {x // x ∈ P.rightVertices} < Fintype.card V := by
  rw [Fintype.card_coe]
  exact P.right_card_lt

lemma vertex_mem_left_or_right (P : CutPartition G v) (x : V) :
    x ∈ P.leftVertices ∨ x ∈ P.rightVertices := by
  by_cases hx : x = v
  · simp [hx]
  have hxErase : x ∈ Finset.univ.erase v := by simp [hx]
  rw [← P.union_eq] at hxErase
  rcases Finset.mem_union.mp hxErase with hxU | hxW
  · exact Or.inl (by simp [leftVertices, hxU])
  · exact Or.inr (by simp [rightVertices, hxW])

lemma left_right_inter (P : CutPartition G v) :
    P.leftVertices ∩ P.rightVertices = {v} := by
  ext x
  constructor
  · simp only [Finset.mem_inter, mem_leftVertices, mem_rightVertices,
      Finset.mem_singleton]
    rintro ⟨hxv | hxU, hyv | hxW⟩
    · exact hxv
    · exact hxv
    · exact hyv
    · exact (Finset.disjoint_left.mp P.disjoint hxU hxW).elim
  · intro hx
    have hxv : x = v := Finset.mem_singleton.mp hx
    subst x
    simp

lemma adj_side (P : CutPartition G v) {x y : V} (hxy : G.Adj x y) :
    (x ∈ P.leftVertices ∧ y ∈ P.leftVertices) ∨
      (x ∈ P.rightVertices ∧ y ∈ P.rightVertices) := by
  by_cases hxv : x = v
  · subst x
    rcases P.vertex_mem_left_or_right y with hyL | hyR
    · exact Or.inl ⟨separator_mem_leftVertices P, hyL⟩
    · exact Or.inr ⟨separator_mem_rightVertices P, hyR⟩
  by_cases hyv : y = v
  · subst y
    rcases P.vertex_mem_left_or_right x with hxL | hxR
    · exact Or.inl ⟨hxL, separator_mem_leftVertices P⟩
    · exact Or.inr ⟨hxR, separator_mem_rightVertices P⟩
  have hxErase : x ∈ Finset.univ.erase v := by simp [hxv]
  have hyErase : y ∈ Finset.univ.erase v := by simp [hyv]
  rw [← P.union_eq] at hxErase hyErase
  rcases Finset.mem_union.mp hxErase with hxU | hxW
  · rcases Finset.mem_union.mp hyErase with hyU | hyW
    · exact Or.inl ⟨by simp [leftVertices, hxU], by simp [leftVertices, hyU]⟩
    · exact (P.no_cross hxU hyW hxy).elim
  · rcases Finset.mem_union.mp hyErase with hyU | hyW
    · exact (P.no_cross hyU hxW hxy.symm).elim
    · exact Or.inr ⟨by simp [rightVertices, hxW], by simp [rightVertices, hyW]⟩

end CutPartition

/-- A connected graph whose deletion at `v` is not preconnected admits a
two-sided cut partition. -/
theorem exists_cutPartition_of_not_preconnected_delete
    (G : SimpleGraph V) (v : V) (hG : G.Connected)
    (hdelete : ¬(deleteVertex G v).Preconnected) :
    Nonempty (CutPartition G v) := by
  classical
  change ¬(∀ x y, (deleteVertex G v).Reachable x y) at hdelete
  obtain ⟨a, ha⟩ := not_forall.mp hdelete
  obtain ⟨b, hab⟩ := not_forall.mp ha
  let C : (deleteVertex G v).ConnectedComponent :=
    (deleteVertex G v).connectedComponentMk a
  let U : Finset V := (deletionComponentVertices G v C).toFinset
  let W : Finset V := (Finset.univ.erase v) \ U
  have hvU : v ∉ U := by
    simp [U]
  have hUsub : U ⊆ Finset.univ.erase v := by
    intro x hx
    have hxC : x ∈ deletionComponentVertices G v C := by
      simpa [U] using hx
    exact Finset.mem_erase.mpr
      ⟨(fun hxv ↦ vertex_not_mem_deletionComponentVertices G v C (hxv ▸ hxC)),
        Finset.mem_univ x⟩
  have haU : a.1 ∈ U := by
    simp only [U, Set.mem_toFinset, mem_deletionComponentVertices_iff]
    exact ⟨a.2, by simp [C]⟩
  have hbU : b.1 ∉ U := by
    intro hbU
    have hbC : b ∈ C.supp := by
      have hbC' : b.1 ∈ deletionComponentVertices G v C := by
        simpa [U] using hbU
      rcases hbC' with ⟨hbv, hbC'⟩
      simpa only [Subtype.ext_iff] using hbC'
    have hba : (deleteVertex G v).Reachable b a := by
      apply SimpleGraph.ConnectedComponent.exact
      simpa [C] using
        (SimpleGraph.ConnectedComponent.mem_supp_iff C b).mp hbC
    exact hab hba.symm
  have hbW : b.1 ∈ W := by
    exact Finset.mem_sdiff.mpr
      ⟨Finset.mem_erase.mpr ⟨b.2, Finset.mem_univ _⟩, hbU⟩
  have hUW : U ∪ W = Finset.univ.erase v := by
    exact Finset.union_sdiff_of_subset hUsub
  have hdisj : Disjoint U W := by
    exact Finset.disjoint_sdiff
  have hcross : ∀ ⦃u w⦄, u ∈ U → w ∈ W → ¬G.Adj u w := by
    intro u w hu hw huw
    have huC' : u ∈ deletionComponentVertices G v C := by
      simpa [U] using hu
    rcases huC' with ⟨huv, huC⟩
    have hwv : w ≠ v := (Finset.mem_erase.mp (Finset.mem_sdiff.mp hw).1).1
    have hadj :
        (deleteVertex G v).Adj
          (⟨u, huv⟩ : {x : V // x ≠ v}) ⟨w, hwv⟩ := by
      exact huw
    have hwC :
        (⟨w, hwv⟩ : {x : V // x ≠ v}) ∈ C.supp :=
      (C.mem_supp_congr_adj hadj).mp huC
    have hwU : w ∈ U := by
      simp only [U, Set.mem_toFinset, mem_deletionComponentVertices_iff]
      exact ⟨hwv, hwC⟩
    exact (Finset.mem_sdiff.mp hw).2 hwU
  have hleft :
      (G.induce (↑(insert v U) : Set V)).Connected := by
    have hc := connected_induce_component_insert_vertex G v hG C
    have hset :
        (↑(insert v U) : Set V) =
          deletionComponentVertices G v C ∪ {v} := by
      ext x
      simp [U]
    rw [hset]
    exact hc
  have hright :
      (G.induce (↑(insert v W) : Set V)).Connected := by
    apply G.induce_connected_of_patches v (by simp)
    intro x hx
    by_cases hxv : x = v
    · subst x
      refine ⟨{v}, ?_, by simp, by simp, ?_⟩
      · intro y hy
        have hyv : y = v := by simpa using hy
        subst y
        simp
      · exact SimpleGraph.Reachable.rfl
    · have hxW : x ∈ W := by simpa [hxv] using hx
      let x' : {x : V // x ≠ v} := ⟨x, hxv⟩
      let D : (deleteVertex G v).ConnectedComponent :=
        (deleteVertex G v).connectedComponentMk x'
      have hDne : D ≠ C := by
        intro hDC
        have hxC :
            x ∈ deletionComponentVertices G v C := by
          refine ⟨hxv, ?_⟩
          have hxD : x' ∈ D.supp := by
            exact SimpleGraph.ConnectedComponent.connectedComponentMk_mem
          have hxC' : x' ∈ C.supp := hDC ▸ hxD
          simpa [x'] using hxC'
        have hxU : x ∈ U := by simpa [U] using hxC
        exact (Finset.mem_sdiff.mp hxW).2 hxU
      let s : Set V := deletionComponentVertices G v D ∪ {v}
      have hsv : v ∈ s := by simp [s]
      have hsx : x ∈ s := by
        left
        exact ⟨hxv, by simp [D, x']⟩
      refine ⟨s, ?_, hsv, hsx, ?_⟩
      · intro y hy
        rcases hy with hyD | hyv
        · rcases hyD with ⟨hyv, hyDmem⟩
          have hyNotU : y ∉ U := by
            intro hyU
            have hyC' : y ∈ deletionComponentVertices G v C := by
              simpa [U] using hyU
            rcases hyC' with ⟨hyv', hyCmem⟩
            have hDC : D = C := by
              apply SimpleGraph.ConnectedComponent.eq_of_common_vertex
                (v := (⟨y, hyv⟩ : {x : V // x ≠ v}))
              · exact hyDmem
              · simpa only [Subtype.ext_iff] using hyCmem
            exact hDne hDC
          simp only [Finset.mem_coe, Finset.mem_insert]
          exact Or.inr (Finset.mem_sdiff.mpr
            ⟨Finset.mem_erase.mpr ⟨hyv, Finset.mem_univ _⟩, hyNotU⟩)
        · have : y = v := by simpa using hyv
          simp [this]
      · exact (connected_induce_component_insert_vertex G v hG D).preconnected
          ⟨v, hsv⟩ ⟨x, hsx⟩
  have hVdisj : Disjoint (insert v U) W := by
    rw [Finset.disjoint_left]
    intro x hx hW
    rcases Finset.mem_insert.mp hx with rfl | hxU
    · exact (Finset.mem_erase.mp (Finset.mem_sdiff.mp hW).1).1 rfl
    · exact (Finset.mem_sdiff.mp hW).2 hxU
  have hVunion : insert v U ∪ W = Finset.univ := by
    ext x
    by_cases hxv : x = v
    · simp [hxv]
    · have hxErase : x ∈ Finset.univ.erase v := by simp [hxv]
      rw [← hUW] at hxErase
      simpa [hxv] using hxErase
  have hcard :
      (insert v U).card + W.card = Fintype.card V := by
    rw [← Finset.card_union_of_disjoint hVdisj, hVunion,
      Finset.card_univ]
  have hWpos : 0 < W.card := Finset.card_pos.mpr ⟨b.1, hbW⟩
  have hleftCard : (insert v U).card < Fintype.card V := by
    omega
  have hrightDisj : Disjoint (insert v W) U := by
    rw [Finset.disjoint_left]
    intro x hx hU
    rcases Finset.mem_insert.mp hx with rfl | hxW
    · exact hvU hU
    · exact (Finset.mem_sdiff.mp hxW).2 hU
  have hrightUnion : insert v W ∪ U = Finset.univ := by
    rw [Finset.union_comm]
    simpa [Finset.union_assoc, Finset.union_left_comm,
      Finset.union_comm] using hVunion
  have hcardRight :
      (insert v W).card + U.card = Fintype.card V := by
    rw [← Finset.card_union_of_disjoint hrightDisj, hrightUnion,
      Finset.card_univ]
  have hUpos : 0 < U.card := Finset.card_pos.mpr ⟨a.1, haU⟩
  have hrightCard : (insert v W).card < Fintype.card V := by
    omega
  exact ⟨{
    U := U
    W := W
    v_not_mem_U := hvU
    v_not_mem_W := by
      intro hvW
      exact (Finset.mem_erase.mp (Finset.mem_sdiff.mp hvW).1).1 rfl
    disjoint := hdisj
    union_eq := hUW
    U_nonempty := ⟨a.1, haU⟩
    W_nonempty := ⟨b.1, hbW⟩
    no_cross := hcross
    left_connected := hleft
    right_connected := hright
    left_card_lt := hleftCard
    right_card_lt := hrightCard
  }⟩

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)

lemma left_right_edge_intersections_disjoint [DecidableRel G.Adj] :
    Disjoint
      (G.edgeFinset ∩ P.leftVertices.sym2)
      (G.edgeFinset ∩ P.rightVertices.sym2) := by
  classical
  rw [Finset.disjoint_left]
  intro e heL heR
  induction e using Sym2.inductionOn with
  | _ x y =>
      have heL' := Finset.mem_inter.mp heL
      have heR' := Finset.mem_inter.mp heR
      have hxy : G.Adj x y := by
        simpa [SimpleGraph.mem_edgeFinset] using heL'.1
      have hxL : x ∈ P.leftVertices := (Finset.mk_mem_sym2_iff.mp heL'.2).1
      have hyL : y ∈ P.leftVertices := (Finset.mk_mem_sym2_iff.mp heL'.2).2
      have hxR : x ∈ P.rightVertices := (Finset.mk_mem_sym2_iff.mp heR'.2).1
      have hyR : y ∈ P.rightVertices := (Finset.mk_mem_sym2_iff.mp heR'.2).2
      have hxv : x = v := by
        apply Finset.mem_singleton.mp
        rw [← P.left_right_inter]
        exact Finset.mem_inter.mpr ⟨hxL, hxR⟩
      have hyv : y = v := by
        apply Finset.mem_singleton.mp
        rw [← P.left_right_inter]
        exact Finset.mem_inter.mpr ⟨hyL, hyR⟩
      exact hxy.ne (hxv.trans hyv.symm)

lemma left_right_edge_intersections_union [DecidableRel G.Adj] :
    (G.edgeFinset ∩ P.leftVertices.sym2) ∪
        (G.edgeFinset ∩ P.rightVertices.sym2) =
      G.edgeFinset := by
  classical
  ext e
  induction e using Sym2.inductionOn with
  | _ x y =>
      simp only [Finset.mem_union, Finset.mem_inter,
        Finset.mk_mem_sym2_iff]
      constructor
      · rintro (⟨he, -⟩ | ⟨he, -⟩)
        · exact he
        · exact he
      · intro he
        have hxy : G.Adj x y := by
          simpa [SimpleGraph.mem_edgeFinset] using he
        rcases P.adj_side hxy with hL | hR
        · exact Or.inl ⟨he, hL⟩
        · exact Or.inr ⟨he, hR⟩

/-- The side edge sets partition the edge set of `G`. -/
lemma card_edges_left_add_right [DecidableRel G.Adj] :
    P.leftGraph.edgeFinset.card + P.rightGraph.edgeFinset.card =
      G.edgeFinset.card := by
  classical
  have hleft :
      P.leftGraph.edgeFinset.card =
        (G.edgeFinset ∩ P.leftVertices.sym2).card := by
    have hmap :
        P.leftGraph.edgeFinset.map
            (Function.Embedding.subtype (· ∈ P.leftVertices)).sym2Map =
          G.edgeFinset ∩ P.leftVertices.sym2 := by
      ext e
      induction e using Sym2.inductionOn with
      | _ x y =>
          constructor
          · intro he
            rw [Finset.mem_map] at he
            obtain ⟨a, ha, heq⟩ := he
            induction a using Sym2.inductionOn with
            | _ p q =>
                have hpqEdge : s(p, q) ∈ P.leftGraph.edgeSet :=
                  (P.leftGraph.mem_edgeFinset).mp ha
                have hpqSide : P.leftGraph.Adj p q :=
                  (P.leftGraph.mem_edgeSet).mp hpqEdge
                have hpq : G.Adj p.1 q.1 := by
                  exact hpqSide
                change s(p.1, q.1) = s(x, y) at heq
                rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq,
                      Finset.mk_mem_sym2_iff.mpr ⟨p.2, q.2⟩⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq.symm,
                      Finset.mk_mem_sym2_iff.mpr ⟨q.2, p.2⟩⟩
          · intro he
            have he' := Finset.mem_inter.mp he
            have hxy : G.Adj x y := by
              simpa [SimpleGraph.mem_edgeFinset] using he'.1
            obtain ⟨hx, hy⟩ := Finset.mk_mem_sym2_iff.mp he'.2
            rw [Finset.mem_map]
            refine ⟨s((⟨x, hx⟩ : {z // z ∈ P.leftVertices}),
                (⟨y, hy⟩ : {z // z ∈ P.leftVertices})), ?_, rfl⟩
            apply (P.leftGraph.mem_edgeFinset).mpr
            apply (P.leftGraph.mem_edgeSet).mpr
            exact hxy
    rw [← hmap, Finset.card_map]
  have hright :
      P.rightGraph.edgeFinset.card =
        (G.edgeFinset ∩ P.rightVertices.sym2).card := by
    have hmap :
        P.rightGraph.edgeFinset.map
            (Function.Embedding.subtype (· ∈ P.rightVertices)).sym2Map =
          G.edgeFinset ∩ P.rightVertices.sym2 := by
      ext e
      induction e using Sym2.inductionOn with
      | _ x y =>
          constructor
          · intro he
            rw [Finset.mem_map] at he
            obtain ⟨a, ha, heq⟩ := he
            induction a using Sym2.inductionOn with
            | _ p q =>
                have hpqEdge : s(p, q) ∈ P.rightGraph.edgeSet :=
                  (P.rightGraph.mem_edgeFinset).mp ha
                have hpqSide : P.rightGraph.Adj p q :=
                  (P.rightGraph.mem_edgeSet).mp hpqEdge
                have hpq : G.Adj p.1 q.1 := by
                  exact hpqSide
                change s(p.1, q.1) = s(x, y) at heq
                rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq,
                      Finset.mk_mem_sym2_iff.mpr ⟨p.2, q.2⟩⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq.symm,
                      Finset.mk_mem_sym2_iff.mpr ⟨q.2, p.2⟩⟩
          · intro he
            have he' := Finset.mem_inter.mp he
            have hxy : G.Adj x y := by
              simpa [SimpleGraph.mem_edgeFinset] using he'.1
            obtain ⟨hx, hy⟩ := Finset.mk_mem_sym2_iff.mp he'.2
            rw [Finset.mem_map]
            refine ⟨s((⟨x, hx⟩ : {z // z ∈ P.rightVertices}),
                (⟨y, hy⟩ : {z // z ∈ P.rightVertices})), ?_, rfl⟩
            apply (P.rightGraph.mem_edgeFinset).mpr
            apply (P.rightGraph.mem_edgeSet).mpr
            exact hxy
    rw [← hmap, Finset.card_map]
  rw [hleft, hright, ← Finset.card_union_of_disjoint
    P.left_right_edge_intersections_disjoint,
    P.left_right_edge_intersections_union]

lemma card_vertices_left_add_right :
    Fintype.card {x // x ∈ P.leftVertices} +
        Fintype.card {x // x ∈ P.rightVertices} =
      Fintype.card V + 1 := by
  classical
  rw [Fintype.card_coe, Fintype.card_coe]
  have hparts :
      P.U.card + P.W.card = (Finset.univ.erase v).card := by
    rw [← Finset.card_union_of_disjoint P.disjoint, P.union_eq]
  have herase :
      (Finset.univ.erase v).card = Fintype.card V - 1 :=
    Finset.card_erase_of_mem (Finset.mem_univ v)
  have hVpos : 0 < Fintype.card V := Fintype.card_pos_iff.mpr ⟨v⟩
  simp only [leftVertices, rightVertices,
    Finset.card_insert_of_notMem P.v_not_mem_U,
    Finset.card_insert_of_notMem P.v_not_mem_W]
  omega

/-- The graph parameters of the two sides add to the graph parameter of the
original graph. -/
lemma graphQ_left_add_right [DecidableRel G.Adj] :
    graphQ P.leftGraph + graphQ P.rightGraph = graphQ G := by
  have hE := P.card_edges_left_add_right
  have hV := P.card_vertices_left_add_right
  have hEr :
      (P.leftGraph.edgeFinset.card : ℝ) +
          (P.rightGraph.edgeFinset.card : ℝ) =
        (G.edgeFinset.card : ℝ) := by
    exact_mod_cast hE
  have hVr :
      (Fintype.card {x // x ∈ P.leftVertices} : ℝ) +
          (Fintype.card {x // x ∈ P.rightVertices} : ℝ) =
        (Fintype.card V : ℝ) + 1 := by
    exact_mod_cast hV
  simp only [graphQ]
  linarith

end CutPartition

/-- The finite set of oriented edges. -/
def orientedEdgeFinset (G : SimpleGraph V) [DecidableRel G.Adj] :
    Finset ((_u : V) × V) :=
  Finset.univ.sigma fun u ↦ G.neighborFinset u

omit [DecidableEq V] in
@[simp]
lemma mem_orientedEdgeFinset_iff (G : SimpleGraph V) [DecidableRel G.Adj]
    (u w : V) :
    Sigma.mk u w ∈ orientedEdgeFinset G ↔ G.Adj u w := by
  simp [orientedEdgeFinset]

omit [DecidableEq V] in
lemma edgeSqrtMass_eq_sum_orientedEdgeFinset
    (G : SimpleGraph V) [DecidableRel G.Adj] (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      (orientedEdgeFinset G).sum fun e ↦ √(M e.1 e.2) := by
  exact Finset.sum_sigma' Finset.univ (fun u ↦ G.neighborFinset u)
    (fun u w ↦ √(M u w))

/-- The embedding of ordered pairs of vertices in a finite set back into the
ambient ordered-pair type. -/
def orientedSubtypeEmbedding (s : Finset V) :
    (((_u : {x // x ∈ s}) × {x // x ∈ s}) ↪ ((_u : V) × V)) where
  toFun e := Sigma.mk e.1.1 e.2.1
  inj' := by
    rintro ⟨x, y⟩ ⟨x', y'⟩ h
    change
      (@Sigma.mk V (fun _ : V ↦ V) x.1 y.1) =
        (@Sigma.mk V (fun _ : V ↦ V) x'.1 y'.1) at h
    have hx : x = x' := Subtype.ext (congrArg Sigma.fst h)
    subst x'
    have hy : y = y' := Subtype.ext (by
      exact congrArg (fun e ↦ e.2) h)
    subst y'
    rfl

lemma map_orientedEdgeFinset_induce (G : SimpleGraph V)
    [DecidableRel G.Adj] (s : Finset V) :
    (orientedEdgeFinset (G.induce (↑s : Set V))).map
        (orientedSubtypeEmbedding s) =
      (orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ s ∧ e.2 ∈ s) := by
  classical
  ext e
  rcases e with ⟨x, y⟩
  constructor
  · intro he
    rw [Finset.mem_map] at he
    obtain ⟨⟨x', y'⟩, hxy', heq⟩ := he
    change
      (@Sigma.mk V (fun _ : V ↦ V) x'.1 y'.1) =
        (@Sigma.mk V (fun _ : V ↦ V) x y) at heq
    have hx : x'.1 = x := congrArg Sigma.fst heq
    subst x
    have hy : y'.1 = y := by
      exact congrArg (fun e ↦ e.2) heq
    subst y
    simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff]
    exact ⟨by simpa using hxy', x'.2, y'.2⟩
  · simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff]
    rintro ⟨hxy, hx, hy⟩
    rw [Finset.mem_map]
    refine ⟨Sigma.mk (⟨x, hx⟩ : {z // z ∈ s}) (⟨y, hy⟩ : {z // z ∈ s}), ?_, rfl⟩
    simpa using hxy

/-- Oriented edge sums on an induced graph can be evaluated in the ambient
graph when all induced-edge entries are preserved. -/
lemma edgeSqrtMass_induce_eq_filtered_oriented_sum
    (G : SimpleGraph V) [DecidableRel G.Adj] (s : Finset V)
    (N : Matrix {x // x ∈ s} {x // x ∈ s} ℝ) (M : Matrix V V ℝ)
    (hentry : ∀ ⦃x y : {x // x ∈ s}⦄,
      (G.induce (↑s : Set V)).Adj x y → N x y = M x.1 y.1) :
    edgeSqrtMass (G.induce (↑s : Set V)) N =
      ((orientedEdgeFinset G).filter
          (fun e ↦ e.1 ∈ s ∧ e.2 ∈ s)).sum
        (fun e ↦ √(M e.1 e.2)) := by
  classical
  rw [edgeSqrtMass_eq_sum_orientedEdgeFinset]
  rw [← map_orientedEdgeFinset_induce G s]
  rw [Finset.sum_map]
  apply Finset.sum_congr rfl
  intro e he
  rw [hentry (by simpa [orientedEdgeFinset] using he)]
  rfl

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)

lemma filtered_oriented_edges_disjoint [DecidableRel G.Adj] :
    Disjoint
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.leftVertices ∧ e.2 ∈ P.leftVertices))
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.rightVertices ∧ e.2 ∈ P.rightVertices)) := by
  classical
  rw [Finset.disjoint_left]
  rintro ⟨x, y⟩ hx hy
  simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff] at hx hy
  have hxv : x = v := by
    apply Finset.mem_singleton.mp
    rw [← P.left_right_inter]
    exact Finset.mem_inter.mpr ⟨hx.2.1, hy.2.1⟩
  have hyv : y = v := by
    apply Finset.mem_singleton.mp
    rw [← P.left_right_inter]
    exact Finset.mem_inter.mpr ⟨hx.2.2, hy.2.2⟩
  exact hx.1.ne (hxv.trans hyv.symm)

lemma filtered_oriented_edges_union [DecidableRel G.Adj] :
    ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.leftVertices ∧ e.2 ∈ P.leftVertices)) ∪
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.rightVertices ∧ e.2 ∈ P.rightVertices)) =
      orientedEdgeFinset G := by
  classical
  ext e
  rcases e with ⟨x, y⟩
  simp only [Finset.mem_union, Finset.mem_filter,
    mem_orientedEdgeFinset_iff]
  constructor
  · rintro (⟨hxy, -⟩ | ⟨hxy, -⟩)
    · exact hxy
    · exact hxy
  · intro hxy
    rcases P.adj_side hxy with hL | hR
    · exact Or.inl ⟨hxy, hL⟩
    · exact Or.inr ⟨hxy, hR⟩

/-- The two induced oriented edge sums add to the oriented edge sum of the
original graph, provided their edge entries agree with the original matrix. -/
lemma edgeSqrtMass_left_add_right
    [DecidableRel G.Adj]
    (M₁ : Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ)
    (M₂ : Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ)
    (M : Matrix V V ℝ)
    (h₁ : ∀ ⦃x y⦄, P.leftGraph.Adj x y → M₁ x y = M x.1 y.1)
    (h₂ : ∀ ⦃x y⦄, P.rightGraph.Adj x y → M₂ x y = M x.1 y.1) :
    edgeSqrtMass P.leftGraph M₁ + edgeSqrtMass P.rightGraph M₂ =
      edgeSqrtMass G M := by
  change
    edgeSqrtMass (G.induce (↑P.leftVertices : Set V)) M₁ +
        edgeSqrtMass (G.induce (↑P.rightVertices : Set V)) M₂ =
      edgeSqrtMass G M
  rw [edgeSqrtMass_induce_eq_filtered_oriented_sum G P.leftVertices M₁ M h₁,
    edgeSqrtMass_induce_eq_filtered_oriented_sum G P.rightVertices M₂ M h₂,
    edgeSqrtMass_eq_sum_orientedEdgeFinset]
  rw [← Finset.sum_union P.filtered_oriented_edges_disjoint,
    P.filtered_oriented_edges_union]

end CutPartition

/-- A positive semidefinite real matrix is a Gram matrix in a finite
Euclidean space. -/
lemma exists_eq_gram_of_posSemidef {I : Type*} [Finite I]
    {M : Matrix I I ℝ} (hM : M.PosSemidef) :
    ∃ (m : ℕ) (z : I → EuclideanSpace ℝ (Fin m)),
      M = Matrix.gram ℝ z := by
  obtain ⟨m, a, ha⟩ :=
    Matrix.posSemidef_iff_eq_sum_vecMulVec.mp hM
  refine ⟨m, fun u ↦ WithLp.toLp 2 (fun k ↦ a k u), ?_⟩
  rw [ha]
  ext u w
  simp [Matrix.sum_apply, Matrix.gram_apply, Matrix.vecMulVec_apply,
    EuclideanSpace.inner_eq_star_dotProduct, dotProduct, mul_comm]

/-- The total entry mass of a Gram matrix is the squared norm of the sum of
its representing vectors. -/
lemma totalMass_gram {I E : Type*} [Fintype I]
    [NormedAddCommGroup E] [InnerProductSpace ℝ E] (z : I → E) :
    totalMass (Matrix.gram ℝ z) = ‖∑ i, z i‖ ^ 2 := by
  unfold totalMass
  simp only [Matrix.gram_apply]
  calc
    (∑ i, ∑ j, inner ℝ (z i) (z j)) =
        ∑ i, inner ℝ (z i) (∑ j, z j) := by
      apply Finset.sum_congr rfl
      intro i _
      exact (inner_sum Finset.univ z (z i)).symm
    _ = inner ℝ (∑ i, z i) (∑ j, z j) :=
      (sum_inner Finset.univ z _).symm
    _ = ‖∑ i, z i‖ ^ 2 := real_inner_self_eq_norm_sq _

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)
variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E]

/-- Span of the Gram vectors on the open left side. -/
def leftSpan (z : V → E) : Submodule ℝ E :=
  Submodule.span ℝ (z '' (↑P.U : Set V))

/-- Span of the Gram vectors on the open right side. -/
def rightSpan (z : V → E) : Submodule ℝ E :=
  Submodule.span ℝ (z '' (↑P.W : Set V))

lemma mem_leftSpan (z : V → E) {u : V} (hu : u ∈ P.U) :
    z u ∈ P.leftSpan z := by
  apply Submodule.subset_span
  exact ⟨u, hu, rfl⟩

lemma mem_rightSpan (z : V → E) {w : V} (hw : w ∈ P.W) :
    z w ∈ P.rightSpan z := by
  apply Submodule.subset_span
  exact ⟨w, hw, rfl⟩

/-- Support on `G` makes the spans generated by the two open sides
orthogonal. -/
lemma rightSpan_le_leftSpan_orthogonal
    {M : Matrix V V ℝ} (hSupport : SupportedOn G M)
    (z : V → E) (hgram : M = Matrix.gram ℝ z) :
    P.rightSpan z ≤ (P.leftSpan z)ᗮ := by
  rw [rightSpan, Submodule.span_le]
  rintro y ⟨w, hw, rfl⟩
  apply (Submodule.mem_orthogonal (P.leftSpan z) (z w)).2
  intro x hx
  refine Submodule.span_induction ?_ (by simp) ?_ ?_ hx
  · rintro _ ⟨u, hu, rfl⟩
    have huw : u ≠ w := by
      intro huw
      subst w
      exact (Finset.disjoint_left.mp P.disjoint hu hw)
    have hnon : ¬G.Adj u w := P.no_cross hu hw
    have hzero : M u w = 0 := hSupport huw hnon
    simpa [hgram, Matrix.gram_apply] using hzero
  · intro x y hx hy hix hiy
    simp [inner_add_left, hix, hiy]
  · intro a x hx hix
    simp [inner_smul_left, hix]

/-- The sequential orthogonal-projection decomposition of the separator
Gram vector. -/
structure SeparatorProjection (z : V → E) where
  pU : E
  pW : E
  p0 : E
  separator_eq : z v = pU + pW + p0
  pU_mem_left : pU ∈ P.leftSpan z
  pW_mem_right : pW ∈ P.rightSpan z
  pW_mem_leftOrth : pW ∈ (P.leftSpan z)ᗮ
  pU_mem_rightOrth : pU ∈ (P.rightSpan z)ᗮ
  p0_mem_leftOrth : p0 ∈ (P.leftSpan z)ᗮ
  p0_mem_rightOrth : p0 ∈ (P.rightSpan z)ᗮ
  rightSpan_le_leftOrth : P.rightSpan z ≤ (P.leftSpan z)ᗮ

/-- Construct the separator decomposition by first projecting onto the left
span and then projecting the residual onto the right span. -/
def separatorProjection [FiniteDimensional ℝ E]
    {M : Matrix V V ℝ} (hSupport : SupportedOn G M)
    (z : V → E) (hgram : M = Matrix.gram ℝ z) :
    P.SeparatorProjection z := by
  let L : Submodule ℝ E := P.leftSpan z
  let R : Submodule ℝ E := P.rightSpan z
  let pU : E := L.starProjection (z v)
  let r : E := z v - pU
  let pW : E := R.starProjection r
  let p0 : E := r - pW
  have hpU : pU ∈ L := L.starProjection_apply_mem _
  have hrL : r ∈ Lᗮ := Submodule.sub_starProjection_mem_orthogonal _
  have hpW : pW ∈ R := R.starProjection_apply_mem _
  have hRL : R ≤ Lᗮ :=
    P.rightSpan_le_leftSpan_orthogonal hSupport z hgram
  have hpWL : pW ∈ Lᗮ := by
    exact hRL hpW
  have hp0R : p0 ∈ Rᗮ := Submodule.sub_starProjection_mem_orthogonal _
  have hp0L : p0 ∈ Lᗮ := by
    exact Submodule.sub_mem _ hrL hpWL
  have hpUR : pU ∈ Rᗮ := by
    apply (Submodule.mem_orthogonal R pU).2
    intro y hy
    have hyL : y ∈ Lᗮ := hRL hy
    have hzero : inner ℝ pU y = 0 :=
      (Submodule.mem_orthogonal L y).1 hyL pU hpU
    simpa [real_inner_comm] using hzero
  refine {
    pU := pU
    pW := pW
    p0 := p0
    separator_eq := ?_
    pU_mem_left := hpU
    pW_mem_right := hpW
    pW_mem_leftOrth := hpWL
    pU_mem_rightOrth := hpUR
    p0_mem_leftOrth := hp0L
    p0_mem_rightOrth := hp0R
    rightSpan_le_leftOrth := hRL
  }
  dsimp [p0, r]
  abel

namespace SeparatorProjection

variable {P : CutPartition G v} {z : V → E}

/-- The separator vector assigned to the left side. -/
def leftSeparator (S : P.SeparatorProjection z) : E :=
  S.pU + S.p0

/-- The separator vector assigned to the right side. -/
def rightSeparator (S : P.SeparatorProjection z) : E :=
  S.pW

lemma leftSeparator_add_rightSeparator (S : P.SeparatorProjection z) :
    S.leftSeparator + S.rightSeparator = z v := by
  rw [S.separator_eq]
  simp only [leftSeparator, rightSeparator]
  abel

lemma leftSeparator_inner_eq (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    inner ℝ S.leftSeparator (z u) = inner ℝ (z v) (z u) := by
  have hzu : z u ∈ P.leftSpan z := P.mem_leftSpan z hu
  have hpWzero : inner ℝ S.pW (z u) = 0 :=
    (Submodule.mem_orthogonal' (P.leftSpan z) S.pW).1
      S.pW_mem_leftOrth (z u) hzu
  have hsep : S.leftSeparator = z v - S.pW := by
    rw [S.separator_eq]
    simp only [leftSeparator]
    abel
  rw [hsep, inner_sub_left, hpWzero, sub_zero]

lemma inner_leftSeparator_eq (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    inner ℝ (z u) S.leftSeparator = inner ℝ (z u) (z v) := by
  simpa [real_inner_comm] using S.leftSeparator_inner_eq hu

lemma rightSeparator_inner_eq (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    inner ℝ S.rightSeparator (z w) = inner ℝ (z v) (z w) := by
  have hzw : z w ∈ P.rightSpan z := P.mem_rightSpan z hw
  have hpUzero : inner ℝ S.pU (z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.pU).1
      S.pU_mem_rightOrth (z w) hzw
  have hp0zero : inner ℝ S.p0 (z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.p0).1
      S.p0_mem_rightOrth (z w) hzw
  rw [S.separator_eq]
  simp only [rightSeparator, inner_add_left, hpUzero, hp0zero,
    zero_add, add_zero]

lemma inner_rightSeparator_eq (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    inner ℝ (z w) S.rightSeparator = inner ℝ (z w) (z v) := by
  simpa [real_inner_comm] using S.rightSeparator_inner_eq hw

/-- Gram vectors for the left side. -/
def leftVector (S : P.SeparatorProjection z) :
    {x // x ∈ P.leftVertices} → E :=
  fun x ↦ if x.1 = v then S.leftSeparator else z x.1

/-- Gram vectors for the right side. -/
def rightVector (S : P.SeparatorProjection z) :
    {x // x ∈ P.rightVertices} → E :=
  fun x ↦ if x.1 = v then S.rightSeparator else z x.1

@[simp]
lemma leftVector_separator (S : P.SeparatorProjection z) :
    S.leftVector ⟨v, P.separator_mem_leftVertices⟩ = S.leftSeparator := by
  simp [leftVector]

@[simp]
lemma rightVector_separator (S : P.SeparatorProjection z) :
    S.rightVector ⟨v, P.separator_mem_rightVertices⟩ = S.rightSeparator := by
  simp [rightVector]

lemma leftVector_of_mem_U (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    S.leftVector ⟨u, by simp [CutPartition.leftVertices, hu]⟩ = z u := by
  have huv : u ≠ v := by
    intro huv
    subst u
    exact P.v_not_mem_U hu
  simp [leftVector, huv]

lemma rightVector_of_mem_W (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    S.rightVector ⟨w, by simp [CutPartition.rightVertices, hw]⟩ = z w := by
  have hwv : w ≠ v := by
    intro hwv
    subst w
    exact P.v_not_mem_W hw
  simp [rightVector, hwv]

/-- Left side Gram matrix. -/
def leftMatrix (S : P.SeparatorProjection z) :
    Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ :=
  Matrix.gram ℝ S.leftVector

/-- Right side Gram matrix. -/
def rightMatrix (S : P.SeparatorProjection z) :
    Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ :=
  Matrix.gram ℝ S.rightVector

/-- Every off-diagonal left-side entry is inherited from the original Gram
matrix. -/
lemma leftMatrix_apply_of_ne (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.leftVertices}} (hxy : x ≠ y) :
    S.leftMatrix x y = M x.1 y.1 := by
  rw [leftMatrix, Matrix.gram_apply]
  by_cases hx : x.1 = v
  · by_cases hy : y.1 = v
    · exact (hxy (Subtype.ext (hx.trans hy.symm))).elim
    · have hyU : y.1 ∈ P.U :=
        (P.mem_leftVertices y.1).mp y.2 |>.resolve_left hy
      rw [leftVector, ite_eq_left hx, leftVector, ite_eq_right hy,
        S.leftSeparator_inner_eq hyU, hgram, Matrix.gram_apply]
      simp [hx]
  · by_cases hy : y.1 = v
    · have hxU : x.1 ∈ P.U :=
        (P.mem_leftVertices x.1).mp x.2 |>.resolve_left hx
      rw [leftVector, ite_eq_right hx, leftVector, ite_eq_left hy,
        S.inner_leftSeparator_eq hxU, hgram, Matrix.gram_apply]
      simp [hy]
    · rw [leftVector, ite_eq_right hx, leftVector, ite_eq_right hy,
        hgram, Matrix.gram_apply]

/-- Every off-diagonal right-side entry is inherited from the original Gram
matrix. -/
lemma rightMatrix_apply_of_ne (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.rightVertices}} (hxy : x ≠ y) :
    S.rightMatrix x y = M x.1 y.1 := by
  rw [rightMatrix, Matrix.gram_apply]
  by_cases hx : x.1 = v
  · by_cases hy : y.1 = v
    · exact (hxy (Subtype.ext (hx.trans hy.symm))).elim
    · have hyW : y.1 ∈ P.W :=
        (P.mem_rightVertices y.1).mp y.2 |>.resolve_left hy
      rw [rightVector, ite_eq_left hx, rightVector, ite_eq_right hy,
        S.rightSeparator_inner_eq hyW, hgram, Matrix.gram_apply]
      simp [hx]
  · by_cases hy : y.1 = v
    · have hxW : x.1 ∈ P.W :=
        (P.mem_rightVertices x.1).mp x.2 |>.resolve_left hx
      rw [rightVector, ite_eq_right hx, rightVector, ite_eq_left hy,
        S.inner_rightSeparator_eq hxW, hgram, Matrix.gram_apply]
      simp [hy]
    · rw [rightVector, ite_eq_right hx, rightVector, ite_eq_right hy,
        hgram, Matrix.gram_apply]

lemma leftMatrix_doublyNonnegative (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hgram : M = Matrix.gram ℝ z) :
    DoublyNonnegative S.leftMatrix := by
  refine ⟨Matrix.posSemidef_gram ℝ S.leftVector, ?_⟩
  intro x y
  by_cases hxy : x = y
  · subst y
    exact real_inner_self_nonneg
  · rw [S.leftMatrix_apply_of_ne hgram hxy]
    exact hM.entry_nonneg x.1 y.1

lemma rightMatrix_doublyNonnegative (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hgram : M = Matrix.gram ℝ z) :
    DoublyNonnegative S.rightMatrix := by
  refine ⟨Matrix.posSemidef_gram ℝ S.rightVector, ?_⟩
  intro x y
  by_cases hxy : x = y
  · subst y
    exact real_inner_self_nonneg
  · rw [S.rightMatrix_apply_of_ne hgram hxy]
    exact hM.entry_nonneg x.1 y.1

lemma leftMatrix_supportedOn (S : P.SeparatorProjection z) {M : Matrix V V ℝ}
    (hSupport : SupportedOn G M) (hgram : M = Matrix.gram ℝ z) :
    SupportedOn P.leftGraph S.leftMatrix := by
  intro x y hxy hnon
  rw [S.leftMatrix_apply_of_ne hgram hxy]
  apply hSupport
  · intro hval
    exact hxy (Subtype.ext hval)
  · exact hnon

lemma rightMatrix_supportedOn (S : P.SeparatorProjection z) {M : Matrix V V ℝ}
    (hSupport : SupportedOn G M) (hgram : M = Matrix.gram ℝ z) :
    SupportedOn P.rightGraph S.rightMatrix := by
  intro x y hxy hnon
  rw [S.rightMatrix_apply_of_ne hgram hxy]
  apply hSupport
  · intro hval
    exact hxy (Subtype.ext hval)
  · exact hnon

lemma leftMatrix_apply_of_adj (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.leftVertices}} (hxy : P.leftGraph.Adj x y) :
    S.leftMatrix x y = M x.1 y.1 :=
  S.leftMatrix_apply_of_ne hgram hxy.ne

lemma rightMatrix_apply_of_adj (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.rightVertices}} (hxy : P.rightGraph.Adj x y) :
    S.rightMatrix x y = M x.1 y.1 :=
  S.rightMatrix_apply_of_ne hgram hxy.ne

lemma sum_leftVector (S : P.SeparatorProjection z) :
    ∑ x, S.leftVector x = S.leftSeparator + ∑ u ∈ P.U, z u := by
  let f : V → E := fun x ↦ if x = v then S.leftSeparator else z x
  change (∑ x : {x // x ∈ P.leftVertices}, f x.1) =
    S.leftSeparator + ∑ u ∈ P.U, z u
  rw [← Finset.sum_subtype P.leftVertices (fun _ ↦ Iff.rfl) f]
  rw [leftVertices, Finset.sum_insert P.v_not_mem_U]
  simp only [f, ite_eq_left]
  congr 1
  apply Finset.sum_congr rfl
  intro u hu
  have huv : u ≠ v := by
    intro huv
    subst u
    exact P.v_not_mem_U hu
  simp [huv]

lemma sum_rightVector (S : P.SeparatorProjection z) :
    ∑ x, S.rightVector x = S.rightSeparator + ∑ w ∈ P.W, z w := by
  let f : V → E := fun x ↦ if x = v then S.rightSeparator else z x
  change (∑ x : {x // x ∈ P.rightVertices}, f x.1) =
    S.rightSeparator + ∑ w ∈ P.W, z w
  rw [← Finset.sum_subtype P.rightVertices (fun _ ↦ Iff.rfl) f]
  rw [rightVertices, Finset.sum_insert P.v_not_mem_W]
  simp only [f, ite_eq_left]
  congr 1
  apply Finset.sum_congr rfl
  intro w hw
  have hwv : w ≠ v := by
    intro hwv
    subst w
    exact P.v_not_mem_W hw
  simp [hwv]

lemma sum_original_eq (_S : P.SeparatorProjection z) :
    ∑ x, z x =
      z v + (∑ u ∈ P.U, z u) + ∑ w ∈ P.W, z w := by
  calc
    (∑ x, z x) = z v + ∑ x ∈ Finset.univ.erase v, z x :=
      (Finset.add_sum_erase Finset.univ z (Finset.mem_univ v)).symm
    _ = z v + ∑ x ∈ P.U ∪ P.W, z x := by rw [P.union_eq]
    _ = z v + ((∑ u ∈ P.U, z u) + ∑ w ∈ P.W, z w) := by
      rw [Finset.sum_union P.disjoint]
    _ = _ := by abel

lemma sum_leftVector_add_sum_rightVector (S : P.SeparatorProjection z) :
    (∑ x, S.leftVector x) + (∑ x, S.rightVector x) = ∑ x, z x := by
  rw [S.sum_leftVector, S.sum_rightVector, S.sum_original_eq]
  rw [← S.leftSeparator_add_rightSeparator]
  abel

lemma inner_sum_leftVector_sum_rightVector (S : P.SeparatorProjection z) :
    inner ℝ (∑ x, S.leftVector x) (∑ x, S.rightVector x) = 0 := by
  have hsumU : (∑ u ∈ P.U, z u) ∈ P.leftSpan z :=
    (P.leftSpan z).sum_mem fun u hu ↦ P.mem_leftSpan z hu
  have hsumW : (∑ w ∈ P.W, z w) ∈ P.rightSpan z :=
    (P.rightSpan z).sum_mem fun w hw ↦ P.mem_rightSpan z hw
  have hright :
      S.rightSeparator + (∑ w ∈ P.W, z w) ∈ P.rightSpan z :=
    (P.rightSpan z).add_mem S.pW_mem_right hsumW
  have hpUzero :
      inner ℝ S.pU (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.pU).1
      S.pU_mem_rightOrth _ hright
  have hp0zero :
      inner ℝ S.p0 (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.p0).1
      S.p0_mem_rightOrth _ hright
  have hrightLeftOrth :
      S.rightSeparator + (∑ w ∈ P.W, z w) ∈ (P.leftSpan z)ᗮ := by
    exact (P.leftSpan z)ᗮ.add_mem S.pW_mem_leftOrth
      (S.rightSpan_le_leftOrth hsumW)
  have hsumUzero :
      inner ℝ (∑ u ∈ P.U, z u)
        (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal (P.leftSpan z) _).1
      hrightLeftOrth _ hsumU
  rw [S.sum_leftVector, S.sum_rightVector]
  simp only [leftSeparator, inner_add_left, hpUzero, hp0zero,
    hsumUzero, zero_add]

lemma totalMass_left_add_right (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z) :
    totalMass M = totalMass S.leftMatrix + totalMass S.rightMatrix := by
  rw [hgram, leftMatrix, rightMatrix, totalMass_gram, totalMass_gram,
    totalMass_gram]
  calc
    ‖∑ x, z x‖ ^ 2 =
        ‖(∑ x, S.leftVector x) + ∑ x, S.rightVector x‖ ^ 2 := by
      rw [S.sum_leftVector_add_sum_rightVector]
    _ = ‖∑ x, S.leftVector x‖ ^ 2 +
        ‖∑ x, S.rightVector x‖ ^ 2 := by
      simpa [pow_two] using
        norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero
          (∑ x, S.leftVector x) (∑ x, S.rightVector x)
          S.inner_sum_leftVector_sum_rightVector

lemma edgeSqrtMass_leftMatrix_add_rightMatrix
    [DecidableRel G.Adj] (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z) :
    edgeSqrtMass P.leftGraph S.leftMatrix +
        edgeSqrtMass P.rightGraph S.rightMatrix =
      edgeSqrtMass G M := by
  exact P.edgeSqrtMass_left_add_right S.leftMatrix S.rightMatrix M
    (fun {_ _} hxy ↦ S.leftMatrix_apply_of_adj hgram hxy)
    (fun {_ _} hxy ↦ S.rightMatrix_apply_of_adj hgram hxy)

end SeparatorProjection

/-- The two side matrices supplied by the separator geometry, together with
all properties needed by the induction step. -/
structure OneSeparatorSplit [DecidableRel G.Adj] (M : Matrix V V ℝ) where
  leftMatrix :
    Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ
  rightMatrix :
    Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ
  left_dnn : DoublyNonnegative leftMatrix
  right_dnn : DoublyNonnegative rightMatrix
  left_supported : SupportedOn P.leftGraph leftMatrix
  right_supported : SupportedOn P.rightGraph rightMatrix
  left_edge_entry :
    ∀ ⦃x y⦄, P.leftGraph.Adj x y → leftMatrix x y = M x.1 y.1
  right_edge_entry :
    ∀ ⦃x y⦄, P.rightGraph.Adj x y → rightMatrix x y = M x.1 y.1
  edgeSqrtMass_eq :
    edgeSqrtMass P.leftGraph leftMatrix +
        edgeSqrtMass P.rightGraph rightMatrix =
      edgeSqrtMass G M
  totalMass_eq :
    totalMass M = totalMass leftMatrix + totalMass rightMatrix

/-- Package the Gram/projection construction into the reusable two-block
split used by the cut-vertex induction branch. -/
theorem oneSeparatorSplit [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M) :
    Nonempty (P.OneSeparatorSplit M) := by
  obtain ⟨m, z, hgram⟩ := exists_eq_gram_of_posSemidef hM.posSemidef
  let S : P.SeparatorProjection z :=
    P.separatorProjection hSupport z hgram
  exact ⟨{
    leftMatrix := S.leftMatrix
    rightMatrix := S.rightMatrix
    left_dnn := S.leftMatrix_doublyNonnegative hM hgram
    right_dnn := S.rightMatrix_doublyNonnegative hM hgram
    left_supported := S.leftMatrix_supportedOn hSupport hgram
    right_supported := S.rightMatrix_supportedOn hSupport hgram
    left_edge_entry := fun {_ _} hxy ↦ S.leftMatrix_apply_of_adj hgram hxy
    right_edge_entry := fun {_ _} hxy ↦ S.rightMatrix_apply_of_adj hgram hxy
    edgeSqrtMass_eq := S.edgeSqrtMass_leftMatrix_add_rightMatrix hgram
    totalMass_eq := S.totalMass_left_add_right hgram
  }⟩

end CutPartition

/-- Scalar Cauchy--Schwarz in the normalization of the oriented sparse
inequality. -/
lemma sq_add_le_of_two_blocks {S₁ S₂ q₁ q₂ T₁ T₂ : ℝ}
    (hS₁ : 0 ≤ S₁) (hS₂ : 0 ≤ S₂)
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂)
    (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂)
    (h₁ : S₁ ^ 2 ≤ q₁ * T₁) (h₂ : S₂ ^ 2 ≤ q₂ * T₂) :
    (S₁ + S₂) ^ 2 ≤ (q₁ + q₂) * (T₁ + T₂) := by
  have hroot₁ : S₁ ≤ √(q₁ * T₁) :=
    (sq_le_mul_iff_le_sqrt_mul hS₁ (mul_nonneg hq₁ hT₁)).mp h₁
  have hroot₂ : S₂ ≤ √(q₂ * T₂) :=
    (sq_le_mul_iff_le_sqrt_mul hS₂ (mul_nonneg hq₂ hT₂)).mp h₂
  apply (sq_le_mul_iff_le_sqrt_mul
    (add_nonneg hS₁ hS₂)
    (mul_nonneg (add_nonneg hq₁ hq₂) (add_nonneg hT₁ hT₂))).mpr
  calc
    S₁ + S₂ ≤ √(q₁ * T₁) + √(q₂ * T₂) :=
      add_le_add hroot₁ hroot₂
    _ ≤ √((q₁ + q₂) * (T₁ + T₂)) :=
      sqrt_mul_add_sqrt_mul_le hq₁ hq₂ hT₁ hT₂

/-- Cut-vertex step with hypotheses stated directly for the two side graphs. -/
theorem supported_sparse_bound_of_cutPartition
    {G : SimpleGraph V} [DecidableRel G.Adj] {v : V}
    (P : CutPartition G v) {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) (hSupport : SupportedOn G M)
    (hleft :
      ∀ (N : Matrix {x // x ∈ P.leftVertices}
          {x // x ∈ P.leftVertices} ℝ),
        DoublyNonnegative N →
        SupportedOn P.leftGraph N →
        edgeSqrtMass P.leftGraph N ^ 2 ≤
          graphQ P.leftGraph * totalMass N)
    (hright :
      ∀ (N : Matrix {x // x ∈ P.rightVertices}
          {x // x ∈ P.rightVertices} ℝ),
        DoublyNonnegative N →
        SupportedOn P.rightGraph N →
        edgeSqrtMass P.rightGraph N ^ 2 ≤
          graphQ P.rightGraph * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let S := Classical.choice (P.oneSeparatorSplit hM hSupport)
  have h₁ := hleft S.leftMatrix S.left_dnn S.left_supported
  have h₂ := hright S.rightMatrix S.right_dnn S.right_supported
  have hcombine :
      (edgeSqrtMass P.leftGraph S.leftMatrix +
          edgeSqrtMass P.rightGraph S.rightMatrix) ^ 2 ≤
        (graphQ P.leftGraph + graphQ P.rightGraph) *
          (totalMass S.leftMatrix + totalMass S.rightMatrix) :=
    sq_add_le_of_two_blocks
      (edgeSqrtMass_nonneg P.leftGraph S.leftMatrix)
      (edgeSqrtMass_nonneg P.rightGraph S.rightMatrix)
      (graphQ_nonneg P.leftGraph P.leftGraph_connected)
      (graphQ_nonneg P.rightGraph P.rightGraph_connected)
      S.left_dnn.totalMass_nonneg S.right_dnn.totalMass_nonneg h₁ h₂
  rw [S.edgeSqrtMass_eq, P.graphQ_left_add_right,
    ← S.totalMass_eq] at hcombine
  exact hcombine

omit [DecidableEq V] in
/-- Induction-facing cut-vertex branch.  The induction hypothesis is supplied
for every strictly smaller connected finite graph. -/
theorem supported_sparse_bound_of_disconnected_delete
    (G : SimpleGraph V) [DecidableRel G.Adj] (v : V)
    (hG : G.Connected) (hdelete : ¬(deleteVertex G v).Preconnected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M)
    (hsmaller :
      ∀ {W : Type u} [Fintype W] [DecidableEq W]
        (H : SimpleGraph W) [DecidableRel H.Adj],
        H.Connected →
        Fintype.card W < Fintype.card V →
        ∀ (N : Matrix W W ℝ),
          DoublyNonnegative N →
          SupportedOn H N →
          edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let P := Classical.choice
    (exists_cutPartition_of_not_preconnected_delete G v hG hdelete)
  apply supported_sparse_bound_of_cutPartition P hM hSupport
  · intro N hN hSupp
    exact hsmaller P.leftGraph P.leftGraph_connected P.card_left_lt
      N hN hSupp
  · intro N hN hSupp
    exact hsmaller P.rightGraph P.rightGraph_connected P.card_right_lt
      N hN hSupp

omit [Fintype V] [DecidableEq V] in
/-- A non-connected deletion with a nonempty vertex type is not
preconnected.  The nonemptiness assumption excludes the one-vertex
degeneracy in mathlib's definition of `Connected`. -/
lemma not_preconnected_delete_of_not_connected
    (G : SimpleGraph V) (v : V)
    (hne : Nonempty {x : V // x ≠ v})
    (hdelete : ¬(deleteVertex G v).Connected) :
    ¬(deleteVertex G v).Preconnected := by
  intro hpre
  letI : Nonempty {x : V // x ≠ v} := hne
  exact hdelete ⟨hpre⟩

omit [DecidableEq V] in
/-- Variant of the induction-facing theorem using mathlib's `¬ Connected`
form of disconnectedness. -/
theorem supported_sparse_bound_of_not_connected_delete
    (G : SimpleGraph V) [DecidableRel G.Adj] (v : V)
    (hG : G.Connected)
    (hne : Nonempty {x : V // x ≠ v})
    (hdelete : ¬(deleteVertex G v).Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M)
    (hsmaller :
      ∀ {W : Type u} [Fintype W] [DecidableEq W]
        (H : SimpleGraph W) [DecidableRel H.Adj],
        H.Connected →
        Fintype.card W < Fintype.card V →
        ∀ (N : Matrix W W ℝ),
          DoublyNonnegative N →
          SupportedOn H N →
          edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M :=
  supported_sparse_bound_of_disconnected_delete G v hG
    (not_preconnected_delete_of_not_connected G v hne hdelete)
    hM hSupport hsmaller

end FiniteGraph

end

end SquareEnergy

end

section

/-!
# The no-cut-vertex induction step

This file proves the vertex-deletion branch of the sparse square-energy
induction.  All edge sums use the oriented convention from `Sq.Sparse.Basic`:
every undirected edge occurs in both directions.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*}

/-- The type of vertices left after deleting `v`. -/
abbrev DeletedVertex (v : V) := {u : V // u ≠ v}

instance (G : SimpleGraph V) [DecidableEq V] [DecidableRel G.Adj] (v : V) :
    DecidableRel (deleteVertex G v).Adj := by
  intro i j
  change Decidable (G.Adj i.1 j.1)
  infer_instance

/-- The principal submatrix obtained by deleting one row and column. -/
def deleteMatrix (M : Matrix V V ℝ) (v : V) :
    Matrix (DeletedVertex v) (DeletedVertex v) ℝ :=
  M.submatrix Subtype.val Subtype.val

section BasicDeletion

variable [Fintype V] [DecidableEq V]

@[simp]
lemma card_deletedVertex (v : V) :
    Fintype.card (DeletedVertex v) = Fintype.card V - 1 := by
  change Fintype.card ({v}ᶜ : Set V) = Fintype.card V - 1
  rw [Fintype.card_compl_set]
  simp

lemma card_deletedVertex_lt (v : V) :
    Fintype.card (DeletedVertex v) < Fintype.card V := by
  rw [card_deletedVertex]
  exact Nat.sub_lt (Fintype.card_pos_iff.mpr ⟨v⟩) Nat.zero_lt_one

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_posSemidef {M : Matrix V V ℝ}
    (hM : M.PosSemidef) (v : V) :
    (deleteMatrix M v).PosSemidef := by
  exact hM.submatrix Subtype.val

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_entrywiseNonnegative {M : Matrix V V ℝ}
    (hM : EntrywiseNonnegative M) (v : V) :
    EntrywiseNonnegative (deleteMatrix M v) := by
  intro i j
  exact hM i.1 j.1

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_doublyNonnegative {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) (v : V) :
    DoublyNonnegative (deleteMatrix M v) :=
  ⟨deleteMatrix_posSemidef hM.posSemidef v,
    deleteMatrix_entrywiseNonnegative hM.entrywise v⟩

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_supportedOn (G : SimpleGraph V)
    {M : Matrix V V ℝ} (hM : SupportedOn G M) (v : V) :
    SupportedOn (deleteVertex G v) (deleteMatrix M v) := by
  intro i j hij hnonedge
  apply hM
  · intro h
    apply hij
    exact Subtype.ext h
  · simpa [deleteVertex, SimpleGraph.induce_adj] using hnonedge

end BasicDeletion

section FiniteSumDeletion

variable [Fintype V] [DecidableEq V]

/--
Deleting row and column `v`, then adding back that row and column, counts the
diagonal entry twice.
-/
private lemma sum_delete_add_row_add_column (a : V → V → ℝ) (v : V) :
    (∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1) +
        (∑ j, a v j) + (∑ i, a i v) =
      (∑ i, ∑ j, a i j) + a v v := by
  have houter :
      (∑ i, ∑ j, a i j) =
        (∑ j, a v j) + ∑ i : DeletedVertex v, ∑ j, a i.1 j := by
    exact Fintype.sum_eq_add_sum_subtype_ne (fun i ↦ ∑ j, a i j) v
  have hinner :
      (∑ i : DeletedVertex v, ∑ j, a i.1 j) =
        (∑ i : DeletedVertex v, a i.1 v) +
          ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1 := by
    simp_rw [Fintype.sum_eq_add_sum_subtype_ne (fun j ↦ a _ j) v]
    rw [Finset.sum_add_distrib]
  have hcolumn :
      (∑ i, a i v) =
        a v v + ∑ i : DeletedVertex v, a i.1 v := by
    exact Fintype.sum_eq_add_sum_subtype_ne (fun i ↦ a i v) v
  rw [houter, hinner, hcolumn]
  ring

/-- Generic summed principal-submatrix deletion identity. -/
private lemma sum_delete_submatrices (a : V → V → ℝ) :
    (∑ v, ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1) =
      ((Fintype.card V : ℝ) - 2) * (∑ i, ∑ j, a i j) +
        ∑ i, a i i := by
  let D : V → ℝ :=
    fun v ↦ ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1
  let R : V → ℝ := fun v ↦ ∑ j, a v j
  let C : V → ℝ := fun v ↦ ∑ i, a i v
  let T : ℝ := ∑ i, ∑ j, a i j
  have hsum :
      (∑ v, D v) + (∑ v, R v) + (∑ v, C v) =
        (∑ _v : V, T) + ∑ v, a v v := by
    calc
      (∑ v, D v) + (∑ v, R v) + (∑ v, C v) =
          ∑ v, (D v + R v + C v) := by
            simp only [Finset.sum_add_distrib]
      _ = ∑ v, (T + a v v) := by
            apply Finset.sum_congr rfl
            intro v _
            exact sum_delete_add_row_add_column a v
      _ = (∑ _v : V, T) + ∑ v, a v v := by
            rw [Finset.sum_add_distrib]
  have hrow : (∑ v, R v) = T := rfl
  have hcolumn : (∑ v, C v) = T := by
    dsimp [C, T]
    rw [Finset.sum_comm]
  have hconstant : (∑ _v : V, T) = (Fintype.card V : ℝ) * T := by
    simp
  rw [hrow, hcolumn, hconstant] at hsum
  dsimp only [D, T] at hsum ⊢
  ring_nf at hsum ⊢
  linarith

end FiniteSumDeletion

section EdgeDeletion

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
private lemma edgeSqrtMass_eq_sum_if (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      ∑ u, ∑ w, if G.Adj u w then Real.sqrt (M u w) else 0 := by
  simp [edgeSqrtMass, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter]

omit [DecidableEq V] in
private lemma edgeMass_eq_sum_if (M : Matrix V V ℝ) :
    edgeMass G M =
      ∑ u, ∑ w, if G.Adj u w then M u w else 0 := by
  simp [edgeMass, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter]

/--
Deleting `v` removes both oriented copies of every incident edge: the copy
leaving `v` and the copy entering `v`.
-/
lemma edgeSqrtMass_deleteVertex_add_incident (M : Matrix V V ℝ) (v : V) :
    edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) +
        (∑ w ∈ G.neighborFinset v, Real.sqrt (M v w)) +
        (∑ u ∈ G.neighborFinset v, Real.sqrt (M u v)) =
      edgeSqrtMass G M := by
  let a : V → V → ℝ :=
    fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0
  have h := sum_delete_add_row_add_column a v
  have hdiag : a v v = 0 := by simp [a]
  rw [hdiag, add_zero] at h
  rw [edgeSqrtMass_eq_sum_if (G := deleteVertex G v),
    edgeSqrtMass_eq_sum_if (G := G)]
  simpa [a, deleteVertex, deleteMatrix,
    SimpleGraph.induce_adj, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter, SimpleGraph.adj_comm] using h

/-- Every oriented edge survives all vertex deletions except its two ends. -/
lemma sum_edgeSqrtMass_deleteVertex (M : Matrix V V ℝ) :
    (∑ v, edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)) =
      ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M := by
  let a : V → V → ℝ :=
    fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0
  have h := sum_delete_submatrices a
  have hdiag : (∑ v, a v v) = 0 := by
    apply Finset.sum_eq_zero
    intro v _
    simp [a]
  rw [hdiag, add_zero] at h
  calc
    (∑ v, edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)) =
        ∑ v, ∑ u : DeletedVertex v, ∑ w : DeletedVertex v,
          a u.1 w.1 := by
            apply Finset.sum_congr rfl
            intro v _
            rw [edgeSqrtMass_eq_sum_if (G := deleteVertex G v)]
            simp [a, deleteVertex, deleteMatrix]
    _ = ((Fintype.card V : ℝ) - 2) * (∑ u, ∑ w, a u w) := h
    _ = ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M := by
      rw [edgeSqrtMass_eq_sum_if (G := G)]

omit [DecidableEq V] in
private lemma edgeSqrtMass_eq_dart_sum (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      ∑ p ∈ (Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2),
        Real.sqrt (M p.1 p.2) := by
  rw [edgeSqrtMass_eq_sum_if]
  rw [Finset.sum_filter]
  exact (Finset.sum_product' Finset.univ Finset.univ
    (fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0)).symm

omit [DecidableEq V] in
private lemma edgeMass_eq_dart_sum (M : Matrix V V ℝ) :
    edgeMass G M =
      ∑ p ∈ (Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2),
        M p.1 p.2 := by
  rw [edgeMass_eq_sum_if]
  rw [Finset.sum_filter]
  exact (Finset.sum_product' Finset.univ Finset.univ
    (fun u w ↦ if G.Adj u w then M u w else 0)).symm

omit [DecidableEq V] in
/--
Flat Cauchy--Schwarz in oriented normalization.  The indexing finset has
`2 * |E(G)|` elements.
-/
lemma edgeSqrtMass_sq_le_two_mul_card_edges_mul_edgeMass
    {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤
      2 * (G.edgeFinset.card : ℝ) * edgeMass G M := by
  let s := Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2
  have hflat :=
    sq_sum_sqrt_le_card_mul_sum s (fun p : V × V ↦ M p.1 p.2)
      (fun p _ ↦ hM p.1 p.2)
  have hcardNat : s.card = 2 * G.edgeFinset.card := by
    dsimp [s]
    exact G.two_mul_card_edgeFinset.symm
  have hcardReal : (s.card : ℝ) = 2 * (G.edgeFinset.card : ℝ) := by
    exact_mod_cast hcardNat
  rw [edgeSqrtMass_eq_dart_sum, edgeMass_eq_dart_sum]
  rw [hcardReal] at hflat
  exact hflat

end EdgeDeletion

section GraphDeletion

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

lemma card_edges_deleteVertex (v : V) :
    (deleteVertex G v).edgeFinset.card =
      G.edgeFinset.card - G.degree v := by
  let e : DeletedVertex v ≃ ({v}ᶜ : Set V) :=
    { toFun := fun u ↦ ⟨u.1, by
          change u.1 ∉ ({v} : Set V)
          simpa using u.2⟩
      invFun := fun u ↦ ⟨u.1, by
          intro h
          apply u.2
          simp [h]⟩
      left_inv := fun _ ↦ rfl
      right_inv := fun _ ↦ rfl }
  let f : deleteVertex G v ≃g G.induce ({v}ᶜ : Set V) :=
    { toEquiv := e
      map_rel_iff' := by
        intro u w
        rfl }
  calc
    (deleteVertex G v).edgeFinset.card =
        (G.induce ({v}ᶜ : Set V)).edgeFinset.card :=
      f.card_edgeFinset_eq
    _ = G.edgeFinset.card - G.degree v :=
      (G.card_edgeFinset_induce_compl_singleton v).trans
        (G.card_edgeFinset_deleteIncidenceSet v)

/-- Vertex deletion changes `q = 2m - n + 1` by `1 - 2 deg(v)`. -/
lemma graphQ_deleteVertex (v : V) :
    graphQ (deleteVertex G v) =
      graphQ G + 1 - 2 * (G.degree v : ℝ) := by
  have hdegree : G.degree v ≤ G.edgeFinset.card :=
    by
      rw [← G.card_incidenceFinset_eq_degree]
      exact Finset.card_le_card (G.incidenceFinset_subset v)
  have hvertex : 1 ≤ Fintype.card V :=
    Fintype.card_pos_iff.mpr ⟨v⟩
  simp only [graphQ_eq, card_edges_deleteVertex, card_deletedVertex]
  rw [Nat.cast_sub hdegree, Nat.cast_sub hvertex]
  ring

/-- Summed deletion identity for the graph parameter. -/
lemma sum_graphQ_deleteVertex :
    (∑ v, graphQ (deleteVertex G v)) =
      ((Fintype.card V : ℝ) - 2) * (graphQ G - 1) := by
  have hdegree :
      (∑ v, (G.degree v : ℝ)) =
        2 * (G.edgeFinset.card : ℝ) := by
    exact_mod_cast G.sum_degrees_eq_twice_card_edges
  calc
    (∑ v, graphQ (deleteVertex G v)) =
        ∑ v, (graphQ G + 1 - 2 * (G.degree v : ℝ)) := by
          apply Finset.sum_congr rfl
          intro v _
          exact graphQ_deleteVertex G v
    _ = (Fintype.card V : ℝ) * (graphQ G + 1) -
        2 * ∑ v, (G.degree v : ℝ) := by
          simp [Finset.sum_sub_distrib, Finset.mul_sum]
          ring
    _ = ((Fintype.card V : ℝ) - 2) * (graphQ G - 1) := by
          rw [hdegree]
          simp only [graphQ]
          ring

end GraphDeletion

section MatrixDeletion

variable [Fintype V] [DecidableEq V]

/-- Summing all principal vertex deletions counts off-diagonal entries
`n - 2` times and diagonal entries `n - 1` times. -/
lemma sum_totalMass_deleteMatrix (M : Matrix V V ℝ) :
    (∑ v, totalMass (deleteMatrix M v)) =
      ((Fintype.card V : ℝ) - 2) * totalMass M + M.trace := by
  simpa [totalMass, deleteMatrix, Matrix.trace, Matrix.diag] using
    (sum_delete_submatrices (fun i j ↦ M i j))

end MatrixDeletion

section SupportedMass

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
/-- For a graph-supported matrix, total mass is diagonal mass plus oriented
edge mass.  Symmetry is not needed for this stronger statement. -/
lemma totalMass_eq_trace_add_edgeMass_of_supported
    {M : Matrix V V ℝ} (hM : SupportedOn G M) :
    totalMass M = M.trace + edgeMass G M := by
  classical
  have hentry (i j : V) :
      M i j =
        (if i = j then M i j else 0) +
          (if G.Adj i j then M i j else 0) := by
    by_cases hij : i = j
    · subst j
      simp
    · by_cases hadj : G.Adj i j
      · simp [hij, hadj]
      · simp [hij, hadj, hM hij hadj]
  calc
    totalMass M = ∑ i, ∑ j,
        ((if i = j then M i j else 0) +
          (if G.Adj i j then M i j else 0)) := by
            unfold totalMass
            apply Finset.sum_congr rfl
            intro i _
            apply Finset.sum_congr rfl
            intro j _
            exact hentry i j
    _ = (∑ i, ∑ j, if i = j then M i j else 0) +
        (∑ i, ∑ j, if G.Adj i j then M i j else 0) := by
          simp only [Finset.sum_add_distrib]
    _ = M.trace + edgeMass G M := by
          rw [edgeMass_eq_sum_if]
          simp [Matrix.trace, Matrix.diag]

end SupportedMass

section GraphCardinality

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/-- The real-valued cycle rank `m - n + 1`. -/
def graphCycleRank : ℝ :=
  (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1

omit [DecidableEq V] in
lemma graphQ_edge_count_identity :
    4 * (G.edgeFinset.card : ℝ) =
      2 * graphQ G + 2 * ((Fintype.card V : ℝ) - 1) := by
  simp only [graphQ]
  ring

omit [DecidableEq V] in
lemma graphQ_sub_one_eq_card_sub_two_add_two_mul_cycleRank :
    graphQ G - 1 =
      ((Fintype.card V : ℝ) - 2) + 2 * graphCycleRank G := by
  simp only [graphQ, graphCycleRank]
  ring

omit [DecidableEq V] in
/-- The complete-graph edge bound in the cycle-rank normalization used in
Case 2. -/
lemma two_mul_graphCycleRank_le :
    2 * graphCycleRank G ≤
      ((Fintype.card V : ℝ) - 1) *
        ((Fintype.card V : ℝ) - 2) := by
  have hsimpleNat :
      G.edgeFinset.card ≤ (Fintype.card V).choose 2 :=
    G.card_edgeFinset_le_card_choose_two
  have hsimple :
      2 * (G.edgeFinset.card : ℝ) ≤
        (Fintype.card V : ℝ) * ((Fintype.card V : ℝ) - 1) := by
    have hcast :
        (G.edgeFinset.card : ℝ) ≤
          ((Fintype.card V).choose 2 : ℝ) := by
      exact_mod_cast hsimpleNat
    rw [Nat.cast_choose_two] at hcast
    linarith
  dsimp [graphCycleRank]
  linarith

omit [DecidableEq V] in
lemma one_le_graphQ_of_connected_of_three_le
    (hG : G.Connected) (hcard : 3 ≤ Fintype.card V) :
    1 ≤ graphQ G := by
  have hedges := connected_card_vertices_le_card_edges_add_one G hG
  have hn : (3 : ℝ) ≤ (Fintype.card V : ℝ) := by
    exact_mod_cast hcard
  simp only [graphQ]
  linarith

end GraphCardinality

section ScalarOriented

/-- `averaged_estimate_of_sqrt_bound` in the oriented normalization. -/
lemma oriented_averaged_estimate_of_sqrt_bound
    {n q S T d₀ : ℝ}
    (hn : 2 < n) (hq : 1 ≤ q) (hS : 0 ≤ S)
    (hT : 0 ≤ T) (hd₀ : 0 ≤ d₀)
    (hbound :
      (n - 2) * S ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀))) :
    S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hbound' :
      2 * (n - 2) * (S / 2) ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀)) := by
    convert hbound using 1
    ring
  have h :=
    averaged_estimate_of_sqrt_bound
      (S := S / 2) hn hq (by positivity) hT hd₀ hbound'
  convert h using 1
  ring

/-- Paper Case 1 with oriented edge and square-root masses. -/
lemma oriented_paper_case_one
    {m n q S d₀ w : ℝ}
    (hcount : 4 * m = 2 * q + 2 * (n - 1))
    (hflat : S ^ 2 ≤ 2 * m * w)
    (hthreshold : (n - 1) * w ≤ q * d₀) :
    S ^ 2 ≤ q * (d₀ + w) := by
  have h :=
    paper_case_one
      (S := S / 2) (w := w / 2) hcount
      (by convert hflat using 1 <;> ring)
      (by
        convert hthreshold using 1
        ring)
  convert h using 1 <;> ring

/-- Paper Case 2 with oriented edge and square-root masses. -/
lemma oriented_paper_case_two
    {n q β S d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < (n - 1) * w)
    (haverage :
      S ^ 2 ≤
        (q - 1) * (d₀ + w) + (q - 1) / (n - 2) * d₀) :
    S ^ 2 ≤ q * (d₀ + w) := by
  have h :=
    paper_case_two
      (S := S / 2) (w := w / 2)
      hn hd₀ hqβ hsimple
      (by
        convert hthreshold using 1
        ring)
      (by convert haverage using 1 <;> ring)
  convert h using 1 <;> ring

end ScalarOriented

section AveragedInduction

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/--
The oriented averaged estimate obtained by summing all vertex-deletion
induction hypotheses.
-/
lemma averaged_estimate_of_deleteVertex_IH
    (hG : G.Connected)
    (hcard : 3 ≤ Fintype.card V)
    (hdelete : ∀ v, (deleteVertex G v).Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hIH : ∀ v,
      edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) ^ 2 ≤
        graphQ (deleteVertex G v) * totalMass (deleteMatrix M v)) :
    edgeSqrtMass G M ^ 2 ≤
      (graphQ G - 1) * totalMass M +
        (graphQ G - 1) / ((Fintype.card V : ℝ) - 2) * M.trace := by
  let qv : V → ℝ := fun v ↦ graphQ (deleteVertex G v)
  let Tv : V → ℝ := fun v ↦ totalMass (deleteMatrix M v)
  let Sv : V → ℝ :=
    fun v ↦ edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)
  have hqv (v : V) : 0 ≤ qv v :=
    graphQ_nonneg (deleteVertex G v) (hdelete v)
  have hTv (v : V) : 0 ≤ Tv v :=
    (deleteMatrix_doublyNonnegative hM v).totalMass_nonneg
  have hSv (v : V) : 0 ≤ Sv v :=
    edgeSqrtMass_nonneg (deleteVertex G v) (deleteMatrix M v)
  have hroot (v : V) : Sv v ≤ √(qv v * Tv v) := by
    exact (sq_le_mul_iff_le_sqrt_mul (hSv v)
      (mul_nonneg (hqv v) (hTv v))).mp (hIH v)
  have hsumroot :
      (∑ v, Sv v) ≤
        √((∑ v, qv v) * (∑ v, Tv v)) := by
    calc
      (∑ v, Sv v) ≤ ∑ v, √(qv v * Tv v) :=
        Finset.sum_le_sum fun v _ ↦ hroot v
      _ ≤ √((∑ v, qv v) * (∑ v, Tv v)) :=
        sum_sqrt_mul_le_sqrt_sum_mul_sum Finset.univ qv Tv hqv hTv
  have hbound :
      ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M ≤
        √((((Fintype.card V : ℝ) - 2) * (graphQ G - 1)) *
          (((Fintype.card V : ℝ) - 2) * totalMass M + M.trace)) := by
    rw [← sum_edgeSqrtMass_deleteVertex G M,
      ← sum_graphQ_deleteVertex G,
      ← sum_totalMass_deleteMatrix M]
    exact hsumroot
  have hn : (2 : ℝ) < Fintype.card V := by
    exact_mod_cast (show 2 < Fintype.card V from lt_of_lt_of_le (by decide) hcard)
  exact oriented_averaged_estimate_of_sqrt_bound
    hn (one_le_graphQ_of_connected_of_three_le G hG hcard)
    (edgeSqrtMass_nonneg G M) hM.totalMass_nonneg
    hM.posSemidef.trace_nonneg hbound

end AveragedInduction

section NoCutStep

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/--
The no-cut-vertex induction step for graph-supported doubly nonnegative
matrices.
-/
theorem noCutVertex_step
    (hG : G.Connected)
    (hcard : 3 ≤ Fintype.card V)
    (hdelete : ∀ v, (deleteVertex G v).Connected)
    {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M)
    (hSupported : SupportedOn G M)
    (hIH : ∀ v,
      edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) ^ 2 ≤
        graphQ (deleteVertex G v) * totalMass (deleteMatrix M v)) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  let n : ℝ := Fintype.card V
  let m : ℝ := G.edgeFinset.card
  let q : ℝ := graphQ G
  let S : ℝ := edgeSqrtMass G M
  let d₀ : ℝ := M.trace
  let w : ℝ := edgeMass G M
  have htotal : totalMass M = d₀ + w := by
    exact totalMass_eq_trace_add_edgeMass_of_supported G hSupported
  have hn : 2 < n := by
    dsimp [n]
    exact_mod_cast (show 2 < Fintype.card V from lt_of_lt_of_le (by decide) hcard)
  have hd₀ : 0 ≤ d₀ := hM.posSemidef.trace_nonneg
  have hflat : S ^ 2 ≤ 2 * m * w := by
    exact edgeSqrtMass_sq_le_two_mul_card_edges_mul_edgeMass G hM.entrywise
  by_cases hcase : (n - 1) * w ≤ q * d₀
  · have hcaseOne : S ^ 2 ≤ q * (d₀ + w) :=
      oriented_paper_case_one
        (by
          dsimp [m, n, q]
          exact graphQ_edge_count_identity G)
        hflat hcase
    simpa [S, q, ← htotal] using hcaseOne
  · have hthreshold : q * d₀ < (n - 1) * w := lt_of_not_ge hcase
    have haverage :
        S ^ 2 ≤
          (q - 1) * (d₀ + w) + (q - 1) / (n - 2) * d₀ := by
      have havg :=
        averaged_estimate_of_deleteVertex_IH G hG hcard hdelete hM hIH
      simpa [S, q, n, d₀, htotal] using havg
    have hcaseTwo : S ^ 2 ≤ q * (d₀ + w) :=
      oriented_paper_case_two
        hn hd₀
        (by
          dsimp [q, n]
          exact graphQ_sub_one_eq_card_sub_two_add_two_mul_cycleRank G)
        (by
          dsimp [n]
          exact two_mul_graphCycleRank_le G)
        hthreshold haverage
    simpa [S, q, ← htotal] using hcaseTwo

end NoCutStep

end

end SquareEnergy

end

section

/-!
# Sparse matrix induction

This file closes the induction for the graph-supported sparse matrix
inequality and then removes the support hypothesis by folding nonedges onto
the diagonal.

The edge sum is oriented: every undirected edge occurs twice in
`edgeSqrtMass`.  Consequently its square is exactly the paper's factor
`4 * (∑ uv ∈ E(G), √(M uv)) ^ 2`.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

universe u

variable {V : Type u} [Fintype V] [DecidableEq V]

section CardinalityFacts

omit [DecidableEq V] in
/-- A two-element fintype can be enumerated by two distinct vertices. -/
lemma exists_pair_of_card_eq_two (hcard : Fintype.card V = 2) :
    ∃ u v : V, u ≠ v ∧ ∀ x : V, x = u ∨ x = v := by
  rw [← Nat.card_eq_fintype_card] at hcard
  obtain ⟨u, v, huv, huv_univ⟩ := Nat.card_eq_two_iff.mp hcard
  refine ⟨u, v, huv, fun x ↦ ?_⟩
  have hx : x ∈ ({u, v} : Set V) := by
    rw [huv_univ]
    exact Set.mem_univ x
  simpa [eq_comm] using hx

/-- The universal finset of a two-element type is its chosen pair. -/
lemma univ_eq_pair_of_card_eq_two
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) :
    (Finset.univ : Finset V) = {u, v} := by
  symm
  apply Finset.eq_of_subset_of_card_le (Finset.subset_univ _)
  simp [hcard, huv]

omit [DecidableEq V] in
/-- Every vertex of a two-element type is one of a fixed distinct pair. -/
lemma eq_left_or_right_of_card_eq_two
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) (x : V) :
    x = u ∨ x = v := by
  classical
  have hx : x ∈ ({u, v} : Finset V) := by
    rw [← univ_eq_pair_of_card_eq_two hcard huv]
    exact Finset.mem_univ x
  simpa [eq_comm] using hx

omit [DecidableEq V] in
/-- In a connected graph on two vertices, the two vertices are adjacent. -/
lemma adj_of_connected_card_two
    (G : SimpleGraph V) (hG : G.Connected)
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) :
    G.Adj u v := by
  let : Nontrivial V :=
    Fintype.one_lt_card_iff_nontrivial.mp (by omega)
  obtain ⟨w, huw⟩ := hG.preconnected.exists_adj_of_nontrivial u
  rcases eq_left_or_right_of_card_eq_two hcard huv w with rfl | rfl
  · exact (huw.ne rfl).elim
  · exact huw

omit [DecidableEq V] in
/-- A connected simple graph on two vertices is the complete graph. -/
lemma eq_top_of_connected_card_two
    (G : SimpleGraph V) (hG : G.Connected)
    (hcard : Fintype.card V = 2) :
    G = ⊤ := by
  ext u v
  simp only [SimpleGraph.top_adj]
  exact ⟨SimpleGraph.Adj.ne, adj_of_connected_card_two G hG hcard⟩

omit [DecidableEq V] in
/-- A connected graph on two vertices has graph parameter exactly one. -/
lemma graphQ_eq_one_of_connected_card_two
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 2) :
    graphQ G = 1 := by
  have hlower : Fintype.card V ≤ G.edgeFinset.card + 1 := by
    simpa only [Nat.card_eq_fintype_card, ← G.edgeFinset_card] using
      hG.card_vert_le_card_edgeSet_add_one
  have hupper := G.card_edgeFinset_le_card_choose_two
  have hedge : G.edgeFinset.card = 1 := by
    rw [hcard] at hlower hupper
    change G.edgeFinset.card ≤ 1 at hupper
    omega
  simp [graphQ, hcard, hedge]

omit [DecidableEq V] in
/-- A simple graph on one vertex has no edges. -/
lemma eq_bot_of_card_eq_one
    (G : SimpleGraph V) (hcard : Fintype.card V = 1) :
    G = ⊥ := by
  have : Subsingleton V :=
    Fintype.card_le_one_iff_subsingleton.mp (by omega)
  exact Subsingleton.elim G ⊥

omit [DecidableEq V] in
/-- The graph parameter is exactly zero on a one-vertex graph. -/
lemma graphQ_eq_zero_of_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hcard : Fintype.card V = 1) :
    graphQ G = 0 := by
  have hupper := G.card_edgeFinset_le_card_choose_two
  have hedge : G.edgeFinset.card = 0 := by
    have hz : G.edgeFinset.card ≤ 0 := by
      simpa [hcard] using hupper
    exact Nat.eq_zero_of_le_zero hz
  simp [graphQ, hcard, hedge]

omit [DecidableEq V] in
/--
The oriented square-root edge mass is zero on a connected one-vertex graph.
Connectedness supplies its unique vertex, and simplicity rules out its only
possible edge.
-/
lemma edgeSqrtMass_eq_zero_of_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 1)
    (M : Matrix V V ℝ) :
    edgeSqrtMass G M = 0 := by
  classical
  let u : V := Classical.choice hG.nonempty
  obtain ⟨a, ha⟩ := Fintype.card_eq_one_iff.mp hcard
  have hall (x : V) : x = u := (ha x).trans (ha u).symm
  have huniv : (Finset.univ : Finset V) = {u} := by
    ext x
    simp [hall x]
  have hneighbor : G.neighborFinset u = ∅ := by
    ext x
    rw [hall x]
    simp
  simp [edgeSqrtMass, huniv, hneighbor]

end CardinalityFacts

section TwoVertexFormulas

variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
/-- The two neighbor finsets in a connected two-vertex graph are singletons. -/
lemma neighborFinsets_of_connected_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v) :
    G.neighborFinset u = {v} ∧ G.neighborFinset v = {u} := by
  classical
  have hadj := adj_of_connected_card_two G hG hcard huv
  constructor <;> ext x
  · simp only [SimpleGraph.mem_neighborFinset, Finset.mem_singleton]
    rcases hcover x with rfl | rfl
    · simp [huv]
    · simp [hadj]
  · simp only [SimpleGraph.mem_neighborFinset, Finset.mem_singleton]
    rcases hcover x with rfl | rfl
    · simp [hadj.symm]
    · simp [huv.symm]

omit [DecidableEq V] in
/-- Explicit oriented square-root edge sum on two connected vertices. -/
lemma edgeSqrtMass_eq_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v)
    (M : Matrix V V ℝ) :
    edgeSqrtMass G M = Real.sqrt (M u v) + Real.sqrt (M v u) := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  obtain ⟨hnu, hnv⟩ :=
    neighborFinsets_of_connected_card_two G hG hcard huv hcover
  simp [edgeSqrtMass, huniv, hnu, hnv, huv]

omit [DecidableEq V] in
/-- For a symmetric nonnegative matrix, oriented edge mass squared is `4 M_uv`. -/
lemma edgeSqrtMass_sq_eq_four_mul_of_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 = 4 * M u v := by
  rw [edgeSqrtMass_eq_card_two G hG hcard huv hcover M]
  rw [← hM.apply_symm u v]
  rw [show (Real.sqrt (M u v) + Real.sqrt (M u v)) ^ 2 =
      4 * Real.sqrt (M u v) ^ 2 by ring]
  rw [Real.sq_sqrt (hM.entry_nonneg u v)]

omit [DecidableEq V] in
/-- Explicit total matrix mass after enumerating a two-element type. -/
lemma totalMass_eq_card_two
    (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass M = M u u + M v v + 2 * M u v := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  simp only [totalMass, huniv, Finset.sum_insert, Finset.sum_singleton,
    Finset.mem_singleton, huv, not_false_eq_true]
  have hsymm : M v u = M u v := by
    simpa using hM.apply u v
  rw [hsymm]
  ring

omit [DecidableEq V] in
/-- PSD evaluated at `e_u - e_v` gives the two-vertex diagonal bound. -/
lemma two_mul_offdiag_le_diag_sum_of_card_two
    (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    {M : Matrix V V ℝ} (hM : M.PosSemidef) :
    2 * M u v ≤ M u u + M v v := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  have hquad :=
    hM.dotProduct_mulVec_nonneg (basisDiff u v)
  simp only [dotProduct, Matrix.mulVec, huniv, Finset.sum_insert,
    Finset.sum_singleton, Finset.mem_singleton, huv, not_false_eq_true,
    basisDiff_apply_left huv, basisDiff_apply_right huv, star_trivial,
    one_mul, neg_mul, mul_one, mul_neg] at hquad
  have hsymm : M v u = M u v := by
    simpa using hM.isHermitian.apply u v
  rw [hsymm] at hquad
  linarith

end TwoVertexFormulas

section BaseCases

omit [DecidableEq V] in
/-- The exact one-vertex base of the sparse induction. -/
lemma supportedSparseMatrixInequality_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 1)
    {M : Matrix V V ℝ} (_hM : DoublyNonnegative M)
    (_hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  rw [edgeSqrtMass_eq_zero_of_card_one G hG hcard M,
    graphQ_eq_zero_of_card_one G hcard]
  norm_num

omit [DecidableEq V] in
/-- The paper's exact two-vertex base of the sparse induction. -/
lemma supportedSparseMatrixInequality_card_two
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (_hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  obtain ⟨u, v, huv, hcover⟩ := exists_pair_of_card_eq_two hcard
  rw [edgeSqrtMass_sq_eq_four_mul_of_card_two G hG hcard huv hcover hM]
  rw [graphQ_eq_one_of_connected_card_two G hG hcard]
  rw [totalMass_eq_card_two hcard huv hM.isHermitian]
  have hdiag :=
    two_mul_offdiag_le_diag_sum_of_card_two hcard huv hM.posSemidef
  linarith

end BaseCases

section Induction

omit [DecidableEq V] in
/--
The supported sparse-matrix inequality for every finite connected simple
graph.  Since `edgeSqrtMass` is oriented, its square includes the paper's
factor `4`.
-/
theorem supportedSparseMatrixInequality
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let P : Nat → Prop := fun n ↦
    ∀ {W : Type u} [Fintype W] [DecidableEq W]
      (H : SimpleGraph W) [DecidableRel H.Adj],
      Fintype.card W = n →
      H.Connected →
      ∀ {N : Matrix W W ℝ},
        DoublyNonnegative N →
        SupportedOn H N →
        edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N
  have hP : ∀ n, P n := by
    intro n
    induction n using Nat.strong_induction_on with
    | ind n ih =>
        dsimp only [P]
        intro W _ _ H _ hcard hH N hN hNSupport
        have hnpos : 0 < n := by
          rw [← hcard]
          exact Fintype.card_pos_iff.mpr hH.nonempty
        by_cases hn1 : n = 1
        · exact supportedSparseMatrixInequality_card_one
            H hH (hcard.trans hn1) hN hNSupport
        by_cases hn2 : n = 2
        · exact supportedSparseMatrixInequality_card_two
            H hH (hcard.trans hn2) hN hNSupport
        have hn3 : 3 ≤ Fintype.card W := by omega
        by_cases hcut : ∃ v, ¬(deleteVertex H v).Connected
        · obtain ⟨v, hv⟩ := hcut
          have hne : Nonempty {x : W // x ≠ v} := by
            obtain ⟨w, hw⟩ :=
              Fintype.exists_ne_of_one_lt_card (by omega : 1 < Fintype.card W) v
            exact ⟨⟨w, hw⟩⟩
          apply supported_sparse_bound_of_not_connected_delete
            H v hH hne hv hN hNSupport
          intro X _ _ K _ hK hlt L hL hLSupport
          exact ih (Fintype.card X) (by omega)
            K rfl hK hL hLSupport
        · have hdelete : ∀ v, (deleteVertex H v).Connected := by
            simpa only [not_exists, not_not] using hcut
          apply noCutVertex_step H hH hn3 hdelete hN hNSupport
          intro v
          have hlt : Fintype.card (DeletedVertex v) < n := by
            have := card_deletedVertex_lt v
            omega
          exact ih (Fintype.card (DeletedVertex v)) hlt
            (deleteVertex H v) rfl (hdelete v)
            (deleteMatrix_doublyNonnegative hN v)
            (deleteMatrix_supportedOn H hNSupport v)
  exact hP (Fintype.card V) G rfl hG hM hSupport

omit [DecidableEq V] in
/--
The sparse-matrix inequality for an arbitrary doubly nonnegative matrix.
Nonedge entries are folded onto the diagonal before applying the supported
theorem.  The oriented edge mass encodes the paper's factor `4`.
-/
theorem sparseMatrixInequality
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  exact supported_sparse_inequality_implies_unrestricted G
    (fun N hN hNSupport ↦
      supportedSparseMatrixInequality G hG hN hNSupport)
    hM

end Induction

end

end SquareEnergy

end

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# Square-energy deduction helpers

This file connects the spectral decomposition of a graph adjacency matrix to
the sparse doubly-nonnegative matrix inequality. It contains the matrix,
trace, quadratic, and lower-bound lemmas used by the final results in
`Sq.Main`.

All edge sums below are **oriented**: an undirected edge `{u, v}` occurs once
as `(u, v)` and once as `(v, u)`. Thus `edgeSqrtMass` already contains the
factor two whose square is the factor four in the unoriented formulation.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The signed sum of matrix entries over oriented adjacent vertex pairs. -/
def orientedSignedEdgeSum (G : SimpleGraph V) [DecidableRel G.Adj]
    (X : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, X u v

/-- The sum of absolute matrix entries over oriented adjacent vertex pairs. -/
def orientedAbsEdgeSum (G : SimpleGraph V) [DecidableRel G.Adj]
    (X : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, |X u v|

omit [Fintype V] [DecidableEq V] in
/-- The Hadamard self-square of a positive semidefinite real matrix is doubly
nonnegative. -/
lemma hadamard_self_doublyNonnegative {X : Matrix V V ℝ}
    (hX : X.PosSemidef) :
    DoublyNonnegative (X ⊙ X) := by
  refine ⟨hX.hadamard hX, ?_⟩
  intro i j
  rw [Matrix.hadamard_apply]
  exact mul_self_nonneg (X i j)

omit [DecidableEq V] in
/-- Taking entrywise square roots of a Hadamard self-square gives absolute
values, term by term, on the oriented adjacency sum. -/
lemma edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    edgeSqrtMass G (X ⊙ X) = orientedAbsEdgeSum G X := by
  simp only [edgeSqrtMass, orientedAbsEdgeSum]
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v _
  rw [Matrix.hadamard_apply, ← pow_two, Real.sqrt_sq_eq_abs]

/-- For a real Hermitian matrix, the total mass of its Hadamard self-square is
the trace of its ordinary square. -/
lemma totalMass_hadamard_self_eq_trace_sq {X : Matrix V V ℝ}
    (hX : X.IsHermitian) :
    totalMass (X ⊙ X) = Matrix.trace (X ^ 2) := by
  have hsymm : X.IsSymm := by
    simpa using hX
  rw [totalMass, Matrix.sum_hadamard_eq, hsymm.eq, pow_two]

omit [DecidableEq V] in
/-- Multiplication by the adjacency matrix and taking the trace extracts the
signed sum over oriented adjacent pairs. -/
lemma trace_adjMatrix_mul_eq_orientedSignedEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    Matrix.trace (G.adjMatrix ℝ * X) = orientedSignedEdgeSum G X := by
  calc
    Matrix.trace (G.adjMatrix ℝ * X) =
        Matrix.trace (X * G.adjMatrix ℝ) := Matrix.trace_mul_comm _ _
    _ = orientedSignedEdgeSum G X := by
      simp [Matrix.trace, orientedSignedEdgeSum]

omit [DecidableEq V] in
/-- A signed oriented edge sum is bounded by the corresponding absolute sum. -/
lemma orientedSignedEdgeSum_le_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    orientedSignedEdgeSum G X ≤ orientedAbsEdgeSum G X := by
  unfold orientedSignedEdgeSum orientedAbsEdgeSum
  refine Finset.sum_le_sum fun u _ ↦ ?_
  exact Finset.sum_le_sum fun v _ ↦ le_abs_self (X u v)

omit [DecidableEq V] in
/-- The negative of a signed oriented edge sum is also bounded by the
corresponding absolute sum. -/
lemma neg_orientedSignedEdgeSum_le_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    -orientedSignedEdgeSum G X ≤ orientedAbsEdgeSum G X := by
  unfold orientedSignedEdgeSum orientedAbsEdgeSum
  rw [← Finset.sum_neg_distrib]
  refine Finset.sum_le_sum fun u _ ↦ ?_
  rw [← Finset.sum_neg_distrib]
  exact Finset.sum_le_sum fun v _ ↦ neg_le_abs (X u v)

/-- The oriented signed edge sum of the positive spectral part is the positive
square energy. -/
lemma orientedSignedEdgeSum_adjacencyPosPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    orientedSignedEdgeSum G (adjacencyPosPart G) = positiveSquareEnergy G := by
  rw [← trace_adjMatrix_mul_eq_orientedSignedEdgeSum]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul,
    adjacencyNegPart_mul_posPart, sub_zero, ← pow_two,
    trace_sq_adjacencyPosPart]

/-- The oriented signed edge sum of the absolute negative spectral part is the
negative of the negative square energy. -/
lemma orientedSignedEdgeSum_adjacencyNegPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    orientedSignedEdgeSum G (adjacencyNegPart G) = -negativeSquareEnergy G := by
  rw [← trace_adjMatrix_mul_eq_orientedSignedEdgeSum]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul,
    adjacencyPosPart_mul_negPart, zero_sub, Matrix.trace_neg, ← pow_two,
    trace_sq_adjacencyNegPart]

/-- The total mass of the positive-part Hadamard square is the positive square
energy. -/
lemma totalMass_hadamard_self_adjacencyPosPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    totalMass (adjacencyPosPart G ⊙ adjacencyPosPart G) =
      positiveSquareEnergy G := by
  calc
    totalMass (adjacencyPosPart G ⊙ adjacencyPosPart G) =
        Matrix.trace (adjacencyPosPart G ^ 2) :=
      totalMass_hadamard_self_eq_trace_sq
        (adjacencyPosPart_posSemidef G).isHermitian
    _ = positiveSquareEnergy G := trace_sq_adjacencyPosPart G

/-- The total mass of the negative-part Hadamard square is the negative square
energy. -/
lemma totalMass_hadamard_self_adjacencyNegPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    totalMass (adjacencyNegPart G ⊙ adjacencyNegPart G) =
      negativeSquareEnergy G := by
  calc
    totalMass (adjacencyNegPart G ⊙ adjacencyNegPart G) =
        Matrix.trace (adjacencyNegPart G ^ 2) :=
      totalMass_hadamard_self_eq_trace_sq
        (adjacencyNegPart_posSemidef G).isHermitian
    _ = negativeSquareEnergy G := trace_sq_adjacencyNegPart G

/-- The positive square energy is at most the square-root edge mass of the
positive-part Hadamard square. -/
lemma positiveSquareEnergy_le_edgeSqrtMass_hadamard_posPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G ≤
      edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) := by
  calc
    positiveSquareEnergy G =
        orientedSignedEdgeSum G (adjacencyPosPart G) :=
      (orientedSignedEdgeSum_adjacencyPosPart G).symm
    _ ≤ orientedAbsEdgeSum G (adjacencyPosPart G) :=
      orientedSignedEdgeSum_le_orientedAbsEdgeSum G _
    _ = edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) :=
      (edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum G _).symm

/-- The negative square energy is at most the square-root edge mass of the
negative-part Hadamard square. -/
lemma negativeSquareEnergy_le_edgeSqrtMass_hadamard_negPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    negativeSquareEnergy G ≤
      edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) := by
  calc
    negativeSquareEnergy G =
        -orientedSignedEdgeSum G (adjacencyNegPart G) := by
      rw [orientedSignedEdgeSum_adjacencyNegPart]
      ring
    _ ≤ orientedAbsEdgeSum G (adjacencyNegPart G) :=
      neg_orientedSignedEdgeSum_le_orientedAbsEdgeSum G _
    _ = edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) :=
      (edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum G _).symm

/-- Applying the sparse DNN theorem to the positive-part Hadamard square gives
the cancellable quadratic estimate. -/
lemma positiveSquareEnergy_sq_le_graphQ_mul
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    positiveSquareEnergy G ^ 2 ≤ graphQ G * positiveSquareEnergy G := by
  have hsparse :=
    sparseMatrixInequality G hG
      (hadamard_self_doublyNonnegative (adjacencyPosPart_posSemidef G))
  rw [totalMass_hadamard_self_adjacencyPosPart] at hsparse
  have henergy : 0 ≤ positiveSquareEnergy G :=
    positiveSquareEnergy_nonneg G
  have hedge :
      0 ≤ edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) :=
    edgeSqrtMass_nonneg G _
  exact
    (sq_le_sq₀ henergy hedge).mpr
      (positiveSquareEnergy_le_edgeSqrtMass_hadamard_posPart G) |>.trans hsparse

/-- Applying the sparse DNN theorem to the negative-part Hadamard square gives
the cancellable quadratic estimate. -/
lemma negativeSquareEnergy_sq_le_graphQ_mul
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    negativeSquareEnergy G ^ 2 ≤ graphQ G * negativeSquareEnergy G := by
  have hsparse :=
    sparseMatrixInequality G hG
      (hadamard_self_doublyNonnegative (adjacencyNegPart_posSemidef G))
  rw [totalMass_hadamard_self_adjacencyNegPart] at hsparse
  have henergy : 0 ≤ negativeSquareEnergy G :=
    negativeSquareEnergy_nonneg G
  have hedge :
      0 ≤ edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) :=
    edgeSqrtMass_nonneg G _
  exact
    (sq_le_sq₀ henergy hedge).mpr
      (negativeSquareEnergy_le_edgeSqrtMass_hadamard_negPart G) |>.trans hsparse

/-- On a nontrivial connected graph, strict positivity permits cancellation in
the positive-energy quadratic estimate. -/
lemma positiveSquareEnergy_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    positiveSquareEnergy G ≤ graphQ G :=
  positive_cancel_sq_le_mul
    (positiveSquareEnergy_pos_of_connected G hG)
    (positiveSquareEnergy_sq_le_graphQ_mul G hG)

/-- On a nontrivial connected graph, strict positivity permits cancellation in
the negative-energy quadratic estimate. -/
lemma negativeSquareEnergy_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    negativeSquareEnergy G ≤ graphQ G :=
  positive_cancel_sq_le_mul
    (negativeSquareEnergy_pos_of_connected G hG)
    (negativeSquareEnergy_sq_le_graphQ_mul G hG)

/-- The upper bound on negative energy and the trace identity give the lower
bound on positive energy by the literal formula
`graphQ G = 2 |E(G)| - |V| + 1`. -/
lemma card_sub_one_le_positiveSquareEnergy_of_negative_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hneg : negativeSquareEnergy G ≤ graphQ G) :
    (Fintype.card V : ℝ) - 1 ≤ positiveSquareEnergy G := by
  have hsum := squareEnergies_add_eq_twice_card_edges G
  rw [graphQ] at hneg
  linarith

/-- The upper bound on positive energy and the trace identity give the lower
bound on negative energy by the literal formula
`graphQ G = 2 |E(G)| - |V| + 1`. -/
lemma card_sub_one_le_negativeSquareEnergy_of_positive_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hpos : positiveSquareEnergy G ≤ graphQ G) :
    (Fintype.card V : ℝ) - 1 ≤ negativeSquareEnergy G := by
  have hsum := squareEnergies_add_eq_twice_card_edges G
  rw [graphQ] at hpos
  linarith

end

end SquareEnergy

end

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# The square-energy theorem

This file exposes the two component lower bounds and their combined final
form. The square energies use strict positive and strict negative filters, so
zero adjacency eigenvalues contribute to neither energy.
-/

namespace SquareEnergy

noncomputable section

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The positive square energy of a nontrivial connected graph is at least
`|V| - 1`. -/
lemma card_sub_one_le_positiveSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤ positiveSquareEnergy G :=
  card_sub_one_le_positiveSquareEnergy_of_negative_le_graphQ G
    (negativeSquareEnergy_le_graphQ G hG)

/-- The negative square energy of a nontrivial connected graph is at least
`|V| - 1`. -/
lemma card_sub_one_le_negativeSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤ negativeSquareEnergy G :=
  card_sub_one_le_negativeSquareEnergy_of_positive_le_graphQ G
    (positiveSquareEnergy_le_graphQ G hG)

/--
Every finite connected simple undirected graph has both positive and negative
square energy at least `|V| - 1`. Adjacency eigenvalues are the real
eigenvalues counted with algebraic multiplicity; the strict sign filters omit
zero eigenvalues. The one-vertex graph is handled separately, while
connectedness excludes the zero-vertex case.
-/
theorem card_sub_one_le_min_squareEnergy
    {V : Type*} [Fintype V] [DecidableEq V]
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤
      min (positiveSquareEnergy G) (negativeSquareEnergy G) := by
  by_cases hcard : Fintype.card V = 1
  · have hleft : (Fintype.card V : ℝ) - 1 = 0 := by
      norm_num [hcard]
    rw [hleft]
    exact le_min (positiveSquareEnergy_nonneg G) (negativeSquareEnergy_nonneg G)
  · have hcard_pos : 0 < Fintype.card V :=
      Fintype.card_pos_iff.mpr hG.nonempty
    have hcard_gt : 1 < Fintype.card V := by
      omega
    let : Nontrivial V :=
      Fintype.one_lt_card_iff_nontrivial.mp hcard_gt
    exact le_min
      (card_sub_one_le_positiveSquareEnergy G hG)
      (card_sub_one_le_negativeSquareEnergy G hG)

end

end SquareEnergy

end


/- Adapted from Tristan Cazenave, SpectralLean/Invariants.lean and Empirical/RandicL1.lean. -/
namespace Spectral

open Matrix SimpleGraph

variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]

/-- Adjacency matrix over `ℝ` is Hermitian (real symmetric). -/
theorem adj_isHermitian : (G.adjMatrix ℝ).IsHermitian := by
  ext i j
  simp [Matrix.conjTranspose_apply, SimpleGraph.adjMatrix_apply, G.adj_comm]

/-- eigenvalues of the adjacency matrix in decreasing order. -/
noncomputable def adjEig (i : Fin (Fintype.card (Fin n))) : ℝ := (adj_isHermitian G).eigenvalues₀ i

/-- Randić index: sum over edges of `1 / sqrt(d(u) d(v))`. -/
noncomputable def randic : ℝ :=
  ∑ e ∈ G.edgeFinset, Sym2.lift ⟨fun u v => 1 / Real.sqrt ((G.degree u : ℝ) * G.degree v),
    fun u v => by simp [mul_comm]⟩ e


section Spec

variable {n : ℕ} {A : Matrix (Fin n) (Fin n) ℝ} (hA : A.IsHermitian)

omit hA in
lemma herm_transpose (hA : A.IsHermitian) : Aᵀ = A := by
  have : Aᴴ = A := hA; rwa [conjTranspose_eq_transpose_of_trivial] at this

lemma parseval (y z : Fin n → ℝ) :
    ∑ i, (y ⬝ᵥ ⇑(hA.eigenvectorBasis i)) * (⇑(hA.eigenvectorBasis i) ⬝ᵥ z) = y ⬝ᵥ z := by
  have := (hA.eigenvectorBasis).sum_inner_mul_inner (WithLp.toLp 2 y) (WithLp.toLp 2 z)
  simp only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] at this
  simpa [dotProduct_comm] using this

lemma eig_le_top (h : 0 < n) (i : Fin n) : hA.eigenvalues i ≤ hA.eigenvalues₀ ⟨0, by simpa⟩ := by
  unfold IsHermitian.eigenvalues
  exact hA.eigenvalues₀_antitone (Fin.mk_le_mk.2 (Nat.zero_le _))

lemma rayleigh_le (h : 0 < n) (y : Fin n → ℝ) :
    y ⬝ᵥ (A *ᵥ y) ≤ hA.eigenvalues₀ ⟨0, by simpa⟩ * (y ⬝ᵥ y) := by
  rw [← parseval hA y (A *ᵥ y), ← parseval hA y y, Finset.mul_sum]
  apply Finset.sum_le_sum
  intro i _
  have e : ⇑(hA.eigenvectorBasis i) ⬝ᵥ (A *ᵥ y) = hA.eigenvalues i * (⇑(hA.eigenvectorBasis i) ⬝ᵥ y) := by
    rw [dotProduct_mulVec, ← mulVec_transpose, herm_transpose hA, hA.mulVec_eigenvectorBasis,
      smul_dotProduct, smul_eq_mul]
  rw [e, dotProduct_comm y]
  have := eig_le_top hA h i
  have := mul_self_nonneg (⇑(hA.eigenvectorBasis i) ⬝ᵥ y)
  nlinarith

end Spec

section Graph

variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]

lemma edge_sum (f : Fin n → Fin n → ℝ) (hf : ∀ u v, f u v = f v u) :
    2 * ∑ e ∈ G.edgeFinset, Sym2.lift ⟨f, hf⟩ e = ∑ u, ∑ v, G.adjMatrix ℝ u v * f u v := by
  have h1 : ∑ u, ∑ v, G.adjMatrix ℝ u v * f u v = ∑ d : G.Dart, f d.fst d.snd := by
    simp only [adjMatrix_apply, ite_mul, one_mul, zero_mul]
    rw [← Fintype.sum_prod_type' (f := fun u v => if G.Adj u v then f u v else 0),
      ← Finset.sum_filter]
    refine Finset.sum_bij' (fun p h => (⟨p, (Finset.mem_filter.1 h).2⟩ : G.Dart))
      (fun d _ => (d.fst, d.snd)) ?_ ?_ ?_ ?_ ?_ <;> simp
  have h2 : ∑ d : G.Dart, f d.fst d.snd = ∑ d : G.Dart, Sym2.lift ⟨f, hf⟩ d.edge := by
    apply Finset.sum_congr rfl; intro d _; rfl
  rw [h1, h2, ← Finset.sum_fiberwise_of_maps_to (s := Finset.univ) (t := G.edgeFinset)
    (g := Dart.edge) (fun d _ => by simp), Finset.mul_sum]
  apply Finset.sum_congr rfl
  intro e he
  rw [Finset.sum_congr rfl (g := fun _ => Sym2.lift ⟨f, hf⟩ e)
    (fun d hd => by rw [(Finset.mem_filter.1 hd).2]), Finset.sum_const, nsmul_eq_mul]
  rw [G.dart_edge_fiber_card e (by simpa using he)]
  norm_num

lemma row_sum (u : Fin n) : ∑ v, G.adjMatrix ℝ u v = (G.degree u : ℝ) := by
  have := G.adjMatrix_mulVec_const_apply (a := (1 : ℝ)) (v := u)
  simpa [mulVec, dotProduct] using this

lemma deg_sum : ∑ u, (G.degree u : ℝ) = 2 * G.edgeFinset.card := by
  exact_mod_cast G.sum_degrees_eq_twice_card_edges

lemma deg_pos (h2 : 2 ≤ n) (hc : G.Connected) (v : Fin n) : (1 : ℝ) ≤ G.degree v := by
  obtain ⟨w, hw⟩ : ∃ w : Fin n, w ≠ v :=
    if h : v.val = 0 then ⟨⟨1, by omega⟩, fun e => by rw [← e] at h; simp at h⟩
    else ⟨⟨0, by omega⟩, fun e => h (by rw [← e])⟩
  obtain ⟨p, -, -⟩ := hc.exists_path_of_dist v w
  have : 1 ≤ G.degree v := by
    cases p with
    | nil => exact absurd rfl hw
    | cons h _ => exact (G.degree_pos_iff_exists_adj v).2 ⟨_, h⟩
  exact_mod_cast this

/-- `λ₁ R ≥ m` (Favaron–Mahéo–Saclé), from the Rayleigh quotient of `√d`. -/
lemma l1_R_ge_m (h2 : 2 ≤ n) (hc : G.Connected) :
    0 < adjEig G ⟨0, by simp; omega⟩ ∧
    (G.edgeFinset.card : ℝ) ≤ adjEig G ⟨0, by simp; omega⟩ * randic G := by
  set A := G.adjMatrix ℝ
  set l := adjEig G ⟨0, by simp; omega⟩
  set d : Fin n → ℝ := fun u => (G.degree u : ℝ)
  set m : ℝ := (G.edgeFinset.card : ℝ)
  have hd : ∀ u, 1 ≤ d u := deg_pos G h2 hc
  let y : Fin n → ℝ := fun u => Real.sqrt (d u)
  have hray := rayleigh_le (adj_isHermitian G) (by omega) y
  have hyy : y ⬝ᵥ y = 2 * m := by
    simp only [dotProduct, y]
    rw [← deg_sum G]; apply Finset.sum_congr rfl; intro u _
    rw [Real.mul_self_sqrt (by linarith [hd u])]
  set S := ∑ u, ∑ v, A u v * (y u * y v)
  have hyAy : y ⬝ᵥ (A *ᵥ y) = S := by
    simp only [dotProduct, mulVec, Finset.mul_sum, S]
    apply Finset.sum_congr rfl; intro u _; apply Finset.sum_congr rfl; intro v _; ring
  have hR : 2 * randic G = ∑ u, ∑ v, A u v * (1 / Real.sqrt (d u * d v)) :=
    edge_sum G _ _
  have hA2m : ∑ u, ∑ v, A u v = 2 * m := by
    rw [← deg_sum G]; exact Finset.sum_congr rfl (fun u _ => row_sum G u)
  have hS : S ≤ l * (2 * m) := by rw [← hyAy, ← hyy]; exact hray
  obtain ⟨u0, v0, huv⟩ : ∃ u v, G.Adj u v := by
    obtain ⟨p, -, -⟩ := hc.exists_path_of_dist (⟨0, by omega⟩ : Fin n) ⟨1, by omega⟩
    cases p with
    | cons h _ => exact ⟨_, _, h⟩
  have hypos : ∀ u, 0 < y u := fun u => Real.sqrt_pos.2 (by linarith [hd u])
  have hterm : ∀ u v, 0 ≤ A u v * (y u * y v) := fun u v => by
    have : 0 ≤ A u v := by by_cases h : G.Adj u v <;> simp [A, adjMatrix_apply, h]
    have := hypos u; have := hypos v; positivity
  have hSpos : 0 < S := by
    apply Finset.sum_pos' (fun u _ => Finset.sum_nonneg (fun v _ => hterm u v))
    refine ⟨u0, Finset.mem_univ _, Finset.sum_pos' (fun v _ => hterm u0 v) ⟨v0, Finset.mem_univ _, ?_⟩⟩
    have := hypos u0; have := hypos v0
    simp [A, adjMatrix_apply, huv]; positivity
  have hm : 0 < m := by
    have : 0 < l * (2 * m) := lt_of_lt_of_le hSpos hS
    by_contra hneg; push Not at hneg
    have hm0 : (0 : ℝ) ≤ m := by positivity
    have : m = 0 := le_antisymm hneg hm0
    rw [this] at hS; linarith
  have hl : 0 < l := by
    by_contra hneg; push Not at hneg; nlinarith
  refine ⟨hl, ?_⟩
  -- AM-GM on each edge
  have hpt : ∀ u v, A u v * 2 ≤ A u v * (y u * y v) / l + l * (A u v * (1 / Real.sqrt (d u * d v))) := by
    intro u v
    by_cases h : G.Adj u v
    · simp only [A, adjMatrix_apply, h, ite_true, one_mul]
      have hs : Real.sqrt (d u * d v) = y u * y v := Real.sqrt_mul (by linarith [hd u]) _
      rw [hs]
      have ha : 0 < y u * y v := mul_pos (hypos u) (hypos v)
      rw [div_add' _ _ _ hl.ne', le_div_iff₀ hl]
      have : l * (1 / (y u * y v)) * l = l ^ 2 / (y u * y v) := by field_simp
      rw [this, show y u * y v + l ^ 2 / (y u * y v) = ((y u * y v) ^ 2 + l ^ 2) / (y u * y v) by
        field_simp]
      rw [le_div_iff₀ ha]; nlinarith [sq_nonneg (y u * y v - l)]
    · simp [A, adjMatrix_apply, h]
  have hsum : ∑ u, ∑ v, A u v * 2 ≤ S / l + l * (2 * randic G) := by
    rw [hR, Finset.sum_div, Finset.mul_sum, ← Finset.sum_add_distrib]
    apply Finset.sum_le_sum; intro u _
    rw [Finset.sum_div, Finset.mul_sum, ← Finset.sum_add_distrib]
    exact Finset.sum_le_sum fun v _ => hpt u v
  have h4m : ∑ u, ∑ v, A u v * 2 = 2 * (2 * m) := by
    rw [← hA2m, Finset.mul_sum]; apply Finset.sum_congr rfl; intro u _
    rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro v _; ring
  have hSl : S / l ≤ 2 * m := by rw [div_le_iff₀ hl]; linarith
  linarith


end Graph
end Spectral


open Matrix WithLp
open scoped BigOperators

namespace RandicSecondBound

private theorem randic_quad_upper {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]
    (x : Fin n → ℝ) (hx : ∑ i, x i = 0) :
    2 * (((G.adjMatrix ℝ) *ᵥ x) ⬝ᵥ x) +
      2 * (x ⬝ᵥ x) ≤ (n : ℝ) * (x ⬝ᵥ x) := by
  classical
  let a := G.adjMatrix ℝ
  have pt (i j : Fin n) :
      (4 * a i j + (if i = j then 4 else 0) - 2) * x i * x j ≤ (x i)^2 + (x j)^2 := by
    by_cases he : i = j
    · subst j
      simp [a]
      nlinarith
    · by_cases h : G.Adj i j
      · simp [a, he, h]
        nlinarith [sq_nonneg (x i - x j)]
      · simp [a, he, h]
        nlinarith [sq_nonneg (x i + x j)]
  have hsum := Finset.sum_le_sum (s := Finset.univ) fun i _ =>
    Finset.sum_le_sum (s := Finset.univ) fun j _ => pt i j
  have hi (i : Fin n) :
      ∑ j, (4 * a i j + (if i = j then 4 else 0) - 2) * x i * x j =
      4 * (∑ j, a i j * x j) * x i + 4 * (x i * x i) := by
    calc
      _ = ∑ j, ((4 * x i) * (a i j * x j) + (if i = j then 4 * x i * x j else 0)
          - 2 * x i * x j) := by
            apply Finset.sum_congr rfl
            intro j _
            split_ifs <;> ring
      _ = _ := by
        rw [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, ← Finset.mul_sum, hx]
        simp
        ring
  simp_rw [hi, Finset.sum_add_distrib] at hsum
  simp [← Finset.mul_sum, pow_two] at hsum
  change 2 * ∑ i, (∑ j, a i j * x j) * x i + 2 * ∑ i, x i * x i ≤
    n * ∑ i, x i * x i
  have hf : ∑ i, 4 * (∑ j, a i j * x j) * x i =
      4 * ∑ i, (∑ j, a i j * x j) * x i := by
    rw [Finset.mul_sum]
    apply Finset.sum_congr rfl
    intro i _
    ring
  rw [hf] at hsum
  linarith

theorem randic_second_bound {n : ℕ} (hn : 2 ≤ n) (G : SimpleGraph (Fin n))
    [DecidableRel G.Adj] :
    (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ + 1 ≤ (n : ℝ) / 2 := by
  classical
  let hA := G.isHermitian_adjMatrix ℝ
  let e : Fin (Fintype.card (Fin n)) ≃ Fin n := Fintype.equivOfCardEq (Fintype.card_fin _)
  let k0 : Fin (Fintype.card (Fin n)) := ⟨0, by simp; omega⟩
  let k1 : Fin (Fintype.card (Fin n)) := ⟨1, by simp; omega⟩
  let f (k : Fin (Fintype.card (Fin n))) : Fin n → ℝ := ⇑(hA.eigenvectorBasis (e k))
  have ev (k) : (G.adjMatrix ℝ) *ᵥ f k = hA.eigenvalues₀ k • f k := by
    simp [f, hA.mulVec_eigenvectorBasis, Matrix.IsHermitian.eigenvalues, e]
  have orth (k l) : f k ⬝ᵥ f l = if k = l then 1 else 0 := by
    have h := orthonormal_iff_ite.mp hA.eigenvectorBasis.orthonormal (e l) (e k)
    rw [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] at h
    simpa [f, eq_comm] using h
  have h01 : k0 ≠ k1 := by simp [k0, k1, Fin.ext_iff]
  have hle : hA.eigenvalues₀ k1 ≤ hA.eigenvalues₀ k0 :=
    hA.eigenvalues₀_antitone (show k0 ≤ k1 by exact Fin.mk_le_mk.mpr (by decide))
  have key (a b : ℝ) (hab : a ≠ 0 ∨ b ≠ 0)
      (hz : ∑ i, (a • f k0 + b • f k1) i = 0) :
      hA.eigenvalues₀ k1 + 1 ≤ (n : ℝ) / 2 := by
    have H := randic_quad_upper G (a • f k0 + b • f k1) hz
    simp only [mulVec_add, mulVec_smul, ev, add_dotProduct, dotProduct_add, smul_dotProduct,
      dotProduct_smul, smul_eq_mul, orth, ite_true, ite_eq_right h01, ite_eq_right (Ne.symm h01),
      mul_one, mul_zero, zero_add, add_zero] at H
    have pos : 0 < a*a + b*b := by
      rcases hab with ha | hb
      · nlinarith [sq_pos_of_ne_zero ha, sq_nonneg b]
      · nlinarith [sq_pos_of_ne_zero hb, sq_nonneg a]
    apply le_of_mul_le_mul_right _ pos
    nlinarith [mul_nonneg (sub_nonneg.mpr hle) (sq_nonneg a)]
  by_cases hs : ∑ i, f k0 i = 0
  · exact key 1 0 (Or.inl one_ne_zero) (by simpa using hs)
  · refine key (∑ i, f k1 i) (-(∑ i, f k0 i)) (Or.inr (neg_ne_zero.mpr hs)) ?_
    simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul, Finset.sum_add_distrib,
      ← Finset.mul_sum]
    ring

end RandicSecondBound

/-- For a connected graph with at least two vertices, its second largest adjacency
eigenvalue plus one is at most its Randić index. -/
theorem nullius_main {n : ℕ} (hn : 2 ≤ n) (G : SimpleGraph (Fin n))
    [DecidableRel G.Adj] (hc : G.Connected) :
    (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ + 1 ≤ Spectral.randic G := by
  classical
  haveI : Nontrivial (Fin n) := Fin.nontrivial_iff_two_le.mpr hn
  let ev := (G.isHermitian_adjMatrix ℝ).eigenvalues₀
  let a : Fin (Fintype.card (Fin n)) := ⟨0, by simp; omega⟩
  let b : Fin (Fintype.card (Fin n)) := ⟨1, by simp; omega⟩
  let e : Fin (Fintype.card (Fin n)) ≃ Fin n := Fintype.equivOfCardEq (Fintype.card_fin _)
  obtain ⟨hfirst, hfms⟩ := Spectral.l1_R_ge_m G hn hc
  change 0 < ev a at hfirst
  have hsize := RandicSecondBound.randic_second_bound hn G
  have henergy := SquareEnergy.positiveSquareEnergy_le_graphQ G hc
  rw [SquareEnergy.positiveSquareEnergy,
    ← SquareEnergy.sum_sq_posPart_eq_filter, SquareEnergy.graphQ, Fintype.card_fin] at henergy
  let f := fun j => (max (ev j) 0)^2
  have hu : (∑ i, f (e.symm i)) = ∑ j, f j := e.symm.sum_comp f
  change (∑ i, f (e.symm i)) ≤ _ at henergy
  rw [hu] at henergy
  have hab : a ≠ b := fun h => by have := congrArg Fin.val h; change 0 = 1 at this; omega
  have hp := Finset.sum_le_sum_of_subset_of_nonneg
    (Finset.subset_univ ({a, b} : Finset (Fin (Fintype.card (Fin n)))))
    (fun j _ _ => show 0 ≤ f j from sq_nonneg _)
  rw [Finset.sum_pair hab] at hp
  change (max (ev a) 0)^2 + (max (ev b) 0)^2 ≤ _ at hp
  rw [max_eq_left hfirst.le] at hp
  have ht : (max (ev b) 0) + 1 ≤ (n : ℝ) / 2 := by
    rw [← max_add_add_right, max_le_iff]
    refine ⟨hsize, ?_⟩
    have hn' : (2 : ℝ) ≤ n := by exact_mod_cast hn
    linarith
  change (G.edgeFinset.card : ℝ) ≤ ev a * Spectral.randic G at hfms
  have hprod : ev a * (max (ev b) 0 + 1) ≤ (G.edgeFinset.card : ℝ) := by
    nlinarith [hp.trans henergy, sq_nonneg (ev a - (max (ev b) 0 + 1))]
  have hR := (le_of_mul_le_mul_left (hprod.trans hfms) hfirst)
  exact (add_le_add_left (le_max_left (ev b) 0) 1).trans hR

Bridge: the proof applied to the independent statement

Download Bridge.lean
import Mathlib

lemma nullius_bridge_eig {m m' : Type*} [Fintype m] [DecidableEq m] [Fintype m'] [DecidableEq m']
    {A : Matrix m m ℝ} {B : Matrix m' m' ℝ} (hA : A.IsHermitian) (hB : B.IsHermitian)
    (hch : A.charpoly = B.charpoly) (k : ℕ) (h1 : k < Fintype.card m) (h2 : k < Fintype.card m') :
    hA.eigenvalues₀ ⟨k, h1⟩ = hB.eigenvalues₀ ⟨k, h2⟩ := by
  have h : List.ofFn hA.eigenvalues₀ = List.ofFn hB.eigenvalues₀ := by
    rw [← hA.sort_roots_charpoly_eq_eigenvalues₀, ← hB.sort_roots_charpoly_eq_eigenvalues₀, hch]
  have := congrArg (fun l => l[k]?) h
  simpa [List.getElem?_ofFn, h1, h2] using this

theorem nullius_bridge : NulliusClaim := by
  classical
  intro V _ G hn hc
  intro lam R
  let n := Fintype.card V
  let e : V ≃ Fin n := Fintype.equivFin V
  let G' : SimpleGraph (Fin n) := G.comap e.symm
  let φ : G' ≃g G := SimpleGraph.Iso.comap e.symm G
  have hc' : G'.Connected := φ.connected_iff.mpr hc
  have main := nullius_main (n := n) hn G' hc'
  have hR : Spectral.randic G' = R := by
    unfold Spectral.randic
    refine Finset.sum_nbij' (Sym2.map e.symm) (Sym2.map e) ?_ ?_ ?_ ?_ ?_
    · intro x
      induction x using Sym2.ind with | _ a b => ?_
      simp [G']
    · intro x
      induction x using Sym2.ind with | _ a b => ?_
      simp [G']
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      simp
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      simp
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      have ha : G'.degree a = G.degree (e.symm a) := (φ.degree_eq a).symm
      have hb : G'.degree b = G.degree (e.symm b) := (φ.degree_eq b).symm
      simp [Sym2.mul_mk, ha, hb]
  have hE : (G'.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ = lam := by
    apply nullius_bridge_eig
    have : G'.adjMatrix ℝ = Matrix.reindex e e (G.adjMatrix ℝ) := by
      ext i j
      simp [G', SimpleGraph.adjMatrix_apply]
    rw [this, Matrix.charpoly_reindex]
  rw [hE, hR] at main
  exact main

Combined file, exactly as checked by Lean

Download Combined.lean
import Mathlib

-- ===== Statement (independent formalizer) =====

open scoped Classical in
def NulliusClaim : Prop :=
  ∀ (V : Type*) [Fintype V] (G : SimpleGraph V) (hn : 2 ≤ Fintype.card V),
    G.Connected →
      let lambda₂ := (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, hn⟩
      let R := ∑ e ∈ G.edgeFinset, (Real.sqrt (↑((e.map (fun v => G.degree v)).mul) : ℝ))⁻¹
      lambda₂ + 1 ≤ R

-- ===== Proof =====

/- The SquareEnergy development is adapted from Yinchen Liu, Quanyu Tang and Shengtong Zhang,
   https://github.com/ShengtongZhang-alt/Sq/tree/df80e517f78202298f02f2637a39ff4ad3f6b4c5 .
   The modules are combined here and updated to Lean 4.37.0-rc1. -/

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# Square-energy definitions

This file defines the adjacency eigenvalues of a finite simple graph and its
positive and negative square energies. Eigenvalues are indexed by the vertex
type and therefore counted with algebraic multiplicity; the strict sign
filters exclude zero eigenvalues from both energies.
-/

open scoped BigOperators

namespace SquareEnergy

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The adjacency eigenvalues of a finite simple graph, indexed with algebraic
multiplicity by its vertex type. -/
noncomputable def adjacencyEigenvalues
    (G : SimpleGraph V) [DecidableRel G.Adj] : V → ℝ :=
  (G.isHermitian_adjMatrix ℝ).eigenvalues

/-- The sum of the squares of the strictly positive adjacency eigenvalues. -/
noncomputable def positiveSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  ∑ i with 0 < adjacencyEigenvalues G i, (adjacencyEigenvalues G i) ^ 2

/-- The sum of the squares of the strictly negative adjacency eigenvalues. -/
noncomputable def negativeSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  ∑ i with adjacencyEigenvalues G i < 0, (adjacencyEigenvalues G i) ^ 2

end SquareEnergy

end

section


/-!
# Positive and negative square energy

This file fixes the spectral conventions used in the paper.  Eigenvalues are
the real eigenvalues of the real symmetric adjacency matrix, indexed with
algebraic multiplicity by the vertex type.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The positive spectral part of the adjacency matrix. -/
noncomputable def adjacencyPosPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix V V ℝ :=
  (G.isHermitian_adjMatrix ℝ).cfc (fun x ↦ max x 0)

/-- The absolute value of the negative spectral part of the adjacency matrix. -/
noncomputable def adjacencyNegPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix V V ℝ :=
  (G.isHermitian_adjMatrix ℝ).cfc (fun x ↦ max (-x) 0)

/-- The characteristic-polynomial roots are exactly the indexed adjacency
eigenvalues.  Since `Polynomial.roots` is a multiset, this records algebraic
multiplicity. -/
lemma roots_charpoly_adjMatrix_eq_adjacencyEigenvalues
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    (G.adjMatrix ℝ).charpoly.roots =
      Multiset.map (adjacencyEigenvalues G) Finset.univ.val := by
  simpa [adjacencyEigenvalues, Function.comp_def] using
    (G.isHermitian_adjMatrix ℝ).roots_charpoly_eq_eigenvalues

lemma positiveSquareEnergy_nonneg (G : SimpleGraph V) [DecidableRel G.Adj] :
    0 ≤ positiveSquareEnergy G := by
  classical
  exact Finset.sum_nonneg fun _ _ ↦ sq_nonneg _

lemma negativeSquareEnergy_nonneg (G : SimpleGraph V) [DecidableRel G.Adj] :
    0 ≤ negativeSquareEnergy G := by
  classical
  exact Finset.sum_nonneg fun _ _ ↦ sq_nonneg _

omit [DecidableEq V] in
lemma sum_sq_posPart_eq_filter (f : V → ℝ) :
    (∑ i, (max (f i) 0) ^ 2) = ∑ i with 0 < f i, (f i) ^ 2 := by
  classical
  rw [Finset.sum_filter]
  apply Finset.sum_congr rfl
  intro i _
  by_cases hi : 0 < f i
  · simp [hi, hi.le]
  · have hi' : f i ≤ 0 := le_of_not_gt hi
    simp [hi, hi']

omit [DecidableEq V] in
lemma sum_sq_negPart_eq_filter (f : V → ℝ) :
    (∑ i, (max (-f i) 0) ^ 2) = ∑ i with f i < 0, (f i) ^ 2 := by
  classical
  rw [Finset.sum_filter]
  apply Finset.sum_congr rfl
  intro i _
  by_cases hi : f i < 0
  · have hneg : 0 < -f i := neg_pos.mpr hi
    rw [ite_eq_left hi, max_eq_left hneg.le]
    ring
  · have hi' : 0 ≤ f i := le_of_not_gt hi
    simp [hi, hi']

open scoped MatrixOrder

/-- The explicitly diagonalized positive part agrees with the native CFC
positive part of the adjacency matrix. -/
lemma adjacencyPosPart_eq_posPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyPosPart G = (G.adjMatrix ℝ)⁺ := by
  rw [adjacencyPosPart, CFC.posPart_def, cfcₙ_eq_cfc,
    (G.isHermitian_adjMatrix ℝ).cfc_eq]
  congr 1

/-- The explicitly diagonalized negative part agrees with the native CFC
negative part of the adjacency matrix. -/
lemma adjacencyNegPart_eq_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyNegPart G = (G.adjMatrix ℝ)⁻ := by
  rw [adjacencyNegPart, CFC.negPart_def, cfcₙ_eq_cfc,
    (G.isHermitian_adjMatrix ℝ).cfc_eq]
  congr 1

lemma adjacencyPosPart_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj] :
    (adjacencyPosPart G).PosSemidef := by
  rw [adjacencyPosPart_eq_posPart]
  exact (CFC.posPart_nonneg (G.adjMatrix ℝ)).posSemidef

lemma adjacencyNegPart_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj] :
    (adjacencyNegPart G).PosSemidef := by
  rw [adjacencyNegPart_eq_negPart]
  exact (CFC.negPart_nonneg (G.adjMatrix ℝ)).posSemidef

lemma adjacency_eq_posPart_sub_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    G.adjMatrix ℝ = adjacencyPosPart G - adjacencyNegPart G := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact (CFC.posPart_sub_negPart (G.adjMatrix ℝ)
    (G.isHermitian_adjMatrix ℝ).isSelfAdjoint).symm

lemma adjacencyPosPart_mul_negPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyPosPart G * adjacencyNegPart G = 0 := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact CFC.posPart_mul_negPart (G.adjMatrix ℝ)

lemma adjacencyNegPart_mul_posPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    adjacencyNegPart G * adjacencyPosPart G = 0 := by
  rw [adjacencyPosPart_eq_posPart, adjacencyNegPart_eq_negPart]
  exact CFC.negPart_mul_posPart (G.adjMatrix ℝ)

/-- Trace of the finite-dimensional Hermitian functional calculus. -/
lemma trace_hermitianCfc {A : Matrix V V ℝ} (hA : A.IsHermitian) (f : ℝ → ℝ) :
    Matrix.trace (hA.cfc f) = ∑ i, f (hA.eigenvalues i) := by
  rw [Matrix.IsHermitian.cfc, Unitary.conjStarAlgAut_apply,
    Matrix.trace_mul_cycle, Unitary.coe_star_mul_self, Matrix.one_mul,
    Matrix.trace_diagonal]
  simp

/-- The trace of the square of a Hermitian CFC value is the sum of the
corresponding squared scalar values. -/
lemma trace_sq_hermitianCfc {A : Matrix V V ℝ} (hA : A.IsHermitian) (f : ℝ → ℝ) :
    Matrix.trace (hA.cfc f ^ 2) = ∑ i, (f (hA.eigenvalues i)) ^ 2 := by
  have hf : ContinuousOn f (spectrum ℝ A) := by
    rw [continuousOn_iff_continuous_domRestrict]
    fun_prop
  calc
    Matrix.trace (hA.cfc f ^ 2) =
        Matrix.trace (hA.cfc (fun x ↦ f x * f x)) := by
      rw [pow_two, ← hA.cfc_eq f, ← cfc_mul f f A hf hf, hA.cfc_eq]
    _ = ∑ i, f (hA.eigenvalues i) * f (hA.eigenvalues i) :=
      trace_hermitianCfc hA _
    _ = ∑ i, (f (hA.eigenvalues i)) ^ 2 := by
      simp only [pow_two]

lemma trace_sq_adjacencyPosPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (adjacencyPosPart G ^ 2) = positiveSquareEnergy G := by
  rw [adjacencyPosPart, trace_sq_hermitianCfc, sum_sq_posPart_eq_filter]
  rfl

lemma trace_sq_adjacencyNegPart (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (adjacencyNegPart G ^ 2) = negativeSquareEnergy G := by
  rw [adjacencyNegPart, trace_sq_hermitianCfc, sum_sq_negPart_eq_filter]
  rfl

lemma sq_adjacency_eq_sq_posPart_add_sq_negPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    G.adjMatrix ℝ ^ 2 = adjacencyPosPart G ^ 2 + adjacencyNegPart G ^ 2 := by
  simp only [pow_two]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul, Matrix.mul_sub,
    Matrix.mul_sub, adjacencyPosPart_mul_negPart, adjacencyNegPart_mul_posPart]
  simp

lemma squareEnergies_add_eq_trace_sq_adjacency
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G + negativeSquareEnergy G =
      Matrix.trace (G.adjMatrix ℝ ^ 2) := by
  rw [sq_adjacency_eq_sq_posPart_add_sq_negPart, Matrix.trace_add,
    trace_sq_adjacencyPosPart, trace_sq_adjacencyNegPart]

lemma trace_sq_adjacency_eq_twice_card_edges
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    Matrix.trace (G.adjMatrix ℝ ^ 2) = (2 : ℝ) * G.edgeFinset.card := by
  simp only [pow_two, Matrix.trace, Matrix.diag_apply,
    G.adjMatrix_mul_self_apply_self]
  exact_mod_cast G.sum_degrees_eq_twice_card_edges

lemma squareEnergies_add_eq_twice_card_edges
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G + negativeSquareEnergy G =
      (2 : ℝ) * G.edgeFinset.card :=
  (squareEnergies_add_eq_trace_sq_adjacency G).trans
    (trace_sq_adjacency_eq_twice_card_edges G)

omit [DecidableEq V] in
lemma exists_pos_of_sum_eq_zero_of_ne_zero (f : V → ℝ)
    (hsum : ∑ i, f i = 0) (hf : f ≠ 0) :
    ∃ i, 0 < f i := by
  classical
  by_contra hpos
  apply hf
  funext i
  have hnonpos : ∀ j, f j ≤ 0 := fun j ↦
    le_of_not_gt fun hj ↦ hpos ⟨j, hj⟩
  exact (Finset.sum_eq_zero_iff_of_nonpos fun j _ ↦ hnonpos j).mp hsum
    i (Finset.mem_univ i)

omit [DecidableEq V] in
lemma exists_neg_of_sum_eq_zero_of_ne_zero (f : V → ℝ)
    (hsum : ∑ i, f i = 0) (hf : f ≠ 0) :
    ∃ i, f i < 0 := by
  classical
  by_contra hneg
  apply hf
  funext i
  have hnonneg : ∀ j, 0 ≤ f j := fun j ↦
    le_of_not_gt fun hj ↦ hneg ⟨j, hj⟩
  exact (Finset.sum_eq_zero_iff_of_nonneg fun j _ ↦ hnonneg j).mp hsum
    i (Finset.mem_univ i)

omit [DecidableEq V] in
lemma sum_sq_pos_filter_pos_of_exists_pos (f : V → ℝ)
    (h : ∃ i, 0 < f i) :
    0 < ∑ i with 0 < f i, (f i) ^ 2 := by
  classical
  apply Finset.sum_pos'
  · intro i _
    exact sq_nonneg (f i)
  · obtain ⟨i, hi⟩ := h
    exact ⟨i, by simp [hi], sq_pos_of_pos hi⟩

omit [DecidableEq V] in
lemma sum_sq_neg_filter_pos_of_exists_neg (f : V → ℝ)
    (h : ∃ i, f i < 0) :
    0 < ∑ i with f i < 0, (f i) ^ 2 := by
  classical
  apply Finset.sum_pos'
  · intro i _
    exact sq_nonneg (f i)
  · obtain ⟨i, hi⟩ := h
    exact ⟨i, by simp [hi], sq_pos_of_neg hi⟩

omit [Fintype V] [DecidableEq V] in
lemma exists_adj_of_connected_nontrivial
    (G : SimpleGraph V) [Nontrivial V]
    (hG : G.Connected) :
    ∃ u v, G.Adj u v := by
  let v : V := Classical.choice (inferInstance : Nonempty V)
  obtain ⟨u, hu⟩ := hG.preconnected.exists_adj_of_nontrivial v
  exact ⟨v, u, hu⟩

omit [Fintype V] [DecidableEq V] in
lemma adjacencyMatrix_ne_zero_of_exists_adj
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (h : ∃ u v, G.Adj u v) :
    G.adjMatrix ℝ ≠ 0 := by
  obtain ⟨u, v, huv⟩ := h
  intro hzero
  have huv_entry := congr_fun (congr_fun hzero u) v
  simp [huv] at huv_entry

omit [Fintype V] [DecidableEq V] in
lemma adjacencyMatrix_ne_zero_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    G.adjMatrix ℝ ≠ 0 :=
  adjacencyMatrix_ne_zero_of_exists_adj G
    (exists_adj_of_connected_nontrivial G hG)

lemma adjacencyEigenvalues_ne_zero_of_adjacencyMatrix_ne_zero
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hA : G.adjMatrix ℝ ≠ 0) :
    adjacencyEigenvalues G ≠ 0 := by
  intro hzero
  apply hA
  apply (G.isHermitian_adjMatrix ℝ).eigenvalues_eq_zero_iff.mp
  simpa only [adjacencyEigenvalues] using hzero

lemma adjacencyEigenvalues_ne_zero_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    adjacencyEigenvalues G ≠ 0 :=
  adjacencyEigenvalues_ne_zero_of_adjacencyMatrix_ne_zero G
    (adjacencyMatrix_ne_zero_of_connected G hG)

lemma sum_adjacencyEigenvalues_eq_zero
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    ∑ i, adjacencyEigenvalues G i = 0 := by
  calc
    ∑ i, adjacencyEigenvalues G i = Matrix.trace (G.adjMatrix ℝ) := by
      simpa [adjacencyEigenvalues] using
        (G.isHermitian_adjMatrix ℝ).trace_eq_sum_eigenvalues.symm
    _ = 0 := G.trace_adjMatrix ℝ

lemma exists_pos_adjacencyEigenvalue_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    ∃ i, 0 < adjacencyEigenvalues G i :=
  exists_pos_of_sum_eq_zero_of_ne_zero (adjacencyEigenvalues G)
    (sum_adjacencyEigenvalues_eq_zero G)
    (adjacencyEigenvalues_ne_zero_of_connected G hG)

lemma exists_neg_adjacencyEigenvalue_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    ∃ i, adjacencyEigenvalues G i < 0 :=
  exists_neg_of_sum_eq_zero_of_ne_zero (adjacencyEigenvalues G)
    (sum_adjacencyEigenvalues_eq_zero G)
    (adjacencyEigenvalues_ne_zero_of_connected G hG)

lemma positiveSquareEnergy_pos_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    0 < positiveSquareEnergy G := by
  exact sum_sq_pos_filter_pos_of_exists_pos (adjacencyEigenvalues G)
    (exists_pos_adjacencyEigenvalue_of_connected G hG)

lemma negativeSquareEnergy_pos_of_connected
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    0 < negativeSquareEnergy G := by
  exact sum_sq_neg_filter_pos_of_exists_neg (adjacencyEigenvalues G)
    (exists_neg_adjacencyEigenvalue_of_connected G hG)

end SquareEnergy

end

section

/-!
# Basic definitions for the sparse matrix inequality

This file fixes the conventions used by the sparse-matrix part of the
square-energy argument.  In particular, `EntrywiseNonnegative` is an
entrywise condition; it is deliberately not notation from `MatrixOrder`.

The edge sums below are oriented: an undirected edge contributes once from
each endpoint.  Thus the paper's
`4 * (∑ uv ∈ E(G), √(M uv)) ^ 2` is represented by
`edgeSqrtMass G M ^ 2`.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*}

/-- Every entry of `M` is nonnegative.  This is not the Loewner order. -/
def EntrywiseNonnegative (M : Matrix V V ℝ) : Prop :=
  ∀ i j, 0 ≤ M i j

/-- A real matrix which is both positive semidefinite and entrywise nonnegative. -/
def DoublyNonnegative (M : Matrix V V ℝ) : Prop :=
  M.PosSemidef ∧ EntrywiseNonnegative M

/-- The off-diagonal support of `M` is contained in the edge set of `G`. -/
def SupportedOn (G : SimpleGraph V) (M : Matrix V V ℝ) : Prop :=
  ∀ ⦃u v⦄, u ≠ v → ¬G.Adj u v → M u v = 0

namespace EntrywiseNonnegative

lemma add {M N : Matrix V V ℝ} (hM : EntrywiseNonnegative M)
    (hN : EntrywiseNonnegative N) : EntrywiseNonnegative (M + N) :=
  fun i j ↦ add_nonneg (hM i j) (hN i j)

lemma zero : EntrywiseNonnegative (0 : Matrix V V ℝ) := by
  intro i j
  simp

lemma smul {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) {c : ℝ}
    (hc : 0 ≤ c) : EntrywiseNonnegative (c • M) := by
  intro i j
  exact mul_nonneg hc (hM i j)

end EntrywiseNonnegative

namespace DoublyNonnegative

lemma posSemidef {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.PosSemidef :=
  hM.1

lemma entrywise {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    EntrywiseNonnegative M :=
  hM.2

lemma entry_nonneg {M : Matrix V V ℝ} (hM : DoublyNonnegative M) (i j : V) :
    0 ≤ M i j :=
  hM.2 i j

lemma isHermitian {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.IsHermitian :=
  hM.1.isHermitian

lemma isSymm {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    M.IsSymm := by
  simpa using hM.isHermitian

lemma apply_symm {M : Matrix V V ℝ} (hM : DoublyNonnegative M) (i j : V) :
    M i j = M j i := by
  simpa using (hM.isSymm.apply j i)

end DoublyNonnegative

section Finite

variable [Fintype V]

/-- The graph parameter `2 |E(G)| - |V(G)| + 1`, with no truncation. -/
def graphQ (G : SimpleGraph V) [DecidableRel G.Adj] : ℝ :=
  2 * (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1

@[simp]
lemma graphQ_eq (G : SimpleGraph V) [DecidableRel G.Adj] :
    graphQ G =
      2 * (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1 :=
  rfl

/-- A useful separation of `graphQ` into edge count and connected excess. -/
lemma graphQ_eq_card_edges_add_excess (G : SimpleGraph V) [DecidableRel G.Adj] :
    graphQ G =
      (G.edgeFinset.card : ℝ) +
        ((G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1) := by
  simp only [graphQ]
  ring

lemma connected_card_vertices_le_card_edges_add_one
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    (Fintype.card V : ℝ) ≤ (G.edgeFinset.card : ℝ) + 1 := by
  have hNat : Fintype.card V ≤ G.edgeFinset.card + 1 := by
    simpa only [Nat.card_eq_fintype_card, ← G.edgeFinset_card] using
      hG.card_vert_le_card_edgeSet_add_one
  exact_mod_cast hNat

/-- For a connected graph, its edge count is at most `graphQ`. -/
lemma card_edges_le_graphQ (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) :
    (G.edgeFinset.card : ℝ) ≤ graphQ G := by
  have h := connected_card_vertices_le_card_edges_add_one G hG
  simp only [graphQ]
  linarith

/-- The literal (nontruncated) `graphQ` is nonnegative on connected graphs. -/
lemma graphQ_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) :
    0 ≤ graphQ G :=
  (Nat.cast_nonneg G.edgeFinset.card).trans (card_edges_le_graphQ G hG)

/-- The sum of all entries of a matrix. -/
def totalMass (M : Matrix V V ℝ) : ℝ :=
  ∑ i, ∑ j, M i j

lemma totalMass_eq_one_dotProduct_mulVec_one (M : Matrix V V ℝ) :
    totalMass M = (1 : V → ℝ) ⬝ᵥ (M *ᵥ (1 : V → ℝ)) := by
  simp [totalMass, dotProduct, mulVec]

lemma totalMass_add (M N : Matrix V V ℝ) :
    totalMass (M + N) = totalMass M + totalMass N := by
  simp [totalMass, Finset.sum_add_distrib]

lemma totalMass_smul (c : ℝ) (M : Matrix V V ℝ) :
    totalMass (c • M) = c * totalMass M := by
  simp [totalMass, Finset.mul_sum]

lemma totalMass_finset_sum {ι : Type*} (s : Finset ι)
    (M : ι → Matrix V V ℝ) :
    totalMass (∑ k ∈ s, M k) = ∑ k ∈ s, totalMass (M k) := by
  classical
  induction s using Finset.induction_on with
  | empty => simp [totalMass]
  | @insert a s ha ih =>
      simp [ha, totalMass_add, ih]

/-- Positive semidefiniteness makes the total entry mass nonnegative. -/
lemma totalMass_nonneg_of_posSemidef {M : Matrix V V ℝ}
    (hM : M.PosSemidef) : 0 ≤ totalMass M := by
  rw [totalMass_eq_one_dotProduct_mulVec_one]
  simpa using hM.dotProduct_mulVec_nonneg (1 : V → ℝ)

lemma DoublyNonnegative.totalMass_nonneg {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) : 0 ≤ totalMass M :=
  totalMass_nonneg_of_posSemidef hM.posSemidef

/-- The oriented edge-entry mass.  Every undirected edge is counted twice. -/
def edgeMass (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, M u v

/--
The oriented square-root edge mass.  Every undirected edge is counted twice,
so the sparse theorem has the normalization
`edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M`.
-/
def edgeSqrtMass (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, Real.sqrt (M u v)

lemma edgeMass_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) :
    0 ≤ edgeMass G M := by
  exact Finset.sum_nonneg fun u _ ↦
    Finset.sum_nonneg fun v _ ↦ hM u v

lemma edgeSqrtMass_nonneg (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) :
    0 ≤ edgeSqrtMass G M := by
  exact Finset.sum_nonneg fun u _ ↦
    Finset.sum_nonneg fun v _ ↦ Real.sqrt_nonneg _

lemma edgeMass_congr (G : SimpleGraph V) [DecidableRel G.Adj]
    {M N : Matrix V V ℝ}
    (h : ∀ ⦃u v⦄, G.Adj u v → M u v = N u v) :
    edgeMass G M = edgeMass G N := by
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v hv
  exact h ((G.mem_neighborFinset u v).mp hv)

lemma edgeSqrtMass_congr (G : SimpleGraph V) [DecidableRel G.Adj]
    {M N : Matrix V V ℝ}
    (h : ∀ ⦃u v⦄, G.Adj u v → M u v = N u v) :
    edgeSqrtMass G M = edgeSqrtMass G N := by
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v hv
  rw [h ((G.mem_neighborFinset u v).mp hv)]

end Finite

end

end SquareEnergy

end

section

/-!
# Scalar inequalities for the sparse square-energy argument

This file contains the graph-free real inequalities used in the induction for
the square-energy bound.  In particular, it does not depend on the graph or
matrix modules of this project.
-/

open scoped BigOperators

namespace SquareEnergy

/-- An oriented squared bound is equivalent to its square-root form when the
left side and the radicand are nonnegative. -/
lemma sq_le_mul_iff_le_sqrt_mul {S q T : ℝ} (hS : 0 ≤ S) (hprod : 0 ≤ q * T) :
    S ^ 2 ≤ q * T ↔ S ≤ √(q * T) :=
  (Real.le_sqrt hS hprod).symm

/-- The normalized square-energy bound is equivalent to the square-root bound
used when two inductive pieces are combined. -/
lemma four_mul_sq_le_iff_two_mul_le_sqrt_mul {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) :
    4 * S ^ 2 ≤ q * T ↔ 2 * S ≤ √(q * T) := by
  have htwoS : 0 ≤ 2 * S := by positivity
  rw [show 4 * S ^ 2 = (2 * S) ^ 2 by ring]
  exact (Real.le_sqrt htwoS hprod).symm

/-- Convert a normalized squared square-energy bound to its square-root form. -/
lemma two_mul_le_sqrt_mul_of_four_mul_sq_le {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) (h : 4 * S ^ 2 ≤ q * T) :
    2 * S ≤ √(q * T) :=
  (four_mul_sq_le_iff_two_mul_le_sqrt_mul hS hprod).mp h

/-- Convert a normalized square-root square-energy bound back to squared form. -/
lemma four_mul_sq_le_of_two_mul_le_sqrt_mul {S q T : ℝ}
    (hS : 0 ≤ S) (hprod : 0 ≤ q * T) (h : 2 * S ≤ √(q * T)) :
    4 * S ^ 2 ≤ q * T :=
  (four_mul_sq_le_iff_two_mul_le_sqrt_mul hS hprod).mpr h

/-- Finite-sum Cauchy--Schwarz in the form used for sums of inductive
square-root bounds. -/
lemma sum_sqrt_mul_le_sqrt_sum_mul_sum {ι : Type*} (s : Finset ι) (a b : ι → ℝ)
    (ha : ∀ i, 0 ≤ a i) (hb : ∀ i, 0 ≤ b i) :
    (∑ i ∈ s, √(a i * b i)) ≤
      √((∑ i ∈ s, a i) * (∑ i ∈ s, b i)) := by
  calc
    (∑ i ∈ s, √(a i * b i)) =
        ∑ i ∈ s, √(a i) * √(b i) := by
      apply Finset.sum_congr rfl
      intro i _
      rw [Real.sqrt_mul (ha i)]
    _ ≤ √(∑ i ∈ s, a i) * √(∑ i ∈ s, b i) :=
      Real.sum_sqrt_mul_sqrt_le s ha hb
    _ = √((∑ i ∈ s, a i) * (∑ i ∈ s, b i)) := by
      rw [Real.sqrt_mul (Finset.sum_nonneg fun i _ ↦ ha i)]

/-- The two-term scalar Cauchy--Schwarz inequality, written with one square
root around each product. -/
lemma sqrt_mul_add_sqrt_mul_le {q₁ q₂ T₁ T₂ : ℝ}
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂) (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂) :
    √(q₁ * T₁) + √(q₂ * T₂) ≤ √((q₁ + q₂) * (T₁ + T₂)) := by
  rw [Real.sqrt_mul hq₁, Real.sqrt_mul hq₂]
  apply Real.le_sqrt_of_sq_le
  nlinarith [Real.sq_sqrt hq₁, Real.sq_sqrt hq₂, Real.sq_sqrt hT₁,
    Real.sq_sqrt hT₂, sq_nonneg (√q₁ * √T₂ - √q₂ * √T₁)]

/-- Combine the normalized square-energy bounds for two nonnegative blocks. -/
lemma four_mul_sq_add_le_of_two_blocks {S₁ S₂ q₁ q₂ T₁ T₂ : ℝ}
    (hS₁ : 0 ≤ S₁) (hS₂ : 0 ≤ S₂)
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂) (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂)
    (h₁ : 4 * S₁ ^ 2 ≤ q₁ * T₁) (h₂ : 4 * S₂ ^ 2 ≤ q₂ * T₂) :
    4 * (S₁ + S₂) ^ 2 ≤ (q₁ + q₂) * (T₁ + T₂) := by
  have hroot₁ : 2 * S₁ ≤ √(q₁ * T₁) :=
    two_mul_le_sqrt_mul_of_four_mul_sq_le hS₁ (mul_nonneg hq₁ hT₁) h₁
  have hroot₂ : 2 * S₂ ≤ √(q₂ * T₂) :=
    two_mul_le_sqrt_mul_of_four_mul_sq_le hS₂ (mul_nonneg hq₂ hT₂) h₂
  apply (four_mul_sq_le_iff_two_mul_le_sqrt_mul
    (add_nonneg hS₁ hS₂) (mul_nonneg (add_nonneg hq₁ hq₂) (add_nonneg hT₁ hT₂))).mpr
  calc
    2 * (S₁ + S₂) = 2 * S₁ + 2 * S₂ := by ring
    _ ≤ √(q₁ * T₁) + √(q₂ * T₂) := add_le_add hroot₁ hroot₂
    _ ≤ √((q₁ + q₂) * (T₁ + T₂)) :=
      sqrt_mul_add_sqrt_mul_le hq₁ hq₂ hT₁ hT₂

/-- Cancel the common positive factor in the squared vertex-deletion estimate
and put the result into the paper's averaged form. -/
lemma averaged_estimate_of_scaled_bound {n q S T d₀ : ℝ} (hn : 2 < n)
    (hscaled :
      (2 * (n - 2) * S) ^ 2 ≤
        ((n - 2) * (q - 1)) * ((n - 2) * T + d₀)) :
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hfirst :
      (n - 2) * (4 * S ^ 2) ≤ (q - 1) * ((n - 2) * T + d₀) := by
    refine (mul_le_mul_iff_right₀ hn₂).mp ?_
    calc
      (n - 2) * ((n - 2) * (4 * S ^ 2)) =
          (2 * (n - 2) * S) ^ 2 := by ring
      _ ≤ ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) := hscaled
      _ = (n - 2) * ((q - 1) * ((n - 2) * T + d₀)) := by ring
  have hcancel :
      (n - 2) * ((q - 1) / (n - 2)) = q - 1 := by
    calc
      (n - 2) * ((q - 1) / (n - 2)) =
          (q - 1) / (n - 2) * (n - 2) := by ring
      _ = q - 1 := div_mul_cancel₀ _ hn₂.ne'
  refine (mul_le_mul_iff_right₀ hn₂).mp ?_
  calc
    (n - 2) * (4 * S ^ 2) ≤ (q - 1) * ((n - 2) * T + d₀) := hfirst
    _ = (n - 2) * ((q - 1) * T) + (q - 1) * d₀ := by ring
    _ = (n - 2) * ((q - 1) * T) +
        ((n - 2) * ((q - 1) / (n - 2))) * d₀ := by
      rw [hcancel]
    _ = (n - 2) * ((q - 1) * T) +
        (n - 2) * ((q - 1) / (n - 2) * d₀) := by ring
    _ = (n - 2) * ((q - 1) * T + (q - 1) / (n - 2) * d₀) := by
      rw [mul_add]

/-- Derive the averaged estimate directly from the square-root inequality
obtained after summing the vertex-deletion induction hypotheses. -/
lemma averaged_estimate_of_sqrt_bound {n q S T d₀ : ℝ}
    (hn : 2 < n) (hq : 1 ≤ q) (hS : 0 ≤ S) (hT : 0 ≤ T) (hd₀ : 0 ≤ d₀)
    (hbound :
      2 * (n - 2) * S ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀))) :
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hq₁ : 0 ≤ q - 1 := sub_nonneg.mpr hq
  have htail : 0 ≤ (n - 2) * T + d₀ :=
    add_nonneg (mul_nonneg hn₂.le hT) hd₀
  have hradicand :
      0 ≤ ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) :=
    mul_nonneg (mul_nonneg hn₂.le hq₁) htail
  have hleft : 0 ≤ 2 * (n - 2) * S := by positivity
  have hscaled :
      (2 * (n - 2) * S) ^ 2 ≤
        ((n - 2) * (q - 1)) * ((n - 2) * T + d₀) :=
    (Real.le_sqrt hleft hradicand).mp hbound
  exact averaged_estimate_of_scaled_bound hn hscaled

/-- Cauchy--Schwarz for a flat finite edge sum:
the square of a sum of square roots is at most the number of terms times
their sum. -/
lemma sq_sum_sqrt_le_card_mul_sum {ι : Type*} (s : Finset ι) (a : ι → ℝ)
    (ha : ∀ i ∈ s, 0 ≤ a i) :
    (∑ i ∈ s, √(a i)) ^ 2 ≤ (s.card : ℝ) * ∑ i ∈ s, a i := by
  calc
    (∑ i ∈ s, √(a i)) ^ 2 ≤
        (s.card : ℝ) * ∑ i ∈ s, (√(a i)) ^ 2 :=
      sq_sum_le_card_mul_sum_sq (s := s) (f := fun i ↦ √(a i))
    _ = (s.card : ℝ) * ∑ i ∈ s, a i := by
      congr 1
      apply Finset.sum_congr rfl
      intro i hi
      rw [Real.sq_sqrt (ha i hi)]

/-- The flat finite edge Cauchy--Schwarz estimate with the factor `4` used in
the square-energy theorem. -/
lemma four_mul_sq_sum_sqrt_le_card_mul_sum {ι : Type*}
    (s : Finset ι) (a : ι → ℝ) (ha : ∀ i ∈ s, 0 ≤ a i) :
    4 * (∑ i ∈ s, √(a i)) ^ 2 ≤
      4 * (s.card : ℝ) * ∑ i ∈ s, a i := by
  calc
    4 * (∑ i ∈ s, √(a i)) ^ 2 ≤
        4 * ((s.card : ℝ) * ∑ i ∈ s, a i) :=
      mul_le_mul_of_nonneg_left (sq_sum_sqrt_le_card_mul_sum s a ha) (by positivity)
    _ = 4 * (s.card : ℝ) * ∑ i ∈ s, a i := by ring

/-- Paper Case 1: the edge-count identity, flat estimate, and low-edge-mass
threshold imply the target square-energy bound. -/
lemma paper_case_one {m n q S d₀ w : ℝ}
    (hcount : 4 * m = 2 * q + 2 * (n - 1))
    (hflat : 4 * S ^ 2 ≤ 4 * m * w)
    (hthreshold : 2 * (n - 1) * w ≤ q * d₀) :
    4 * S ^ 2 ≤ q * (d₀ + 2 * w) := by
  calc
    4 * S ^ 2 ≤ 4 * m * w := hflat
    _ = 2 * q * w + 2 * (n - 1) * w := by rw [hcount]; ring
    _ ≤ 2 * q * w + q * d₀ := add_le_add le_rfl hthreshold
    _ = q * (d₀ + 2 * w) := by ring

/-- In Paper Case 2, simplicity bounds the coefficient of `d₀` after the
identity `q - 1 = (n - 2) + 2β` is substituted. -/
lemma paper_case_two_coefficient_le {n q β : ℝ}
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2)) :
    2 * β * (n - 1) ≤ q * (n - 2) := by
  have hq : q = (n - 1) + 2 * β := by linarith
  have hgap : 0 ≤ (n - 1) * (n - 2) - 2 * β := sub_nonneg.mpr hsimple
  rw [hq]
  calc
    2 * β * (n - 1) ≤
        2 * β * (n - 1) + ((n - 1) * (n - 2) - 2 * β) :=
      le_add_of_nonneg_right hgap
    _ = ((n - 1) + 2 * β) * (n - 2) := by ring

/-- The strict Case 2 threshold gives the strict paper bound
`β d₀ < (n - 2) w`; all cancellations use an explicitly positive factor. -/
lemma paper_case_two_beta_mul_d_lt {n q β d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w) :
    β * d₀ < (n - 2) * w := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have hn₁ : 0 < n - 1 := by linarith
  have hfactor : 0 < 2 * (n - 1) := mul_pos (by positivity) hn₁
  have hcoefficient :
      2 * β * (n - 1) ≤ q * (n - 2) :=
    paper_case_two_coefficient_le hqβ hsimple
  have hcoefficient_d :
      (2 * β * (n - 1)) * d₀ ≤ (q * (n - 2)) * d₀ :=
    mul_le_mul_of_nonneg_right hcoefficient hd₀
  have hthreshold_scaled :
      (q * d₀) * (n - 2) < (2 * (n - 1) * w) * (n - 2) :=
    mul_lt_mul_of_pos_right hthreshold hn₂
  have hscaled :
      (2 * (n - 1)) * (β * d₀) <
        (2 * (n - 1)) * ((n - 2) * w) := by
    calc
      (2 * (n - 1)) * (β * d₀) = (2 * β * (n - 1)) * d₀ := by ring
      _ ≤ (q * (n - 2)) * d₀ := hcoefficient_d
      _ = (q * d₀) * (n - 2) := by ring
      _ < (2 * (n - 1) * w) * (n - 2) := hthreshold_scaled
      _ = (2 * (n - 1)) * ((n - 2) * w) := by ring
  exact (mul_lt_mul_iff_right₀ hfactor).mp hscaled

/-- The weak Case 2 bound `β d₀ ≤ (n - 2) w` used by the averaged
correction estimate. -/
lemma paper_case_two_beta_mul_d_le {n q β d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w) :
    β * d₀ ≤ (n - 2) * w :=
  (paper_case_two_beta_mul_d_lt hn hd₀ hqβ hsimple hthreshold).le

/-- The Case 2 beta bound controls the correction term in the averaged
estimate by `T = d₀ + 2w`. -/
lemma paper_case_two_averaged_correction_le {n q β d₀ w : ℝ}
    (hn : 2 < n) (hqβ : q - 1 = (n - 2) + 2 * β)
    (hβd : β * d₀ ≤ (n - 2) * w) :
    (q - 1) / (n - 2) * d₀ ≤ d₀ + 2 * w := by
  have hn₂ : 0 < n - 2 := sub_pos.mpr hn
  have htwice :
      2 * (β * d₀) ≤ 2 * ((n - 2) * w) :=
    mul_le_mul_of_nonneg_left hβd (by positivity)
  have hnumerator :
      (q - 1) * d₀ ≤ (d₀ + 2 * w) * (n - 2) := by
    calc
      (q - 1) * d₀ = ((n - 2) + 2 * β) * d₀ := by rw [hqβ]
      _ = (n - 2) * d₀ + 2 * (β * d₀) := by ring
      _ ≤ (n - 2) * d₀ + 2 * ((n - 2) * w) :=
        add_le_add le_rfl htwice
      _ = (d₀ + 2 * w) * (n - 2) := by ring
  calc
    (q - 1) / (n - 2) * d₀ = ((q - 1) * d₀) / (n - 2) := by ring
    _ ≤ d₀ + 2 * w := (div_le_iff₀ hn₂).mpr hnumerator

/-- Once the averaged correction is at most `T`, the averaged estimate is the
target bound `4S² ≤ qT`. -/
lemma paper_case_two_final_averaged_target {n q S T d₀ : ℝ}
    (haverage :
      4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀)
    (hcorrection : (q - 1) / (n - 2) * d₀ ≤ T) :
    4 * S ^ 2 ≤ q * T := by
  calc
    4 * S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := haverage
    _ ≤ (q - 1) * T + T := add_le_add le_rfl hcorrection
    _ = q * T := by ring

/-- Paper Case 2 in assembled scalar form: simplicity and the high-edge-mass
threshold turn the averaged estimate into the target bound. -/
lemma paper_case_two {n q β S d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < 2 * (n - 1) * w)
    (haverage :
      4 * S ^ 2 ≤
        (q - 1) * (d₀ + 2 * w) + (q - 1) / (n - 2) * d₀) :
    4 * S ^ 2 ≤ q * (d₀ + 2 * w) := by
  have hβd : β * d₀ ≤ (n - 2) * w :=
    paper_case_two_beta_mul_d_le hn hd₀ hqβ hsimple hthreshold
  have hcorrection :
      (q - 1) / (n - 2) * d₀ ≤ d₀ + 2 * w :=
    paper_case_two_averaged_correction_le hn hqβ hβd
  exact paper_case_two_final_averaged_target haverage hcorrection

/-- Cancel a positive `x` from `x² ≤ qx`; this is the final scalar step in
the spectral square-energy deduction. -/
lemma positive_cancel_sq_le_mul {x q : ℝ} (hx : 0 < x) (h : x ^ 2 ≤ q * x) :
    x ≤ q := by
  apply (mul_le_mul_iff_right₀ hx).mp
  calc
    x * x = x ^ 2 := by ring
    _ ≤ q * x := h
    _ = x * q := by ring

end SquareEnergy

end

section

/-!
# Folding off-diagonal nonedges onto the diagonal

For every unordered nonedge `{u, v}`, the folding operation adds

`M u v • (e_u - e_v) (e_u - e_v)ᵀ`.

The use of `Sym2 V` makes the sum genuinely unordered.  The Hermitian
hypothesis makes the displayed summand independent of which endpoint is
named first.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*} [DecidableEq V]

/-- The vector `e_u - e_v`. -/
def basisDiff (u v : V) : V → ℝ :=
  Pi.single u 1 - Pi.single v 1

@[simp]
lemma basisDiff_self (u : V) : basisDiff u u = 0 := by
  ext i
  simp [basisDiff]

lemma basisDiff_swap (u v : V) : basisDiff v u = -basisDiff u v := by
  ext i
  simp [basisDiff]

@[simp]
lemma basisDiff_apply_left {u v : V} (huv : u ≠ v) :
    basisDiff u v u = 1 := by
  simp [basisDiff, huv]

@[simp]
lemma basisDiff_apply_right {u v : V} (huv : u ≠ v) :
    basisDiff u v v = -1 := by
  simp [basisDiff, huv]

lemma basisDiff_apply_of_ne {u v i : V} (hiu : i ≠ u) (hiv : i ≠ v) :
    basisDiff u v i = 0 := by
  simp [basisDiff, hiu, hiv]

@[simp]
lemma sum_basisDiff [Fintype V] (u v : V) : ∑ i, basisDiff u v i = 0 := by
  simp [basisDiff, Pi.single_apply, Finset.sum_sub_distrib]

/--
The positive-semidefinite rank-one correction belonging to an unordered
pair.  For a Hermitian real matrix, the coefficient `M u v` is independent
of the orientation of the pair.
-/
def rankOneCorrection (M : Matrix V V ℝ) (hM : M.IsHermitian) :
    Sym2 V → Matrix V V ℝ :=
  Sym2.lift
    ⟨fun u v ↦
        M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)),
      by
        intro u v
        have huv : M u v = M v u := by
          simpa using hM.apply v u
        change
          M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) =
            M v u • Matrix.vecMulVec (basisDiff v u) (star (basisDiff v u))
        have hOuter :
            Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) =
              Matrix.vecMulVec (basisDiff v u) (star (basisDiff v u)) := by
          rw [basisDiff_swap u v]
          ext i j
          simp [Matrix.vecMulVec_apply]
        rw [huv, hOuter]⟩

@[simp]
lemma rankOneCorrection_mk (M : Matrix V V ℝ) (hM : M.IsHermitian)
    (u v : V) :
    rankOneCorrection M hM s(u, v) =
      M u v • Matrix.vecMulVec (basisDiff u v) (star (basisDiff u v)) :=
  rfl

section Finite

variable [Fintype V]

/-- The finite set of unordered pairs of distinct, nonadjacent vertices. -/
def nonedgeFinset (G : SimpleGraph V) [DecidableRel G.Adj] : Finset (Sym2 V) :=
  Finset.univ.filter fun e ↦ ¬e.IsDiag ∧ e ∉ G.edgeFinset

@[simp]
lemma mk_mem_nonedgeFinset_iff (G : SimpleGraph V) [DecidableRel G.Adj]
    (u v : V) :
    s(u, v) ∈ nonedgeFinset G ↔ u ≠ v ∧ ¬G.Adj u v := by
  simp [nonedgeFinset, SimpleGraph.mem_edgeFinset]

/-- The sum of all unordered nonedge rank-one corrections. -/
def foldingCorrection (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) (hM : M.IsHermitian) : Matrix V V ℝ :=
  ∑ e ∈ nonedgeFinset G, rankOneCorrection M hM e

/-- Fold every off-diagonal nonedge entry of `M` onto the diagonal. -/
def foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    (M : Matrix V V ℝ) (hM : M.IsHermitian) : Matrix V V ℝ :=
  M + foldingCorrection G M hM

omit [Fintype V] in
lemma rankOneCorrection_posSemidef [Finite V] {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (hEntry : EntrywiseNonnegative M) (e : Sym2 V) :
    (rankOneCorrection M hM e).PosSemidef := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk]
  exact (Matrix.posSemidef_vecMulVec_self_star (basisDiff u v)).smul
    (hEntry u v)

lemma foldingCorrection_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) :
    (foldingCorrection G M hM).PosSemidef := by
  exact Matrix.posSemidef_sum (nonedgeFinset G) fun e _ ↦
    rankOneCorrection_posSemidef hM hEntry e

lemma foldNonedges_posSemidef (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hPSD : M.PosSemidef)
    (hEntry : EntrywiseNonnegative M) :
    (foldNonedges G M hPSD.isHermitian).PosSemidef :=
  hPSD.add (foldingCorrection_posSemidef G hPSD.isHermitian hEntry)

omit [Fintype V] in
/--
Away from the diagonal, one rank-one correction is nonzero only at the
ordered entries belonging to its own unordered pair.
-/
lemma rankOneCorrection_apply_offdiag {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (e : Sym2 V) {i j : V} (hij : i ≠ j) :
    rankOneCorrection M hM e i j =
      if e = s(i, j) then -M i j else 0 := by
  induction e using Sym2.inductionOn with | hf u v
  have huv : M u v = M v u := by
    simpa using hM.apply v u
  by_cases heq : s(u, v) = s(i, j)
  · rw [ite_eq_left heq]
    rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
    · simp [basisDiff, Matrix.vecMulVec_apply, hij]
    · simp [basisDiff, Matrix.vecMulVec_apply, hij, huv]
  · rw [ite_eq_right heq]
    have hz :
        (i ≠ u ∧ i ≠ v) ∨ (j ≠ u ∧ j ≠ v) := by
      by_cases hi : i = u ∨ i = v
      · by_cases hj : j = u ∨ j = v
        · rcases hi with rfl | rfl <;> rcases hj with rfl | rfl
          · exact (hij rfl).elim
          · exact (heq rfl).elim
          · exact (heq Sym2.eq_swap).elim
          · exact (hij rfl).elim
        · exact Or.inr ⟨fun h ↦ hj (Or.inl h), fun h ↦ hj (Or.inr h)⟩
      · exact Or.inl ⟨fun h ↦ hi (Or.inl h), fun h ↦ hi (Or.inr h)⟩
    rcases hz with hi | hj
    · simp [rankOneCorrection_mk, Matrix.vecMulVec_apply,
        basisDiff_apply_of_ne hi.1 hi.2]
    · simp [rankOneCorrection_mk, Matrix.vecMulVec_apply,
        basisDiff_apply_of_ne hj.1 hj.2]

/-- Entry formula for the whole correction sum away from the diagonal. -/
lemma foldingCorrection_apply_offdiag (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    {i j : V} (hij : i ≠ j) :
    foldingCorrection G M hM i j =
      if G.Adj i j then 0 else -M i j := by
  classical
  by_cases hadj : G.Adj i j
  · have hnot : s(i, j) ∉ nonedgeFinset G := by
      simp [hij, hadj]
    rw [foldingCorrection, Matrix.sum_apply]
    simp_rw [rankOneCorrection_apply_offdiag hM _ hij]
    simp [hnot, hadj]
  · have hmem : s(i, j) ∈ nonedgeFinset G := by
      simp [hij, hadj]
    rw [foldingCorrection, Matrix.sum_apply]
    simp_rw [rankOneCorrection_apply_offdiag hM _ hij]
    simp [hmem, hadj]

/-- Complete off-diagonal entry formula for the folded matrix. -/
lemma foldNonedges_apply_offdiag (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) {i j : V} (hij : i ≠ j) :
    foldNonedges G M hM i j =
      if G.Adj i j then M i j else 0 := by
  rw [foldNonedges, Matrix.add_apply,
    foldingCorrection_apply_offdiag G hM hij]
  by_cases hadj : G.Adj i j <;> simp [hadj]

/-- Folding preserves every edge entry. -/
lemma foldNonedges_apply_of_adj (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) {i j : V}
    (hij : G.Adj i j) :
    foldNonedges G M hM i j = M i j := by
  rw [foldNonedges_apply_offdiag G hM hij.ne]
  simp [hij]

/-- Folding zeros every off-diagonal nonedge entry. -/
lemma foldNonedges_apply_of_nonedge (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    {i j : V} (hne : i ≠ j) (hij : ¬G.Adj i j) :
    foldNonedges G M hM i j = 0 := by
  rw [foldNonedges_apply_offdiag G hM hne]
  simp [hij]

omit [Fintype V] in
lemma rankOneCorrection_apply_diag_nonneg {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (hEntry : EntrywiseNonnegative M)
    (e : Sym2 V) (i : V) :
    0 ≤ rankOneCorrection M hM e i i := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk]
  simp only [Matrix.smul_apply, smul_eq_mul, Matrix.vecMulVec_apply,
    star_trivial]
  exact mul_nonneg (hEntry u v) (mul_self_nonneg (basisDiff u v i))

lemma foldingCorrection_apply_diag_nonneg (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) (i : V) :
    0 ≤ foldingCorrection G M hM i i := by
  rw [foldingCorrection, Matrix.sum_apply]
  exact Finset.sum_nonneg fun e _ ↦
    rankOneCorrection_apply_diag_nonneg hM hEntry e i

/-- Folding preserves entrywise nonnegativity. -/
lemma foldNonedges_entrywiseNonnegative (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian)
    (hEntry : EntrywiseNonnegative M) :
    EntrywiseNonnegative (foldNonedges G M hM) := by
  intro i j
  by_cases hij : i = j
  · subst j
    rw [foldNonedges, Matrix.add_apply]
    exact add_nonneg (hEntry i i)
      (foldingCorrection_apply_diag_nonneg G hM hEntry i)
  · rw [foldNonedges_apply_offdiag G hM hij]
    by_cases hadj : G.Adj i j
    · simp [hadj, hEntry i j]
    · simp [hadj]

/-- The folded matrix is supported on the graph. -/
lemma foldNonedges_supportedOn (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    SupportedOn G (foldNonedges G M hM) := by
  intro i j hij hnonedge
  exact foldNonedges_apply_of_nonedge G hM hij hnonedge

/-- Folding a DNN matrix produces a graph-supported DNN matrix. -/
lemma foldNonedges_doublyNonnegative (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) :
    DoublyNonnegative (foldNonedges G M hM.isHermitian) :=
  ⟨foldNonedges_posSemidef G hM.posSemidef hM.entrywise,
    foldNonedges_entrywiseNonnegative G hM.isHermitian hM.entrywise⟩

/-- Each rank-one correction has zero total mass. -/
lemma totalMass_rankOneCorrection {M : Matrix V V ℝ}
    (hM : M.IsHermitian) (e : Sym2 V) :
    totalMass (rankOneCorrection M hM e) = 0 := by
  induction e using Sym2.inductionOn with | hf u v
  rw [rankOneCorrection_mk, totalMass_smul]
  change
    M u v *
      totalMass (Matrix.vecMulVec (basisDiff u v) (basisDiff u v)) = 0
  unfold totalMass
  simp only [Matrix.vecMulVec_apply]
  simp_rw [← Finset.mul_sum]
  rw [← Finset.sum_mul, sum_basisDiff]
  simp

lemma totalMass_foldingCorrection (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass (foldingCorrection G M hM) = 0 := by
  rw [foldingCorrection, totalMass_finset_sum]
  simp [totalMass_rankOneCorrection hM]

/-- Folding preserves the sum of all matrix entries. -/
lemma totalMass_foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass (foldNonedges G M hM) = totalMass M := by
  rw [foldNonedges, totalMass_add, totalMass_foldingCorrection]
  simp

/-- Folding preserves the oriented edge-entry mass. -/
lemma edgeMass_foldNonedges (G : SimpleGraph V) [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    edgeMass G (foldNonedges G M hM) = edgeMass G M := by
  apply edgeMass_congr G
  intro i j hij
  exact foldNonedges_apply_of_adj G hM hij

/-- Folding preserves the oriented square-root edge mass. -/
lemma edgeSqrtMass_foldNonedges (G : SimpleGraph V)
    [DecidableRel G.Adj] {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    edgeSqrtMass G (foldNonedges G M hM) = edgeSqrtMass G M := by
  apply edgeSqrtMass_congr G
  intro i j hij
  exact foldNonedges_apply_of_adj G hM hij

omit [DecidableEq V] in
/--
Reduction from the graph-supported sparse inequality to the same inequality
for arbitrary DNN matrices.  The sparse theorem itself is supplied as a
higher-order hypothesis, so this statement is independent of its eventual
name and proof.
-/
theorem supported_sparse_inequality_implies_unrestricted
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hSupported :
      ∀ (N : Matrix V V ℝ),
        DoublyNonnegative N →
        SupportedOn G N →
        edgeSqrtMass G N ^ 2 ≤ graphQ G * totalMass N)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  have hFold :=
    hSupported (foldNonedges G M hM.isHermitian)
      (foldNonedges_doublyNonnegative G hM)
      (foldNonedges_supportedOn G hM.isHermitian)
  rwa [edgeSqrtMass_foldNonedges G hM.isHermitian,
    totalMass_foldNonedges G hM.isHermitian] at hFold

end Finite

end

end SquareEnergy

end

section

/-!
# The cut-vertex induction step

This file proves the cut-vertex branch of the induction for the supported
sparse square-energy inequality.  The convention from `Sq.Sparse.Basic` is
used throughout: `edgeSqrtMass` is an oriented sum, so every unoriented edge
is counted twice.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

universe u

variable {V : Type u}

/-- The graph obtained by deleting `v`.  Its vertices remember that they are
different from `v`. -/
def deleteVertex (G : SimpleGraph V) (v : V) :
    SimpleGraph {x : V // x ≠ v} :=
  G.induce {x | x ≠ v}

@[simp]
lemma deleteVertex_adj (G : SimpleGraph V) (v : V)
    (x y : {x : V // x ≠ v}) :
    (deleteVertex G v).Adj x y ↔ G.Adj x.1 y.1 :=
  Iff.rfl

/-- The vertices of a component of `G - v`, viewed back in `V`. -/
def deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) : Set V :=
  {x | ∃ hx : x ≠ v, (⟨x, hx⟩ : {x : V // x ≠ v}) ∈ C.supp}

@[simp]
lemma mem_deletionComponentVertices_iff (G : SimpleGraph V) (v x : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    x ∈ deletionComponentVertices G v C ↔
      ∃ hx : x ≠ v, (⟨x, hx⟩ : {x : V // x ≠ v}) ∈ C.supp :=
  Iff.rfl

lemma deletionComponentVertices_nonempty (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    (deletionComponentVertices G v C).Nonempty := by
  obtain ⟨x, hx⟩ := C.nonempty_supp
  exact ⟨x.1, x.2, hx⟩

lemma vertex_not_mem_deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    v ∉ deletionComponentVertices G v C := by
  rintro ⟨h, -⟩
  exact h rfl

/-- A component of the deletion, lifted to the original vertex type, still
induces a connected graph. -/
lemma connected_induce_deletionComponentVertices (G : SimpleGraph V) (v : V)
    (C : (deleteVertex G v).ConnectedComponent) :
    (G.induce (deletionComponentVertices G v C)).Connected := by
  let f :
      C.toSimpleGraph →g G.induce (deletionComponentVertices G v C) := {
    toFun x := ⟨x.1.1, ⟨x.1.2, x.2⟩⟩
    map_rel' := by
      intro x y hxy
      exact hxy
  }
  apply C.connected_toSimpleGraph.map f
  intro x
  rcases x with ⟨x, hx, hC⟩
  exact ⟨⟨⟨x, hx⟩, hC⟩, rfl⟩

/-- In a connected graph, every component left after deleting `v` has a
neighbor of `v`. -/
lemma deletionComponent_has_vertex_neighbor (G : SimpleGraph V) (v : V)
    (hG : G.Connected) (C : (deleteVertex G v).ConnectedComponent) :
    ∃ x ∈ deletionComponentVertices G v C, G.Adj v x := by
  obtain ⟨c, hc⟩ := C.nonempty_supp
  obtain ⟨p, hp⟩ := hG.exists_isPath v c.1
  obtain ⟨w, hvw, q, rfl⟩ := p.exists_eq_cons_of_ne c.2.symm
  have hvq : v ∉ q.support := by
    exact (List.nodup_cons.mp hp.support_nodup).1
  have hall : ∀ x ∈ q.support, x ∈ ({x : V | x ≠ v} : Set V) := by
    intro x hx hxv
    exact hvq (hxv ▸ hx)
  have hreach :
      (deleteVertex G v).Reachable
        (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) c := by
    refine ⟨?_⟩
    simpa [deleteVertex] using q.induce ({x : V | x ≠ v}) hall
  have hwC :
      (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) ∈ C.supp := by
    rw [SimpleGraph.ConnectedComponent.mem_supp_iff]
    calc
      (deleteVertex G v).connectedComponentMk
            (⟨w, hvw.ne.symm⟩ : {x : V // x ≠ v}) =
          (deleteVertex G v).connectedComponentMk c :=
        SimpleGraph.ConnectedComponent.sound hreach
      _ = C := (SimpleGraph.ConnectedComponent.mem_supp_iff C c).mp hc
  exact ⟨w, ⟨hvw.ne.symm, hwC⟩, hvw⟩

/-- Adding the deleted vertex back to one deletion component gives a
connected induced graph. -/
lemma connected_induce_component_insert_vertex (G : SimpleGraph V) (v : V)
    (hG : G.Connected) (C : (deleteVertex G v).ConnectedComponent) :
    (G.induce (deletionComponentVertices G v C ∪ {v})).Connected := by
  obtain ⟨x, hxC, hvx⟩ := deletionComponent_has_vertex_neighbor G v hG C
  have hsingle : (G.induce ({v} : Set V)).Preconnected := by
    intro a b
    have hab : a = b := Subtype.ext (by simpa using a.2.trans b.2.symm)
    subst b
    exact SimpleGraph.Reachable.rfl
  exact G.connected_induce_union
    (connected_induce_deletionComponentVertices G v C).preconnected
    hsingle hxC (by simp) hvx.symm

section FiniteGraph

variable [Fintype V] [DecidableEq V]

/-- Data of the two sides of a cut vertex.  `U` and `W` partition all
vertices other than `v`; the two side graphs overlap only at `v`. -/
structure CutPartition (G : SimpleGraph V) (v : V) where
  U : Finset V
  W : Finset V
  v_not_mem_U : v ∉ U
  v_not_mem_W : v ∉ W
  disjoint : Disjoint U W
  union_eq : U ∪ W = Finset.univ.erase v
  U_nonempty : U.Nonempty
  W_nonempty : W.Nonempty
  no_cross : ∀ ⦃u w⦄, u ∈ U → w ∈ W → ¬G.Adj u w
  left_connected :
    (G.induce (↑(insert v U) : Set V)).Connected
  right_connected :
    (G.induce (↑(insert v W) : Set V)).Connected
  left_card_lt : (insert v U).card < Fintype.card V
  right_card_lt : (insert v W).card < Fintype.card V

namespace CutPartition

variable {G : SimpleGraph V} {v : V}

/-- The vertices of the left side graph. -/
def leftVertices (P : CutPartition G v) : Finset V :=
  insert v P.U

/-- The vertices of the right side graph. -/
def rightVertices (P : CutPartition G v) : Finset V :=
  insert v P.W

/-- The graph induced by the left side and the separator. -/
def leftGraph (P : CutPartition G v) : SimpleGraph {x // x ∈ P.leftVertices} :=
  G.induce (↑P.leftVertices : Set V)

/-- The graph induced by the right side and the separator. -/
def rightGraph (P : CutPartition G v) : SimpleGraph {x // x ∈ P.rightVertices} :=
  G.induce (↑P.rightVertices : Set V)

instance instDecidableRelLeftGraph (P : CutPartition G v)
    [DecidableRel G.Adj] : DecidableRel P.leftGraph.Adj := by
  intro x y
  change Decidable (G.Adj x.1 y.1)
  infer_instance

instance instDecidableRelRightGraph (P : CutPartition G v)
    [DecidableRel G.Adj] : DecidableRel P.rightGraph.Adj := by
  intro x y
  change Decidable (G.Adj x.1 y.1)
  infer_instance

@[simp]
lemma leftVertices_eq (P : CutPartition G v) :
    P.leftVertices = insert v P.U :=
  rfl

@[simp]
lemma rightVertices_eq (P : CutPartition G v) :
    P.rightVertices = insert v P.W :=
  rfl

@[simp]
lemma mem_leftVertices (P : CutPartition G v) (x : V) :
    x ∈ P.leftVertices ↔ x = v ∨ x ∈ P.U := by
  simp [leftVertices]

@[simp]
lemma mem_rightVertices (P : CutPartition G v) (x : V) :
    x ∈ P.rightVertices ↔ x = v ∨ x ∈ P.W := by
  simp [rightVertices]

@[simp]
lemma separator_mem_leftVertices (P : CutPartition G v) :
    v ∈ P.leftVertices := by
  simp

@[simp]
lemma separator_mem_rightVertices (P : CutPartition G v) :
    v ∈ P.rightVertices := by
  simp

lemma leftGraph_connected (P : CutPartition G v) :
    P.leftGraph.Connected :=
  P.left_connected

lemma rightGraph_connected (P : CutPartition G v) :
    P.rightGraph.Connected :=
  P.right_connected

lemma card_left_lt (P : CutPartition G v) :
    Fintype.card {x // x ∈ P.leftVertices} < Fintype.card V := by
  rw [Fintype.card_coe]
  exact P.left_card_lt

lemma card_right_lt (P : CutPartition G v) :
    Fintype.card {x // x ∈ P.rightVertices} < Fintype.card V := by
  rw [Fintype.card_coe]
  exact P.right_card_lt

lemma vertex_mem_left_or_right (P : CutPartition G v) (x : V) :
    x ∈ P.leftVertices ∨ x ∈ P.rightVertices := by
  by_cases hx : x = v
  · simp [hx]
  have hxErase : x ∈ Finset.univ.erase v := by simp [hx]
  rw [← P.union_eq] at hxErase
  rcases Finset.mem_union.mp hxErase with hxU | hxW
  · exact Or.inl (by simp [leftVertices, hxU])
  · exact Or.inr (by simp [rightVertices, hxW])

lemma left_right_inter (P : CutPartition G v) :
    P.leftVertices ∩ P.rightVertices = {v} := by
  ext x
  constructor
  · simp only [Finset.mem_inter, mem_leftVertices, mem_rightVertices,
      Finset.mem_singleton]
    rintro ⟨hxv | hxU, hyv | hxW⟩
    · exact hxv
    · exact hxv
    · exact hyv
    · exact (Finset.disjoint_left.mp P.disjoint hxU hxW).elim
  · intro hx
    have hxv : x = v := Finset.mem_singleton.mp hx
    subst x
    simp

lemma adj_side (P : CutPartition G v) {x y : V} (hxy : G.Adj x y) :
    (x ∈ P.leftVertices ∧ y ∈ P.leftVertices) ∨
      (x ∈ P.rightVertices ∧ y ∈ P.rightVertices) := by
  by_cases hxv : x = v
  · subst x
    rcases P.vertex_mem_left_or_right y with hyL | hyR
    · exact Or.inl ⟨separator_mem_leftVertices P, hyL⟩
    · exact Or.inr ⟨separator_mem_rightVertices P, hyR⟩
  by_cases hyv : y = v
  · subst y
    rcases P.vertex_mem_left_or_right x with hxL | hxR
    · exact Or.inl ⟨hxL, separator_mem_leftVertices P⟩
    · exact Or.inr ⟨hxR, separator_mem_rightVertices P⟩
  have hxErase : x ∈ Finset.univ.erase v := by simp [hxv]
  have hyErase : y ∈ Finset.univ.erase v := by simp [hyv]
  rw [← P.union_eq] at hxErase hyErase
  rcases Finset.mem_union.mp hxErase with hxU | hxW
  · rcases Finset.mem_union.mp hyErase with hyU | hyW
    · exact Or.inl ⟨by simp [leftVertices, hxU], by simp [leftVertices, hyU]⟩
    · exact (P.no_cross hxU hyW hxy).elim
  · rcases Finset.mem_union.mp hyErase with hyU | hyW
    · exact (P.no_cross hyU hxW hxy.symm).elim
    · exact Or.inr ⟨by simp [rightVertices, hxW], by simp [rightVertices, hyW]⟩

end CutPartition

/-- A connected graph whose deletion at `v` is not preconnected admits a
two-sided cut partition. -/
theorem exists_cutPartition_of_not_preconnected_delete
    (G : SimpleGraph V) (v : V) (hG : G.Connected)
    (hdelete : ¬(deleteVertex G v).Preconnected) :
    Nonempty (CutPartition G v) := by
  classical
  change ¬(∀ x y, (deleteVertex G v).Reachable x y) at hdelete
  obtain ⟨a, ha⟩ := not_forall.mp hdelete
  obtain ⟨b, hab⟩ := not_forall.mp ha
  let C : (deleteVertex G v).ConnectedComponent :=
    (deleteVertex G v).connectedComponentMk a
  let U : Finset V := (deletionComponentVertices G v C).toFinset
  let W : Finset V := (Finset.univ.erase v) \ U
  have hvU : v ∉ U := by
    simp [U]
  have hUsub : U ⊆ Finset.univ.erase v := by
    intro x hx
    have hxC : x ∈ deletionComponentVertices G v C := by
      simpa [U] using hx
    exact Finset.mem_erase.mpr
      ⟨(fun hxv ↦ vertex_not_mem_deletionComponentVertices G v C (hxv ▸ hxC)),
        Finset.mem_univ x⟩
  have haU : a.1 ∈ U := by
    simp only [U, Set.mem_toFinset, mem_deletionComponentVertices_iff]
    exact ⟨a.2, by simp [C]⟩
  have hbU : b.1 ∉ U := by
    intro hbU
    have hbC : b ∈ C.supp := by
      have hbC' : b.1 ∈ deletionComponentVertices G v C := by
        simpa [U] using hbU
      rcases hbC' with ⟨hbv, hbC'⟩
      simpa only [Subtype.ext_iff] using hbC'
    have hba : (deleteVertex G v).Reachable b a := by
      apply SimpleGraph.ConnectedComponent.exact
      simpa [C] using
        (SimpleGraph.ConnectedComponent.mem_supp_iff C b).mp hbC
    exact hab hba.symm
  have hbW : b.1 ∈ W := by
    exact Finset.mem_sdiff.mpr
      ⟨Finset.mem_erase.mpr ⟨b.2, Finset.mem_univ _⟩, hbU⟩
  have hUW : U ∪ W = Finset.univ.erase v := by
    exact Finset.union_sdiff_of_subset hUsub
  have hdisj : Disjoint U W := by
    exact Finset.disjoint_sdiff
  have hcross : ∀ ⦃u w⦄, u ∈ U → w ∈ W → ¬G.Adj u w := by
    intro u w hu hw huw
    have huC' : u ∈ deletionComponentVertices G v C := by
      simpa [U] using hu
    rcases huC' with ⟨huv, huC⟩
    have hwv : w ≠ v := (Finset.mem_erase.mp (Finset.mem_sdiff.mp hw).1).1
    have hadj :
        (deleteVertex G v).Adj
          (⟨u, huv⟩ : {x : V // x ≠ v}) ⟨w, hwv⟩ := by
      exact huw
    have hwC :
        (⟨w, hwv⟩ : {x : V // x ≠ v}) ∈ C.supp :=
      (C.mem_supp_congr_adj hadj).mp huC
    have hwU : w ∈ U := by
      simp only [U, Set.mem_toFinset, mem_deletionComponentVertices_iff]
      exact ⟨hwv, hwC⟩
    exact (Finset.mem_sdiff.mp hw).2 hwU
  have hleft :
      (G.induce (↑(insert v U) : Set V)).Connected := by
    have hc := connected_induce_component_insert_vertex G v hG C
    have hset :
        (↑(insert v U) : Set V) =
          deletionComponentVertices G v C ∪ {v} := by
      ext x
      simp [U]
    rw [hset]
    exact hc
  have hright :
      (G.induce (↑(insert v W) : Set V)).Connected := by
    apply G.induce_connected_of_patches v (by simp)
    intro x hx
    by_cases hxv : x = v
    · subst x
      refine ⟨{v}, ?_, by simp, by simp, ?_⟩
      · intro y hy
        have hyv : y = v := by simpa using hy
        subst y
        simp
      · exact SimpleGraph.Reachable.rfl
    · have hxW : x ∈ W := by simpa [hxv] using hx
      let x' : {x : V // x ≠ v} := ⟨x, hxv⟩
      let D : (deleteVertex G v).ConnectedComponent :=
        (deleteVertex G v).connectedComponentMk x'
      have hDne : D ≠ C := by
        intro hDC
        have hxC :
            x ∈ deletionComponentVertices G v C := by
          refine ⟨hxv, ?_⟩
          have hxD : x' ∈ D.supp := by
            exact SimpleGraph.ConnectedComponent.connectedComponentMk_mem
          have hxC' : x' ∈ C.supp := hDC ▸ hxD
          simpa [x'] using hxC'
        have hxU : x ∈ U := by simpa [U] using hxC
        exact (Finset.mem_sdiff.mp hxW).2 hxU
      let s : Set V := deletionComponentVertices G v D ∪ {v}
      have hsv : v ∈ s := by simp [s]
      have hsx : x ∈ s := by
        left
        exact ⟨hxv, by simp [D, x']⟩
      refine ⟨s, ?_, hsv, hsx, ?_⟩
      · intro y hy
        rcases hy with hyD | hyv
        · rcases hyD with ⟨hyv, hyDmem⟩
          have hyNotU : y ∉ U := by
            intro hyU
            have hyC' : y ∈ deletionComponentVertices G v C := by
              simpa [U] using hyU
            rcases hyC' with ⟨hyv', hyCmem⟩
            have hDC : D = C := by
              apply SimpleGraph.ConnectedComponent.eq_of_common_vertex
                (v := (⟨y, hyv⟩ : {x : V // x ≠ v}))
              · exact hyDmem
              · simpa only [Subtype.ext_iff] using hyCmem
            exact hDne hDC
          simp only [Finset.mem_coe, Finset.mem_insert]
          exact Or.inr (Finset.mem_sdiff.mpr
            ⟨Finset.mem_erase.mpr ⟨hyv, Finset.mem_univ _⟩, hyNotU⟩)
        · have : y = v := by simpa using hyv
          simp [this]
      · exact (connected_induce_component_insert_vertex G v hG D).preconnected
          ⟨v, hsv⟩ ⟨x, hsx⟩
  have hVdisj : Disjoint (insert v U) W := by
    rw [Finset.disjoint_left]
    intro x hx hW
    rcases Finset.mem_insert.mp hx with rfl | hxU
    · exact (Finset.mem_erase.mp (Finset.mem_sdiff.mp hW).1).1 rfl
    · exact (Finset.mem_sdiff.mp hW).2 hxU
  have hVunion : insert v U ∪ W = Finset.univ := by
    ext x
    by_cases hxv : x = v
    · simp [hxv]
    · have hxErase : x ∈ Finset.univ.erase v := by simp [hxv]
      rw [← hUW] at hxErase
      simpa [hxv] using hxErase
  have hcard :
      (insert v U).card + W.card = Fintype.card V := by
    rw [← Finset.card_union_of_disjoint hVdisj, hVunion,
      Finset.card_univ]
  have hWpos : 0 < W.card := Finset.card_pos.mpr ⟨b.1, hbW⟩
  have hleftCard : (insert v U).card < Fintype.card V := by
    omega
  have hrightDisj : Disjoint (insert v W) U := by
    rw [Finset.disjoint_left]
    intro x hx hU
    rcases Finset.mem_insert.mp hx with rfl | hxW
    · exact hvU hU
    · exact (Finset.mem_sdiff.mp hxW).2 hU
  have hrightUnion : insert v W ∪ U = Finset.univ := by
    rw [Finset.union_comm]
    simpa [Finset.union_assoc, Finset.union_left_comm,
      Finset.union_comm] using hVunion
  have hcardRight :
      (insert v W).card + U.card = Fintype.card V := by
    rw [← Finset.card_union_of_disjoint hrightDisj, hrightUnion,
      Finset.card_univ]
  have hUpos : 0 < U.card := Finset.card_pos.mpr ⟨a.1, haU⟩
  have hrightCard : (insert v W).card < Fintype.card V := by
    omega
  exact ⟨{
    U := U
    W := W
    v_not_mem_U := hvU
    v_not_mem_W := by
      intro hvW
      exact (Finset.mem_erase.mp (Finset.mem_sdiff.mp hvW).1).1 rfl
    disjoint := hdisj
    union_eq := hUW
    U_nonempty := ⟨a.1, haU⟩
    W_nonempty := ⟨b.1, hbW⟩
    no_cross := hcross
    left_connected := hleft
    right_connected := hright
    left_card_lt := hleftCard
    right_card_lt := hrightCard
  }⟩

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)

lemma left_right_edge_intersections_disjoint [DecidableRel G.Adj] :
    Disjoint
      (G.edgeFinset ∩ P.leftVertices.sym2)
      (G.edgeFinset ∩ P.rightVertices.sym2) := by
  classical
  rw [Finset.disjoint_left]
  intro e heL heR
  induction e using Sym2.inductionOn with
  | _ x y =>
      have heL' := Finset.mem_inter.mp heL
      have heR' := Finset.mem_inter.mp heR
      have hxy : G.Adj x y := by
        simpa [SimpleGraph.mem_edgeFinset] using heL'.1
      have hxL : x ∈ P.leftVertices := (Finset.mk_mem_sym2_iff.mp heL'.2).1
      have hyL : y ∈ P.leftVertices := (Finset.mk_mem_sym2_iff.mp heL'.2).2
      have hxR : x ∈ P.rightVertices := (Finset.mk_mem_sym2_iff.mp heR'.2).1
      have hyR : y ∈ P.rightVertices := (Finset.mk_mem_sym2_iff.mp heR'.2).2
      have hxv : x = v := by
        apply Finset.mem_singleton.mp
        rw [← P.left_right_inter]
        exact Finset.mem_inter.mpr ⟨hxL, hxR⟩
      have hyv : y = v := by
        apply Finset.mem_singleton.mp
        rw [← P.left_right_inter]
        exact Finset.mem_inter.mpr ⟨hyL, hyR⟩
      exact hxy.ne (hxv.trans hyv.symm)

lemma left_right_edge_intersections_union [DecidableRel G.Adj] :
    (G.edgeFinset ∩ P.leftVertices.sym2) ∪
        (G.edgeFinset ∩ P.rightVertices.sym2) =
      G.edgeFinset := by
  classical
  ext e
  induction e using Sym2.inductionOn with
  | _ x y =>
      simp only [Finset.mem_union, Finset.mem_inter,
        Finset.mk_mem_sym2_iff]
      constructor
      · rintro (⟨he, -⟩ | ⟨he, -⟩)
        · exact he
        · exact he
      · intro he
        have hxy : G.Adj x y := by
          simpa [SimpleGraph.mem_edgeFinset] using he
        rcases P.adj_side hxy with hL | hR
        · exact Or.inl ⟨he, hL⟩
        · exact Or.inr ⟨he, hR⟩

/-- The side edge sets partition the edge set of `G`. -/
lemma card_edges_left_add_right [DecidableRel G.Adj] :
    P.leftGraph.edgeFinset.card + P.rightGraph.edgeFinset.card =
      G.edgeFinset.card := by
  classical
  have hleft :
      P.leftGraph.edgeFinset.card =
        (G.edgeFinset ∩ P.leftVertices.sym2).card := by
    have hmap :
        P.leftGraph.edgeFinset.map
            (Function.Embedding.subtype (· ∈ P.leftVertices)).sym2Map =
          G.edgeFinset ∩ P.leftVertices.sym2 := by
      ext e
      induction e using Sym2.inductionOn with
      | _ x y =>
          constructor
          · intro he
            rw [Finset.mem_map] at he
            obtain ⟨a, ha, heq⟩ := he
            induction a using Sym2.inductionOn with
            | _ p q =>
                have hpqEdge : s(p, q) ∈ P.leftGraph.edgeSet :=
                  (P.leftGraph.mem_edgeFinset).mp ha
                have hpqSide : P.leftGraph.Adj p q :=
                  (P.leftGraph.mem_edgeSet).mp hpqEdge
                have hpq : G.Adj p.1 q.1 := by
                  exact hpqSide
                change s(p.1, q.1) = s(x, y) at heq
                rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq,
                      Finset.mk_mem_sym2_iff.mpr ⟨p.2, q.2⟩⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq.symm,
                      Finset.mk_mem_sym2_iff.mpr ⟨q.2, p.2⟩⟩
          · intro he
            have he' := Finset.mem_inter.mp he
            have hxy : G.Adj x y := by
              simpa [SimpleGraph.mem_edgeFinset] using he'.1
            obtain ⟨hx, hy⟩ := Finset.mk_mem_sym2_iff.mp he'.2
            rw [Finset.mem_map]
            refine ⟨s((⟨x, hx⟩ : {z // z ∈ P.leftVertices}),
                (⟨y, hy⟩ : {z // z ∈ P.leftVertices})), ?_, rfl⟩
            apply (P.leftGraph.mem_edgeFinset).mpr
            apply (P.leftGraph.mem_edgeSet).mpr
            exact hxy
    rw [← hmap, Finset.card_map]
  have hright :
      P.rightGraph.edgeFinset.card =
        (G.edgeFinset ∩ P.rightVertices.sym2).card := by
    have hmap :
        P.rightGraph.edgeFinset.map
            (Function.Embedding.subtype (· ∈ P.rightVertices)).sym2Map =
          G.edgeFinset ∩ P.rightVertices.sym2 := by
      ext e
      induction e using Sym2.inductionOn with
      | _ x y =>
          constructor
          · intro he
            rw [Finset.mem_map] at he
            obtain ⟨a, ha, heq⟩ := he
            induction a using Sym2.inductionOn with
            | _ p q =>
                have hpqEdge : s(p, q) ∈ P.rightGraph.edgeSet :=
                  (P.rightGraph.mem_edgeFinset).mp ha
                have hpqSide : P.rightGraph.Adj p q :=
                  (P.rightGraph.mem_edgeSet).mp hpqEdge
                have hpq : G.Adj p.1 q.1 := by
                  exact hpqSide
                change s(p.1, q.1) = s(x, y) at heq
                rcases Sym2.eq_iff.mp heq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq,
                      Finset.mk_mem_sym2_iff.mpr ⟨p.2, q.2⟩⟩
                · exact Finset.mem_inter.mpr
                    ⟨by simpa [SimpleGraph.mem_edgeFinset] using hpq.symm,
                      Finset.mk_mem_sym2_iff.mpr ⟨q.2, p.2⟩⟩
          · intro he
            have he' := Finset.mem_inter.mp he
            have hxy : G.Adj x y := by
              simpa [SimpleGraph.mem_edgeFinset] using he'.1
            obtain ⟨hx, hy⟩ := Finset.mk_mem_sym2_iff.mp he'.2
            rw [Finset.mem_map]
            refine ⟨s((⟨x, hx⟩ : {z // z ∈ P.rightVertices}),
                (⟨y, hy⟩ : {z // z ∈ P.rightVertices})), ?_, rfl⟩
            apply (P.rightGraph.mem_edgeFinset).mpr
            apply (P.rightGraph.mem_edgeSet).mpr
            exact hxy
    rw [← hmap, Finset.card_map]
  rw [hleft, hright, ← Finset.card_union_of_disjoint
    P.left_right_edge_intersections_disjoint,
    P.left_right_edge_intersections_union]

lemma card_vertices_left_add_right :
    Fintype.card {x // x ∈ P.leftVertices} +
        Fintype.card {x // x ∈ P.rightVertices} =
      Fintype.card V + 1 := by
  classical
  rw [Fintype.card_coe, Fintype.card_coe]
  have hparts :
      P.U.card + P.W.card = (Finset.univ.erase v).card := by
    rw [← Finset.card_union_of_disjoint P.disjoint, P.union_eq]
  have herase :
      (Finset.univ.erase v).card = Fintype.card V - 1 :=
    Finset.card_erase_of_mem (Finset.mem_univ v)
  have hVpos : 0 < Fintype.card V := Fintype.card_pos_iff.mpr ⟨v⟩
  simp only [leftVertices, rightVertices,
    Finset.card_insert_of_notMem P.v_not_mem_U,
    Finset.card_insert_of_notMem P.v_not_mem_W]
  omega

/-- The graph parameters of the two sides add to the graph parameter of the
original graph. -/
lemma graphQ_left_add_right [DecidableRel G.Adj] :
    graphQ P.leftGraph + graphQ P.rightGraph = graphQ G := by
  have hE := P.card_edges_left_add_right
  have hV := P.card_vertices_left_add_right
  have hEr :
      (P.leftGraph.edgeFinset.card : ℝ) +
          (P.rightGraph.edgeFinset.card : ℝ) =
        (G.edgeFinset.card : ℝ) := by
    exact_mod_cast hE
  have hVr :
      (Fintype.card {x // x ∈ P.leftVertices} : ℝ) +
          (Fintype.card {x // x ∈ P.rightVertices} : ℝ) =
        (Fintype.card V : ℝ) + 1 := by
    exact_mod_cast hV
  simp only [graphQ]
  linarith

end CutPartition

/-- The finite set of oriented edges. -/
def orientedEdgeFinset (G : SimpleGraph V) [DecidableRel G.Adj] :
    Finset ((_u : V) × V) :=
  Finset.univ.sigma fun u ↦ G.neighborFinset u

omit [DecidableEq V] in
@[simp]
lemma mem_orientedEdgeFinset_iff (G : SimpleGraph V) [DecidableRel G.Adj]
    (u w : V) :
    Sigma.mk u w ∈ orientedEdgeFinset G ↔ G.Adj u w := by
  simp [orientedEdgeFinset]

omit [DecidableEq V] in
lemma edgeSqrtMass_eq_sum_orientedEdgeFinset
    (G : SimpleGraph V) [DecidableRel G.Adj] (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      (orientedEdgeFinset G).sum fun e ↦ √(M e.1 e.2) := by
  exact Finset.sum_sigma' Finset.univ (fun u ↦ G.neighborFinset u)
    (fun u w ↦ √(M u w))

/-- The embedding of ordered pairs of vertices in a finite set back into the
ambient ordered-pair type. -/
def orientedSubtypeEmbedding (s : Finset V) :
    (((_u : {x // x ∈ s}) × {x // x ∈ s}) ↪ ((_u : V) × V)) where
  toFun e := Sigma.mk e.1.1 e.2.1
  inj' := by
    rintro ⟨x, y⟩ ⟨x', y'⟩ h
    change
      (@Sigma.mk V (fun _ : V ↦ V) x.1 y.1) =
        (@Sigma.mk V (fun _ : V ↦ V) x'.1 y'.1) at h
    have hx : x = x' := Subtype.ext (congrArg Sigma.fst h)
    subst x'
    have hy : y = y' := Subtype.ext (by
      exact congrArg (fun e ↦ e.2) h)
    subst y'
    rfl

lemma map_orientedEdgeFinset_induce (G : SimpleGraph V)
    [DecidableRel G.Adj] (s : Finset V) :
    (orientedEdgeFinset (G.induce (↑s : Set V))).map
        (orientedSubtypeEmbedding s) =
      (orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ s ∧ e.2 ∈ s) := by
  classical
  ext e
  rcases e with ⟨x, y⟩
  constructor
  · intro he
    rw [Finset.mem_map] at he
    obtain ⟨⟨x', y'⟩, hxy', heq⟩ := he
    change
      (@Sigma.mk V (fun _ : V ↦ V) x'.1 y'.1) =
        (@Sigma.mk V (fun _ : V ↦ V) x y) at heq
    have hx : x'.1 = x := congrArg Sigma.fst heq
    subst x
    have hy : y'.1 = y := by
      exact congrArg (fun e ↦ e.2) heq
    subst y
    simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff]
    exact ⟨by simpa using hxy', x'.2, y'.2⟩
  · simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff]
    rintro ⟨hxy, hx, hy⟩
    rw [Finset.mem_map]
    refine ⟨Sigma.mk (⟨x, hx⟩ : {z // z ∈ s}) (⟨y, hy⟩ : {z // z ∈ s}), ?_, rfl⟩
    simpa using hxy

/-- Oriented edge sums on an induced graph can be evaluated in the ambient
graph when all induced-edge entries are preserved. -/
lemma edgeSqrtMass_induce_eq_filtered_oriented_sum
    (G : SimpleGraph V) [DecidableRel G.Adj] (s : Finset V)
    (N : Matrix {x // x ∈ s} {x // x ∈ s} ℝ) (M : Matrix V V ℝ)
    (hentry : ∀ ⦃x y : {x // x ∈ s}⦄,
      (G.induce (↑s : Set V)).Adj x y → N x y = M x.1 y.1) :
    edgeSqrtMass (G.induce (↑s : Set V)) N =
      ((orientedEdgeFinset G).filter
          (fun e ↦ e.1 ∈ s ∧ e.2 ∈ s)).sum
        (fun e ↦ √(M e.1 e.2)) := by
  classical
  rw [edgeSqrtMass_eq_sum_orientedEdgeFinset]
  rw [← map_orientedEdgeFinset_induce G s]
  rw [Finset.sum_map]
  apply Finset.sum_congr rfl
  intro e he
  rw [hentry (by simpa [orientedEdgeFinset] using he)]
  rfl

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)

lemma filtered_oriented_edges_disjoint [DecidableRel G.Adj] :
    Disjoint
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.leftVertices ∧ e.2 ∈ P.leftVertices))
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.rightVertices ∧ e.2 ∈ P.rightVertices)) := by
  classical
  rw [Finset.disjoint_left]
  rintro ⟨x, y⟩ hx hy
  simp only [Finset.mem_filter, mem_orientedEdgeFinset_iff] at hx hy
  have hxv : x = v := by
    apply Finset.mem_singleton.mp
    rw [← P.left_right_inter]
    exact Finset.mem_inter.mpr ⟨hx.2.1, hy.2.1⟩
  have hyv : y = v := by
    apply Finset.mem_singleton.mp
    rw [← P.left_right_inter]
    exact Finset.mem_inter.mpr ⟨hx.2.2, hy.2.2⟩
  exact hx.1.ne (hxv.trans hyv.symm)

lemma filtered_oriented_edges_union [DecidableRel G.Adj] :
    ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.leftVertices ∧ e.2 ∈ P.leftVertices)) ∪
      ((orientedEdgeFinset G).filter
        (fun e ↦ e.1 ∈ P.rightVertices ∧ e.2 ∈ P.rightVertices)) =
      orientedEdgeFinset G := by
  classical
  ext e
  rcases e with ⟨x, y⟩
  simp only [Finset.mem_union, Finset.mem_filter,
    mem_orientedEdgeFinset_iff]
  constructor
  · rintro (⟨hxy, -⟩ | ⟨hxy, -⟩)
    · exact hxy
    · exact hxy
  · intro hxy
    rcases P.adj_side hxy with hL | hR
    · exact Or.inl ⟨hxy, hL⟩
    · exact Or.inr ⟨hxy, hR⟩

/-- The two induced oriented edge sums add to the oriented edge sum of the
original graph, provided their edge entries agree with the original matrix. -/
lemma edgeSqrtMass_left_add_right
    [DecidableRel G.Adj]
    (M₁ : Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ)
    (M₂ : Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ)
    (M : Matrix V V ℝ)
    (h₁ : ∀ ⦃x y⦄, P.leftGraph.Adj x y → M₁ x y = M x.1 y.1)
    (h₂ : ∀ ⦃x y⦄, P.rightGraph.Adj x y → M₂ x y = M x.1 y.1) :
    edgeSqrtMass P.leftGraph M₁ + edgeSqrtMass P.rightGraph M₂ =
      edgeSqrtMass G M := by
  change
    edgeSqrtMass (G.induce (↑P.leftVertices : Set V)) M₁ +
        edgeSqrtMass (G.induce (↑P.rightVertices : Set V)) M₂ =
      edgeSqrtMass G M
  rw [edgeSqrtMass_induce_eq_filtered_oriented_sum G P.leftVertices M₁ M h₁,
    edgeSqrtMass_induce_eq_filtered_oriented_sum G P.rightVertices M₂ M h₂,
    edgeSqrtMass_eq_sum_orientedEdgeFinset]
  rw [← Finset.sum_union P.filtered_oriented_edges_disjoint,
    P.filtered_oriented_edges_union]

end CutPartition

/-- A positive semidefinite real matrix is a Gram matrix in a finite
Euclidean space. -/
lemma exists_eq_gram_of_posSemidef {I : Type*} [Finite I]
    {M : Matrix I I ℝ} (hM : M.PosSemidef) :
    ∃ (m : ℕ) (z : I → EuclideanSpace ℝ (Fin m)),
      M = Matrix.gram ℝ z := by
  obtain ⟨m, a, ha⟩ :=
    Matrix.posSemidef_iff_eq_sum_vecMulVec.mp hM
  refine ⟨m, fun u ↦ WithLp.toLp 2 (fun k ↦ a k u), ?_⟩
  rw [ha]
  ext u w
  simp [Matrix.sum_apply, Matrix.gram_apply, Matrix.vecMulVec_apply,
    EuclideanSpace.inner_eq_star_dotProduct, dotProduct, mul_comm]

/-- The total entry mass of a Gram matrix is the squared norm of the sum of
its representing vectors. -/
lemma totalMass_gram {I E : Type*} [Fintype I]
    [NormedAddCommGroup E] [InnerProductSpace ℝ E] (z : I → E) :
    totalMass (Matrix.gram ℝ z) = ‖∑ i, z i‖ ^ 2 := by
  unfold totalMass
  simp only [Matrix.gram_apply]
  calc
    (∑ i, ∑ j, inner ℝ (z i) (z j)) =
        ∑ i, inner ℝ (z i) (∑ j, z j) := by
      apply Finset.sum_congr rfl
      intro i _
      exact (inner_sum Finset.univ z (z i)).symm
    _ = inner ℝ (∑ i, z i) (∑ j, z j) :=
      (sum_inner Finset.univ z _).symm
    _ = ‖∑ i, z i‖ ^ 2 := real_inner_self_eq_norm_sq _

namespace CutPartition

variable {G : SimpleGraph V} {v : V} (P : CutPartition G v)
variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E]

/-- Span of the Gram vectors on the open left side. -/
def leftSpan (z : V → E) : Submodule ℝ E :=
  Submodule.span ℝ (z '' (↑P.U : Set V))

/-- Span of the Gram vectors on the open right side. -/
def rightSpan (z : V → E) : Submodule ℝ E :=
  Submodule.span ℝ (z '' (↑P.W : Set V))

lemma mem_leftSpan (z : V → E) {u : V} (hu : u ∈ P.U) :
    z u ∈ P.leftSpan z := by
  apply Submodule.subset_span
  exact ⟨u, hu, rfl⟩

lemma mem_rightSpan (z : V → E) {w : V} (hw : w ∈ P.W) :
    z w ∈ P.rightSpan z := by
  apply Submodule.subset_span
  exact ⟨w, hw, rfl⟩

/-- Support on `G` makes the spans generated by the two open sides
orthogonal. -/
lemma rightSpan_le_leftSpan_orthogonal
    {M : Matrix V V ℝ} (hSupport : SupportedOn G M)
    (z : V → E) (hgram : M = Matrix.gram ℝ z) :
    P.rightSpan z ≤ (P.leftSpan z)ᗮ := by
  rw [rightSpan, Submodule.span_le]
  rintro y ⟨w, hw, rfl⟩
  apply (Submodule.mem_orthogonal (P.leftSpan z) (z w)).2
  intro x hx
  refine Submodule.span_induction ?_ (by simp) ?_ ?_ hx
  · rintro _ ⟨u, hu, rfl⟩
    have huw : u ≠ w := by
      intro huw
      subst w
      exact (Finset.disjoint_left.mp P.disjoint hu hw)
    have hnon : ¬G.Adj u w := P.no_cross hu hw
    have hzero : M u w = 0 := hSupport huw hnon
    simpa [hgram, Matrix.gram_apply] using hzero
  · intro x y hx hy hix hiy
    simp [inner_add_left, hix, hiy]
  · intro a x hx hix
    simp [inner_smul_left, hix]

/-- The sequential orthogonal-projection decomposition of the separator
Gram vector. -/
structure SeparatorProjection (z : V → E) where
  pU : E
  pW : E
  p0 : E
  separator_eq : z v = pU + pW + p0
  pU_mem_left : pU ∈ P.leftSpan z
  pW_mem_right : pW ∈ P.rightSpan z
  pW_mem_leftOrth : pW ∈ (P.leftSpan z)ᗮ
  pU_mem_rightOrth : pU ∈ (P.rightSpan z)ᗮ
  p0_mem_leftOrth : p0 ∈ (P.leftSpan z)ᗮ
  p0_mem_rightOrth : p0 ∈ (P.rightSpan z)ᗮ
  rightSpan_le_leftOrth : P.rightSpan z ≤ (P.leftSpan z)ᗮ

/-- Construct the separator decomposition by first projecting onto the left
span and then projecting the residual onto the right span. -/
def separatorProjection [FiniteDimensional ℝ E]
    {M : Matrix V V ℝ} (hSupport : SupportedOn G M)
    (z : V → E) (hgram : M = Matrix.gram ℝ z) :
    P.SeparatorProjection z := by
  let L : Submodule ℝ E := P.leftSpan z
  let R : Submodule ℝ E := P.rightSpan z
  let pU : E := L.starProjection (z v)
  let r : E := z v - pU
  let pW : E := R.starProjection r
  let p0 : E := r - pW
  have hpU : pU ∈ L := L.starProjection_apply_mem _
  have hrL : r ∈ Lᗮ := Submodule.sub_starProjection_mem_orthogonal _
  have hpW : pW ∈ R := R.starProjection_apply_mem _
  have hRL : R ≤ Lᗮ :=
    P.rightSpan_le_leftSpan_orthogonal hSupport z hgram
  have hpWL : pW ∈ Lᗮ := by
    exact hRL hpW
  have hp0R : p0 ∈ Rᗮ := Submodule.sub_starProjection_mem_orthogonal _
  have hp0L : p0 ∈ Lᗮ := by
    exact Submodule.sub_mem _ hrL hpWL
  have hpUR : pU ∈ Rᗮ := by
    apply (Submodule.mem_orthogonal R pU).2
    intro y hy
    have hyL : y ∈ Lᗮ := hRL hy
    have hzero : inner ℝ pU y = 0 :=
      (Submodule.mem_orthogonal L y).1 hyL pU hpU
    simpa [real_inner_comm] using hzero
  refine {
    pU := pU
    pW := pW
    p0 := p0
    separator_eq := ?_
    pU_mem_left := hpU
    pW_mem_right := hpW
    pW_mem_leftOrth := hpWL
    pU_mem_rightOrth := hpUR
    p0_mem_leftOrth := hp0L
    p0_mem_rightOrth := hp0R
    rightSpan_le_leftOrth := hRL
  }
  dsimp [p0, r]
  abel

namespace SeparatorProjection

variable {P : CutPartition G v} {z : V → E}

/-- The separator vector assigned to the left side. -/
def leftSeparator (S : P.SeparatorProjection z) : E :=
  S.pU + S.p0

/-- The separator vector assigned to the right side. -/
def rightSeparator (S : P.SeparatorProjection z) : E :=
  S.pW

lemma leftSeparator_add_rightSeparator (S : P.SeparatorProjection z) :
    S.leftSeparator + S.rightSeparator = z v := by
  rw [S.separator_eq]
  simp only [leftSeparator, rightSeparator]
  abel

lemma leftSeparator_inner_eq (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    inner ℝ S.leftSeparator (z u) = inner ℝ (z v) (z u) := by
  have hzu : z u ∈ P.leftSpan z := P.mem_leftSpan z hu
  have hpWzero : inner ℝ S.pW (z u) = 0 :=
    (Submodule.mem_orthogonal' (P.leftSpan z) S.pW).1
      S.pW_mem_leftOrth (z u) hzu
  have hsep : S.leftSeparator = z v - S.pW := by
    rw [S.separator_eq]
    simp only [leftSeparator]
    abel
  rw [hsep, inner_sub_left, hpWzero, sub_zero]

lemma inner_leftSeparator_eq (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    inner ℝ (z u) S.leftSeparator = inner ℝ (z u) (z v) := by
  simpa [real_inner_comm] using S.leftSeparator_inner_eq hu

lemma rightSeparator_inner_eq (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    inner ℝ S.rightSeparator (z w) = inner ℝ (z v) (z w) := by
  have hzw : z w ∈ P.rightSpan z := P.mem_rightSpan z hw
  have hpUzero : inner ℝ S.pU (z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.pU).1
      S.pU_mem_rightOrth (z w) hzw
  have hp0zero : inner ℝ S.p0 (z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.p0).1
      S.p0_mem_rightOrth (z w) hzw
  rw [S.separator_eq]
  simp only [rightSeparator, inner_add_left, hpUzero, hp0zero,
    zero_add, add_zero]

lemma inner_rightSeparator_eq (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    inner ℝ (z w) S.rightSeparator = inner ℝ (z w) (z v) := by
  simpa [real_inner_comm] using S.rightSeparator_inner_eq hw

/-- Gram vectors for the left side. -/
def leftVector (S : P.SeparatorProjection z) :
    {x // x ∈ P.leftVertices} → E :=
  fun x ↦ if x.1 = v then S.leftSeparator else z x.1

/-- Gram vectors for the right side. -/
def rightVector (S : P.SeparatorProjection z) :
    {x // x ∈ P.rightVertices} → E :=
  fun x ↦ if x.1 = v then S.rightSeparator else z x.1

@[simp]
lemma leftVector_separator (S : P.SeparatorProjection z) :
    S.leftVector ⟨v, P.separator_mem_leftVertices⟩ = S.leftSeparator := by
  simp [leftVector]

@[simp]
lemma rightVector_separator (S : P.SeparatorProjection z) :
    S.rightVector ⟨v, P.separator_mem_rightVertices⟩ = S.rightSeparator := by
  simp [rightVector]

lemma leftVector_of_mem_U (S : P.SeparatorProjection z)
    {u : V} (hu : u ∈ P.U) :
    S.leftVector ⟨u, by simp [CutPartition.leftVertices, hu]⟩ = z u := by
  have huv : u ≠ v := by
    intro huv
    subst u
    exact P.v_not_mem_U hu
  simp [leftVector, huv]

lemma rightVector_of_mem_W (S : P.SeparatorProjection z)
    {w : V} (hw : w ∈ P.W) :
    S.rightVector ⟨w, by simp [CutPartition.rightVertices, hw]⟩ = z w := by
  have hwv : w ≠ v := by
    intro hwv
    subst w
    exact P.v_not_mem_W hw
  simp [rightVector, hwv]

/-- Left side Gram matrix. -/
def leftMatrix (S : P.SeparatorProjection z) :
    Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ :=
  Matrix.gram ℝ S.leftVector

/-- Right side Gram matrix. -/
def rightMatrix (S : P.SeparatorProjection z) :
    Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ :=
  Matrix.gram ℝ S.rightVector

/-- Every off-diagonal left-side entry is inherited from the original Gram
matrix. -/
lemma leftMatrix_apply_of_ne (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.leftVertices}} (hxy : x ≠ y) :
    S.leftMatrix x y = M x.1 y.1 := by
  rw [leftMatrix, Matrix.gram_apply]
  by_cases hx : x.1 = v
  · by_cases hy : y.1 = v
    · exact (hxy (Subtype.ext (hx.trans hy.symm))).elim
    · have hyU : y.1 ∈ P.U :=
        (P.mem_leftVertices y.1).mp y.2 |>.resolve_left hy
      rw [leftVector, ite_eq_left hx, leftVector, ite_eq_right hy,
        S.leftSeparator_inner_eq hyU, hgram, Matrix.gram_apply]
      simp [hx]
  · by_cases hy : y.1 = v
    · have hxU : x.1 ∈ P.U :=
        (P.mem_leftVertices x.1).mp x.2 |>.resolve_left hx
      rw [leftVector, ite_eq_right hx, leftVector, ite_eq_left hy,
        S.inner_leftSeparator_eq hxU, hgram, Matrix.gram_apply]
      simp [hy]
    · rw [leftVector, ite_eq_right hx, leftVector, ite_eq_right hy,
        hgram, Matrix.gram_apply]

/-- Every off-diagonal right-side entry is inherited from the original Gram
matrix. -/
lemma rightMatrix_apply_of_ne (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.rightVertices}} (hxy : x ≠ y) :
    S.rightMatrix x y = M x.1 y.1 := by
  rw [rightMatrix, Matrix.gram_apply]
  by_cases hx : x.1 = v
  · by_cases hy : y.1 = v
    · exact (hxy (Subtype.ext (hx.trans hy.symm))).elim
    · have hyW : y.1 ∈ P.W :=
        (P.mem_rightVertices y.1).mp y.2 |>.resolve_left hy
      rw [rightVector, ite_eq_left hx, rightVector, ite_eq_right hy,
        S.rightSeparator_inner_eq hyW, hgram, Matrix.gram_apply]
      simp [hx]
  · by_cases hy : y.1 = v
    · have hxW : x.1 ∈ P.W :=
        (P.mem_rightVertices x.1).mp x.2 |>.resolve_left hx
      rw [rightVector, ite_eq_right hx, rightVector, ite_eq_left hy,
        S.inner_rightSeparator_eq hxW, hgram, Matrix.gram_apply]
      simp [hy]
    · rw [rightVector, ite_eq_right hx, rightVector, ite_eq_right hy,
        hgram, Matrix.gram_apply]

lemma leftMatrix_doublyNonnegative (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hgram : M = Matrix.gram ℝ z) :
    DoublyNonnegative S.leftMatrix := by
  refine ⟨Matrix.posSemidef_gram ℝ S.leftVector, ?_⟩
  intro x y
  by_cases hxy : x = y
  · subst y
    exact real_inner_self_nonneg
  · rw [S.leftMatrix_apply_of_ne hgram hxy]
    exact hM.entry_nonneg x.1 y.1

lemma rightMatrix_doublyNonnegative (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hgram : M = Matrix.gram ℝ z) :
    DoublyNonnegative S.rightMatrix := by
  refine ⟨Matrix.posSemidef_gram ℝ S.rightVector, ?_⟩
  intro x y
  by_cases hxy : x = y
  · subst y
    exact real_inner_self_nonneg
  · rw [S.rightMatrix_apply_of_ne hgram hxy]
    exact hM.entry_nonneg x.1 y.1

lemma leftMatrix_supportedOn (S : P.SeparatorProjection z) {M : Matrix V V ℝ}
    (hSupport : SupportedOn G M) (hgram : M = Matrix.gram ℝ z) :
    SupportedOn P.leftGraph S.leftMatrix := by
  intro x y hxy hnon
  rw [S.leftMatrix_apply_of_ne hgram hxy]
  apply hSupport
  · intro hval
    exact hxy (Subtype.ext hval)
  · exact hnon

lemma rightMatrix_supportedOn (S : P.SeparatorProjection z) {M : Matrix V V ℝ}
    (hSupport : SupportedOn G M) (hgram : M = Matrix.gram ℝ z) :
    SupportedOn P.rightGraph S.rightMatrix := by
  intro x y hxy hnon
  rw [S.rightMatrix_apply_of_ne hgram hxy]
  apply hSupport
  · intro hval
    exact hxy (Subtype.ext hval)
  · exact hnon

lemma leftMatrix_apply_of_adj (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.leftVertices}} (hxy : P.leftGraph.Adj x y) :
    S.leftMatrix x y = M x.1 y.1 :=
  S.leftMatrix_apply_of_ne hgram hxy.ne

lemma rightMatrix_apply_of_adj (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z)
    {x y : {x // x ∈ P.rightVertices}} (hxy : P.rightGraph.Adj x y) :
    S.rightMatrix x y = M x.1 y.1 :=
  S.rightMatrix_apply_of_ne hgram hxy.ne

lemma sum_leftVector (S : P.SeparatorProjection z) :
    ∑ x, S.leftVector x = S.leftSeparator + ∑ u ∈ P.U, z u := by
  let f : V → E := fun x ↦ if x = v then S.leftSeparator else z x
  change (∑ x : {x // x ∈ P.leftVertices}, f x.1) =
    S.leftSeparator + ∑ u ∈ P.U, z u
  rw [← Finset.sum_subtype P.leftVertices (fun _ ↦ Iff.rfl) f]
  rw [leftVertices, Finset.sum_insert P.v_not_mem_U]
  simp only [f, ite_eq_left]
  congr 1
  apply Finset.sum_congr rfl
  intro u hu
  have huv : u ≠ v := by
    intro huv
    subst u
    exact P.v_not_mem_U hu
  simp [huv]

lemma sum_rightVector (S : P.SeparatorProjection z) :
    ∑ x, S.rightVector x = S.rightSeparator + ∑ w ∈ P.W, z w := by
  let f : V → E := fun x ↦ if x = v then S.rightSeparator else z x
  change (∑ x : {x // x ∈ P.rightVertices}, f x.1) =
    S.rightSeparator + ∑ w ∈ P.W, z w
  rw [← Finset.sum_subtype P.rightVertices (fun _ ↦ Iff.rfl) f]
  rw [rightVertices, Finset.sum_insert P.v_not_mem_W]
  simp only [f, ite_eq_left]
  congr 1
  apply Finset.sum_congr rfl
  intro w hw
  have hwv : w ≠ v := by
    intro hwv
    subst w
    exact P.v_not_mem_W hw
  simp [hwv]

lemma sum_original_eq (_S : P.SeparatorProjection z) :
    ∑ x, z x =
      z v + (∑ u ∈ P.U, z u) + ∑ w ∈ P.W, z w := by
  calc
    (∑ x, z x) = z v + ∑ x ∈ Finset.univ.erase v, z x :=
      (Finset.add_sum_erase Finset.univ z (Finset.mem_univ v)).symm
    _ = z v + ∑ x ∈ P.U ∪ P.W, z x := by rw [P.union_eq]
    _ = z v + ((∑ u ∈ P.U, z u) + ∑ w ∈ P.W, z w) := by
      rw [Finset.sum_union P.disjoint]
    _ = _ := by abel

lemma sum_leftVector_add_sum_rightVector (S : P.SeparatorProjection z) :
    (∑ x, S.leftVector x) + (∑ x, S.rightVector x) = ∑ x, z x := by
  rw [S.sum_leftVector, S.sum_rightVector, S.sum_original_eq]
  rw [← S.leftSeparator_add_rightSeparator]
  abel

lemma inner_sum_leftVector_sum_rightVector (S : P.SeparatorProjection z) :
    inner ℝ (∑ x, S.leftVector x) (∑ x, S.rightVector x) = 0 := by
  have hsumU : (∑ u ∈ P.U, z u) ∈ P.leftSpan z :=
    (P.leftSpan z).sum_mem fun u hu ↦ P.mem_leftSpan z hu
  have hsumW : (∑ w ∈ P.W, z w) ∈ P.rightSpan z :=
    (P.rightSpan z).sum_mem fun w hw ↦ P.mem_rightSpan z hw
  have hright :
      S.rightSeparator + (∑ w ∈ P.W, z w) ∈ P.rightSpan z :=
    (P.rightSpan z).add_mem S.pW_mem_right hsumW
  have hpUzero :
      inner ℝ S.pU (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.pU).1
      S.pU_mem_rightOrth _ hright
  have hp0zero :
      inner ℝ S.p0 (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal' (P.rightSpan z) S.p0).1
      S.p0_mem_rightOrth _ hright
  have hrightLeftOrth :
      S.rightSeparator + (∑ w ∈ P.W, z w) ∈ (P.leftSpan z)ᗮ := by
    exact (P.leftSpan z)ᗮ.add_mem S.pW_mem_leftOrth
      (S.rightSpan_le_leftOrth hsumW)
  have hsumUzero :
      inner ℝ (∑ u ∈ P.U, z u)
        (S.rightSeparator + ∑ w ∈ P.W, z w) = 0 :=
    (Submodule.mem_orthogonal (P.leftSpan z) _).1
      hrightLeftOrth _ hsumU
  rw [S.sum_leftVector, S.sum_rightVector]
  simp only [leftSeparator, inner_add_left, hpUzero, hp0zero,
    hsumUzero, zero_add]

lemma totalMass_left_add_right (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z) :
    totalMass M = totalMass S.leftMatrix + totalMass S.rightMatrix := by
  rw [hgram, leftMatrix, rightMatrix, totalMass_gram, totalMass_gram,
    totalMass_gram]
  calc
    ‖∑ x, z x‖ ^ 2 =
        ‖(∑ x, S.leftVector x) + ∑ x, S.rightVector x‖ ^ 2 := by
      rw [S.sum_leftVector_add_sum_rightVector]
    _ = ‖∑ x, S.leftVector x‖ ^ 2 +
        ‖∑ x, S.rightVector x‖ ^ 2 := by
      simpa [pow_two] using
        norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero
          (∑ x, S.leftVector x) (∑ x, S.rightVector x)
          S.inner_sum_leftVector_sum_rightVector

lemma edgeSqrtMass_leftMatrix_add_rightMatrix
    [DecidableRel G.Adj] (S : P.SeparatorProjection z)
    {M : Matrix V V ℝ} (hgram : M = Matrix.gram ℝ z) :
    edgeSqrtMass P.leftGraph S.leftMatrix +
        edgeSqrtMass P.rightGraph S.rightMatrix =
      edgeSqrtMass G M := by
  exact P.edgeSqrtMass_left_add_right S.leftMatrix S.rightMatrix M
    (fun {_ _} hxy ↦ S.leftMatrix_apply_of_adj hgram hxy)
    (fun {_ _} hxy ↦ S.rightMatrix_apply_of_adj hgram hxy)

end SeparatorProjection

/-- The two side matrices supplied by the separator geometry, together with
all properties needed by the induction step. -/
structure OneSeparatorSplit [DecidableRel G.Adj] (M : Matrix V V ℝ) where
  leftMatrix :
    Matrix {x // x ∈ P.leftVertices} {x // x ∈ P.leftVertices} ℝ
  rightMatrix :
    Matrix {x // x ∈ P.rightVertices} {x // x ∈ P.rightVertices} ℝ
  left_dnn : DoublyNonnegative leftMatrix
  right_dnn : DoublyNonnegative rightMatrix
  left_supported : SupportedOn P.leftGraph leftMatrix
  right_supported : SupportedOn P.rightGraph rightMatrix
  left_edge_entry :
    ∀ ⦃x y⦄, P.leftGraph.Adj x y → leftMatrix x y = M x.1 y.1
  right_edge_entry :
    ∀ ⦃x y⦄, P.rightGraph.Adj x y → rightMatrix x y = M x.1 y.1
  edgeSqrtMass_eq :
    edgeSqrtMass P.leftGraph leftMatrix +
        edgeSqrtMass P.rightGraph rightMatrix =
      edgeSqrtMass G M
  totalMass_eq :
    totalMass M = totalMass leftMatrix + totalMass rightMatrix

/-- Package the Gram/projection construction into the reusable two-block
split used by the cut-vertex induction branch. -/
theorem oneSeparatorSplit [DecidableRel G.Adj]
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M) :
    Nonempty (P.OneSeparatorSplit M) := by
  obtain ⟨m, z, hgram⟩ := exists_eq_gram_of_posSemidef hM.posSemidef
  let S : P.SeparatorProjection z :=
    P.separatorProjection hSupport z hgram
  exact ⟨{
    leftMatrix := S.leftMatrix
    rightMatrix := S.rightMatrix
    left_dnn := S.leftMatrix_doublyNonnegative hM hgram
    right_dnn := S.rightMatrix_doublyNonnegative hM hgram
    left_supported := S.leftMatrix_supportedOn hSupport hgram
    right_supported := S.rightMatrix_supportedOn hSupport hgram
    left_edge_entry := fun {_ _} hxy ↦ S.leftMatrix_apply_of_adj hgram hxy
    right_edge_entry := fun {_ _} hxy ↦ S.rightMatrix_apply_of_adj hgram hxy
    edgeSqrtMass_eq := S.edgeSqrtMass_leftMatrix_add_rightMatrix hgram
    totalMass_eq := S.totalMass_left_add_right hgram
  }⟩

end CutPartition

/-- Scalar Cauchy--Schwarz in the normalization of the oriented sparse
inequality. -/
lemma sq_add_le_of_two_blocks {S₁ S₂ q₁ q₂ T₁ T₂ : ℝ}
    (hS₁ : 0 ≤ S₁) (hS₂ : 0 ≤ S₂)
    (hq₁ : 0 ≤ q₁) (hq₂ : 0 ≤ q₂)
    (hT₁ : 0 ≤ T₁) (hT₂ : 0 ≤ T₂)
    (h₁ : S₁ ^ 2 ≤ q₁ * T₁) (h₂ : S₂ ^ 2 ≤ q₂ * T₂) :
    (S₁ + S₂) ^ 2 ≤ (q₁ + q₂) * (T₁ + T₂) := by
  have hroot₁ : S₁ ≤ √(q₁ * T₁) :=
    (sq_le_mul_iff_le_sqrt_mul hS₁ (mul_nonneg hq₁ hT₁)).mp h₁
  have hroot₂ : S₂ ≤ √(q₂ * T₂) :=
    (sq_le_mul_iff_le_sqrt_mul hS₂ (mul_nonneg hq₂ hT₂)).mp h₂
  apply (sq_le_mul_iff_le_sqrt_mul
    (add_nonneg hS₁ hS₂)
    (mul_nonneg (add_nonneg hq₁ hq₂) (add_nonneg hT₁ hT₂))).mpr
  calc
    S₁ + S₂ ≤ √(q₁ * T₁) + √(q₂ * T₂) :=
      add_le_add hroot₁ hroot₂
    _ ≤ √((q₁ + q₂) * (T₁ + T₂)) :=
      sqrt_mul_add_sqrt_mul_le hq₁ hq₂ hT₁ hT₂

/-- Cut-vertex step with hypotheses stated directly for the two side graphs. -/
theorem supported_sparse_bound_of_cutPartition
    {G : SimpleGraph V} [DecidableRel G.Adj] {v : V}
    (P : CutPartition G v) {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) (hSupport : SupportedOn G M)
    (hleft :
      ∀ (N : Matrix {x // x ∈ P.leftVertices}
          {x // x ∈ P.leftVertices} ℝ),
        DoublyNonnegative N →
        SupportedOn P.leftGraph N →
        edgeSqrtMass P.leftGraph N ^ 2 ≤
          graphQ P.leftGraph * totalMass N)
    (hright :
      ∀ (N : Matrix {x // x ∈ P.rightVertices}
          {x // x ∈ P.rightVertices} ℝ),
        DoublyNonnegative N →
        SupportedOn P.rightGraph N →
        edgeSqrtMass P.rightGraph N ^ 2 ≤
          graphQ P.rightGraph * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let S := Classical.choice (P.oneSeparatorSplit hM hSupport)
  have h₁ := hleft S.leftMatrix S.left_dnn S.left_supported
  have h₂ := hright S.rightMatrix S.right_dnn S.right_supported
  have hcombine :
      (edgeSqrtMass P.leftGraph S.leftMatrix +
          edgeSqrtMass P.rightGraph S.rightMatrix) ^ 2 ≤
        (graphQ P.leftGraph + graphQ P.rightGraph) *
          (totalMass S.leftMatrix + totalMass S.rightMatrix) :=
    sq_add_le_of_two_blocks
      (edgeSqrtMass_nonneg P.leftGraph S.leftMatrix)
      (edgeSqrtMass_nonneg P.rightGraph S.rightMatrix)
      (graphQ_nonneg P.leftGraph P.leftGraph_connected)
      (graphQ_nonneg P.rightGraph P.rightGraph_connected)
      S.left_dnn.totalMass_nonneg S.right_dnn.totalMass_nonneg h₁ h₂
  rw [S.edgeSqrtMass_eq, P.graphQ_left_add_right,
    ← S.totalMass_eq] at hcombine
  exact hcombine

omit [DecidableEq V] in
/-- Induction-facing cut-vertex branch.  The induction hypothesis is supplied
for every strictly smaller connected finite graph. -/
theorem supported_sparse_bound_of_disconnected_delete
    (G : SimpleGraph V) [DecidableRel G.Adj] (v : V)
    (hG : G.Connected) (hdelete : ¬(deleteVertex G v).Preconnected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M)
    (hsmaller :
      ∀ {W : Type u} [Fintype W] [DecidableEq W]
        (H : SimpleGraph W) [DecidableRel H.Adj],
        H.Connected →
        Fintype.card W < Fintype.card V →
        ∀ (N : Matrix W W ℝ),
          DoublyNonnegative N →
          SupportedOn H N →
          edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let P := Classical.choice
    (exists_cutPartition_of_not_preconnected_delete G v hG hdelete)
  apply supported_sparse_bound_of_cutPartition P hM hSupport
  · intro N hN hSupp
    exact hsmaller P.leftGraph P.leftGraph_connected P.card_left_lt
      N hN hSupp
  · intro N hN hSupp
    exact hsmaller P.rightGraph P.rightGraph_connected P.card_right_lt
      N hN hSupp

omit [Fintype V] [DecidableEq V] in
/-- A non-connected deletion with a nonempty vertex type is not
preconnected.  The nonemptiness assumption excludes the one-vertex
degeneracy in mathlib's definition of `Connected`. -/
lemma not_preconnected_delete_of_not_connected
    (G : SimpleGraph V) (v : V)
    (hne : Nonempty {x : V // x ≠ v})
    (hdelete : ¬(deleteVertex G v).Connected) :
    ¬(deleteVertex G v).Preconnected := by
  intro hpre
  letI : Nonempty {x : V // x ≠ v} := hne
  exact hdelete ⟨hpre⟩

omit [DecidableEq V] in
/-- Variant of the induction-facing theorem using mathlib's `¬ Connected`
form of disconnectedness. -/
theorem supported_sparse_bound_of_not_connected_delete
    (G : SimpleGraph V) [DecidableRel G.Adj] (v : V)
    (hG : G.Connected)
    (hne : Nonempty {x : V // x ≠ v})
    (hdelete : ¬(deleteVertex G v).Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M)
    (hsmaller :
      ∀ {W : Type u} [Fintype W] [DecidableEq W]
        (H : SimpleGraph W) [DecidableRel H.Adj],
        H.Connected →
        Fintype.card W < Fintype.card V →
        ∀ (N : Matrix W W ℝ),
          DoublyNonnegative N →
          SupportedOn H N →
          edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M :=
  supported_sparse_bound_of_disconnected_delete G v hG
    (not_preconnected_delete_of_not_connected G v hne hdelete)
    hM hSupport hsmaller

end FiniteGraph

end

end SquareEnergy

end

section

/-!
# The no-cut-vertex induction step

This file proves the vertex-deletion branch of the sparse square-energy
induction.  All edge sums use the oriented convention from `Sq.Sparse.Basic`:
every undirected edge occurs in both directions.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*}

/-- The type of vertices left after deleting `v`. -/
abbrev DeletedVertex (v : V) := {u : V // u ≠ v}

instance (G : SimpleGraph V) [DecidableEq V] [DecidableRel G.Adj] (v : V) :
    DecidableRel (deleteVertex G v).Adj := by
  intro i j
  change Decidable (G.Adj i.1 j.1)
  infer_instance

/-- The principal submatrix obtained by deleting one row and column. -/
def deleteMatrix (M : Matrix V V ℝ) (v : V) :
    Matrix (DeletedVertex v) (DeletedVertex v) ℝ :=
  M.submatrix Subtype.val Subtype.val

section BasicDeletion

variable [Fintype V] [DecidableEq V]

@[simp]
lemma card_deletedVertex (v : V) :
    Fintype.card (DeletedVertex v) = Fintype.card V - 1 := by
  change Fintype.card ({v}ᶜ : Set V) = Fintype.card V - 1
  rw [Fintype.card_compl_set]
  simp

lemma card_deletedVertex_lt (v : V) :
    Fintype.card (DeletedVertex v) < Fintype.card V := by
  rw [card_deletedVertex]
  exact Nat.sub_lt (Fintype.card_pos_iff.mpr ⟨v⟩) Nat.zero_lt_one

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_posSemidef {M : Matrix V V ℝ}
    (hM : M.PosSemidef) (v : V) :
    (deleteMatrix M v).PosSemidef := by
  exact hM.submatrix Subtype.val

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_entrywiseNonnegative {M : Matrix V V ℝ}
    (hM : EntrywiseNonnegative M) (v : V) :
    EntrywiseNonnegative (deleteMatrix M v) := by
  intro i j
  exact hM i.1 j.1

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_doublyNonnegative {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M) (v : V) :
    DoublyNonnegative (deleteMatrix M v) :=
  ⟨deleteMatrix_posSemidef hM.posSemidef v,
    deleteMatrix_entrywiseNonnegative hM.entrywise v⟩

omit [Fintype V] [DecidableEq V] in
lemma deleteMatrix_supportedOn (G : SimpleGraph V)
    {M : Matrix V V ℝ} (hM : SupportedOn G M) (v : V) :
    SupportedOn (deleteVertex G v) (deleteMatrix M v) := by
  intro i j hij hnonedge
  apply hM
  · intro h
    apply hij
    exact Subtype.ext h
  · simpa [deleteVertex, SimpleGraph.induce_adj] using hnonedge

end BasicDeletion

section FiniteSumDeletion

variable [Fintype V] [DecidableEq V]

/--
Deleting row and column `v`, then adding back that row and column, counts the
diagonal entry twice.
-/
private lemma sum_delete_add_row_add_column (a : V → V → ℝ) (v : V) :
    (∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1) +
        (∑ j, a v j) + (∑ i, a i v) =
      (∑ i, ∑ j, a i j) + a v v := by
  have houter :
      (∑ i, ∑ j, a i j) =
        (∑ j, a v j) + ∑ i : DeletedVertex v, ∑ j, a i.1 j := by
    exact Fintype.sum_eq_add_sum_subtype_ne (fun i ↦ ∑ j, a i j) v
  have hinner :
      (∑ i : DeletedVertex v, ∑ j, a i.1 j) =
        (∑ i : DeletedVertex v, a i.1 v) +
          ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1 := by
    simp_rw [Fintype.sum_eq_add_sum_subtype_ne (fun j ↦ a _ j) v]
    rw [Finset.sum_add_distrib]
  have hcolumn :
      (∑ i, a i v) =
        a v v + ∑ i : DeletedVertex v, a i.1 v := by
    exact Fintype.sum_eq_add_sum_subtype_ne (fun i ↦ a i v) v
  rw [houter, hinner, hcolumn]
  ring

/-- Generic summed principal-submatrix deletion identity. -/
private lemma sum_delete_submatrices (a : V → V → ℝ) :
    (∑ v, ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1) =
      ((Fintype.card V : ℝ) - 2) * (∑ i, ∑ j, a i j) +
        ∑ i, a i i := by
  let D : V → ℝ :=
    fun v ↦ ∑ i : DeletedVertex v, ∑ j : DeletedVertex v, a i.1 j.1
  let R : V → ℝ := fun v ↦ ∑ j, a v j
  let C : V → ℝ := fun v ↦ ∑ i, a i v
  let T : ℝ := ∑ i, ∑ j, a i j
  have hsum :
      (∑ v, D v) + (∑ v, R v) + (∑ v, C v) =
        (∑ _v : V, T) + ∑ v, a v v := by
    calc
      (∑ v, D v) + (∑ v, R v) + (∑ v, C v) =
          ∑ v, (D v + R v + C v) := by
            simp only [Finset.sum_add_distrib]
      _ = ∑ v, (T + a v v) := by
            apply Finset.sum_congr rfl
            intro v _
            exact sum_delete_add_row_add_column a v
      _ = (∑ _v : V, T) + ∑ v, a v v := by
            rw [Finset.sum_add_distrib]
  have hrow : (∑ v, R v) = T := rfl
  have hcolumn : (∑ v, C v) = T := by
    dsimp [C, T]
    rw [Finset.sum_comm]
  have hconstant : (∑ _v : V, T) = (Fintype.card V : ℝ) * T := by
    simp
  rw [hrow, hcolumn, hconstant] at hsum
  dsimp only [D, T] at hsum ⊢
  ring_nf at hsum ⊢
  linarith

end FiniteSumDeletion

section EdgeDeletion

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
private lemma edgeSqrtMass_eq_sum_if (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      ∑ u, ∑ w, if G.Adj u w then Real.sqrt (M u w) else 0 := by
  simp [edgeSqrtMass, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter]

omit [DecidableEq V] in
private lemma edgeMass_eq_sum_if (M : Matrix V V ℝ) :
    edgeMass G M =
      ∑ u, ∑ w, if G.Adj u w then M u w else 0 := by
  simp [edgeMass, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter]

/--
Deleting `v` removes both oriented copies of every incident edge: the copy
leaving `v` and the copy entering `v`.
-/
lemma edgeSqrtMass_deleteVertex_add_incident (M : Matrix V V ℝ) (v : V) :
    edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) +
        (∑ w ∈ G.neighborFinset v, Real.sqrt (M v w)) +
        (∑ u ∈ G.neighborFinset v, Real.sqrt (M u v)) =
      edgeSqrtMass G M := by
  let a : V → V → ℝ :=
    fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0
  have h := sum_delete_add_row_add_column a v
  have hdiag : a v v = 0 := by simp [a]
  rw [hdiag, add_zero] at h
  rw [edgeSqrtMass_eq_sum_if (G := deleteVertex G v),
    edgeSqrtMass_eq_sum_if (G := G)]
  simpa [a, deleteVertex, deleteMatrix,
    SimpleGraph.induce_adj, SimpleGraph.neighborFinset_eq_filter,
    Finset.sum_filter, SimpleGraph.adj_comm] using h

/-- Every oriented edge survives all vertex deletions except its two ends. -/
lemma sum_edgeSqrtMass_deleteVertex (M : Matrix V V ℝ) :
    (∑ v, edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)) =
      ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M := by
  let a : V → V → ℝ :=
    fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0
  have h := sum_delete_submatrices a
  have hdiag : (∑ v, a v v) = 0 := by
    apply Finset.sum_eq_zero
    intro v _
    simp [a]
  rw [hdiag, add_zero] at h
  calc
    (∑ v, edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)) =
        ∑ v, ∑ u : DeletedVertex v, ∑ w : DeletedVertex v,
          a u.1 w.1 := by
            apply Finset.sum_congr rfl
            intro v _
            rw [edgeSqrtMass_eq_sum_if (G := deleteVertex G v)]
            simp [a, deleteVertex, deleteMatrix]
    _ = ((Fintype.card V : ℝ) - 2) * (∑ u, ∑ w, a u w) := h
    _ = ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M := by
      rw [edgeSqrtMass_eq_sum_if (G := G)]

omit [DecidableEq V] in
private lemma edgeSqrtMass_eq_dart_sum (M : Matrix V V ℝ) :
    edgeSqrtMass G M =
      ∑ p ∈ (Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2),
        Real.sqrt (M p.1 p.2) := by
  rw [edgeSqrtMass_eq_sum_if]
  rw [Finset.sum_filter]
  exact (Finset.sum_product' Finset.univ Finset.univ
    (fun u w ↦ if G.Adj u w then Real.sqrt (M u w) else 0)).symm

omit [DecidableEq V] in
private lemma edgeMass_eq_dart_sum (M : Matrix V V ℝ) :
    edgeMass G M =
      ∑ p ∈ (Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2),
        M p.1 p.2 := by
  rw [edgeMass_eq_sum_if]
  rw [Finset.sum_filter]
  exact (Finset.sum_product' Finset.univ Finset.univ
    (fun u w ↦ if G.Adj u w then M u w else 0)).symm

omit [DecidableEq V] in
/--
Flat Cauchy--Schwarz in oriented normalization.  The indexing finset has
`2 * |E(G)|` elements.
-/
lemma edgeSqrtMass_sq_le_two_mul_card_edges_mul_edgeMass
    {M : Matrix V V ℝ} (hM : EntrywiseNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤
      2 * (G.edgeFinset.card : ℝ) * edgeMass G M := by
  let s := Finset.univ.filter fun p : V × V ↦ G.Adj p.1 p.2
  have hflat :=
    sq_sum_sqrt_le_card_mul_sum s (fun p : V × V ↦ M p.1 p.2)
      (fun p _ ↦ hM p.1 p.2)
  have hcardNat : s.card = 2 * G.edgeFinset.card := by
    dsimp [s]
    exact G.two_mul_card_edgeFinset.symm
  have hcardReal : (s.card : ℝ) = 2 * (G.edgeFinset.card : ℝ) := by
    exact_mod_cast hcardNat
  rw [edgeSqrtMass_eq_dart_sum, edgeMass_eq_dart_sum]
  rw [hcardReal] at hflat
  exact hflat

end EdgeDeletion

section GraphDeletion

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

lemma card_edges_deleteVertex (v : V) :
    (deleteVertex G v).edgeFinset.card =
      G.edgeFinset.card - G.degree v := by
  let e : DeletedVertex v ≃ ({v}ᶜ : Set V) :=
    { toFun := fun u ↦ ⟨u.1, by
          change u.1 ∉ ({v} : Set V)
          simpa using u.2⟩
      invFun := fun u ↦ ⟨u.1, by
          intro h
          apply u.2
          simp [h]⟩
      left_inv := fun _ ↦ rfl
      right_inv := fun _ ↦ rfl }
  let f : deleteVertex G v ≃g G.induce ({v}ᶜ : Set V) :=
    { toEquiv := e
      map_rel_iff' := by
        intro u w
        rfl }
  calc
    (deleteVertex G v).edgeFinset.card =
        (G.induce ({v}ᶜ : Set V)).edgeFinset.card :=
      f.card_edgeFinset_eq
    _ = G.edgeFinset.card - G.degree v :=
      (G.card_edgeFinset_induce_compl_singleton v).trans
        (G.card_edgeFinset_deleteIncidenceSet v)

/-- Vertex deletion changes `q = 2m - n + 1` by `1 - 2 deg(v)`. -/
lemma graphQ_deleteVertex (v : V) :
    graphQ (deleteVertex G v) =
      graphQ G + 1 - 2 * (G.degree v : ℝ) := by
  have hdegree : G.degree v ≤ G.edgeFinset.card :=
    by
      rw [← G.card_incidenceFinset_eq_degree]
      exact Finset.card_le_card (G.incidenceFinset_subset v)
  have hvertex : 1 ≤ Fintype.card V :=
    Fintype.card_pos_iff.mpr ⟨v⟩
  simp only [graphQ_eq, card_edges_deleteVertex, card_deletedVertex]
  rw [Nat.cast_sub hdegree, Nat.cast_sub hvertex]
  ring

/-- Summed deletion identity for the graph parameter. -/
lemma sum_graphQ_deleteVertex :
    (∑ v, graphQ (deleteVertex G v)) =
      ((Fintype.card V : ℝ) - 2) * (graphQ G - 1) := by
  have hdegree :
      (∑ v, (G.degree v : ℝ)) =
        2 * (G.edgeFinset.card : ℝ) := by
    exact_mod_cast G.sum_degrees_eq_twice_card_edges
  calc
    (∑ v, graphQ (deleteVertex G v)) =
        ∑ v, (graphQ G + 1 - 2 * (G.degree v : ℝ)) := by
          apply Finset.sum_congr rfl
          intro v _
          exact graphQ_deleteVertex G v
    _ = (Fintype.card V : ℝ) * (graphQ G + 1) -
        2 * ∑ v, (G.degree v : ℝ) := by
          simp [Finset.sum_sub_distrib, Finset.mul_sum]
          ring
    _ = ((Fintype.card V : ℝ) - 2) * (graphQ G - 1) := by
          rw [hdegree]
          simp only [graphQ]
          ring

end GraphDeletion

section MatrixDeletion

variable [Fintype V] [DecidableEq V]

/-- Summing all principal vertex deletions counts off-diagonal entries
`n - 2` times and diagonal entries `n - 1` times. -/
lemma sum_totalMass_deleteMatrix (M : Matrix V V ℝ) :
    (∑ v, totalMass (deleteMatrix M v)) =
      ((Fintype.card V : ℝ) - 2) * totalMass M + M.trace := by
  simpa [totalMass, deleteMatrix, Matrix.trace, Matrix.diag] using
    (sum_delete_submatrices (fun i j ↦ M i j))

end MatrixDeletion

section SupportedMass

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
/-- For a graph-supported matrix, total mass is diagonal mass plus oriented
edge mass.  Symmetry is not needed for this stronger statement. -/
lemma totalMass_eq_trace_add_edgeMass_of_supported
    {M : Matrix V V ℝ} (hM : SupportedOn G M) :
    totalMass M = M.trace + edgeMass G M := by
  classical
  have hentry (i j : V) :
      M i j =
        (if i = j then M i j else 0) +
          (if G.Adj i j then M i j else 0) := by
    by_cases hij : i = j
    · subst j
      simp
    · by_cases hadj : G.Adj i j
      · simp [hij, hadj]
      · simp [hij, hadj, hM hij hadj]
  calc
    totalMass M = ∑ i, ∑ j,
        ((if i = j then M i j else 0) +
          (if G.Adj i j then M i j else 0)) := by
            unfold totalMass
            apply Finset.sum_congr rfl
            intro i _
            apply Finset.sum_congr rfl
            intro j _
            exact hentry i j
    _ = (∑ i, ∑ j, if i = j then M i j else 0) +
        (∑ i, ∑ j, if G.Adj i j then M i j else 0) := by
          simp only [Finset.sum_add_distrib]
    _ = M.trace + edgeMass G M := by
          rw [edgeMass_eq_sum_if]
          simp [Matrix.trace, Matrix.diag]

end SupportedMass

section GraphCardinality

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/-- The real-valued cycle rank `m - n + 1`. -/
def graphCycleRank : ℝ :=
  (G.edgeFinset.card : ℝ) - (Fintype.card V : ℝ) + 1

omit [DecidableEq V] in
lemma graphQ_edge_count_identity :
    4 * (G.edgeFinset.card : ℝ) =
      2 * graphQ G + 2 * ((Fintype.card V : ℝ) - 1) := by
  simp only [graphQ]
  ring

omit [DecidableEq V] in
lemma graphQ_sub_one_eq_card_sub_two_add_two_mul_cycleRank :
    graphQ G - 1 =
      ((Fintype.card V : ℝ) - 2) + 2 * graphCycleRank G := by
  simp only [graphQ, graphCycleRank]
  ring

omit [DecidableEq V] in
/-- The complete-graph edge bound in the cycle-rank normalization used in
Case 2. -/
lemma two_mul_graphCycleRank_le :
    2 * graphCycleRank G ≤
      ((Fintype.card V : ℝ) - 1) *
        ((Fintype.card V : ℝ) - 2) := by
  have hsimpleNat :
      G.edgeFinset.card ≤ (Fintype.card V).choose 2 :=
    G.card_edgeFinset_le_card_choose_two
  have hsimple :
      2 * (G.edgeFinset.card : ℝ) ≤
        (Fintype.card V : ℝ) * ((Fintype.card V : ℝ) - 1) := by
    have hcast :
        (G.edgeFinset.card : ℝ) ≤
          ((Fintype.card V).choose 2 : ℝ) := by
      exact_mod_cast hsimpleNat
    rw [Nat.cast_choose_two] at hcast
    linarith
  dsimp [graphCycleRank]
  linarith

omit [DecidableEq V] in
lemma one_le_graphQ_of_connected_of_three_le
    (hG : G.Connected) (hcard : 3 ≤ Fintype.card V) :
    1 ≤ graphQ G := by
  have hedges := connected_card_vertices_le_card_edges_add_one G hG
  have hn : (3 : ℝ) ≤ (Fintype.card V : ℝ) := by
    exact_mod_cast hcard
  simp only [graphQ]
  linarith

end GraphCardinality

section ScalarOriented

/-- `averaged_estimate_of_sqrt_bound` in the oriented normalization. -/
lemma oriented_averaged_estimate_of_sqrt_bound
    {n q S T d₀ : ℝ}
    (hn : 2 < n) (hq : 1 ≤ q) (hS : 0 ≤ S)
    (hT : 0 ≤ T) (hd₀ : 0 ≤ d₀)
    (hbound :
      (n - 2) * S ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀))) :
    S ^ 2 ≤ (q - 1) * T + (q - 1) / (n - 2) * d₀ := by
  have hbound' :
      2 * (n - 2) * (S / 2) ≤
        √(((n - 2) * (q - 1)) * ((n - 2) * T + d₀)) := by
    convert hbound using 1
    ring
  have h :=
    averaged_estimate_of_sqrt_bound
      (S := S / 2) hn hq (by positivity) hT hd₀ hbound'
  convert h using 1
  ring

/-- Paper Case 1 with oriented edge and square-root masses. -/
lemma oriented_paper_case_one
    {m n q S d₀ w : ℝ}
    (hcount : 4 * m = 2 * q + 2 * (n - 1))
    (hflat : S ^ 2 ≤ 2 * m * w)
    (hthreshold : (n - 1) * w ≤ q * d₀) :
    S ^ 2 ≤ q * (d₀ + w) := by
  have h :=
    paper_case_one
      (S := S / 2) (w := w / 2) hcount
      (by convert hflat using 1 <;> ring)
      (by
        convert hthreshold using 1
        ring)
  convert h using 1 <;> ring

/-- Paper Case 2 with oriented edge and square-root masses. -/
lemma oriented_paper_case_two
    {n q β S d₀ w : ℝ}
    (hn : 2 < n) (hd₀ : 0 ≤ d₀)
    (hqβ : q - 1 = (n - 2) + 2 * β)
    (hsimple : 2 * β ≤ (n - 1) * (n - 2))
    (hthreshold : q * d₀ < (n - 1) * w)
    (haverage :
      S ^ 2 ≤
        (q - 1) * (d₀ + w) + (q - 1) / (n - 2) * d₀) :
    S ^ 2 ≤ q * (d₀ + w) := by
  have h :=
    paper_case_two
      (S := S / 2) (w := w / 2)
      hn hd₀ hqβ hsimple
      (by
        convert hthreshold using 1
        ring)
      (by convert haverage using 1 <;> ring)
  convert h using 1 <;> ring

end ScalarOriented

section AveragedInduction

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/--
The oriented averaged estimate obtained by summing all vertex-deletion
induction hypotheses.
-/
lemma averaged_estimate_of_deleteVertex_IH
    (hG : G.Connected)
    (hcard : 3 ≤ Fintype.card V)
    (hdelete : ∀ v, (deleteVertex G v).Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hIH : ∀ v,
      edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) ^ 2 ≤
        graphQ (deleteVertex G v) * totalMass (deleteMatrix M v)) :
    edgeSqrtMass G M ^ 2 ≤
      (graphQ G - 1) * totalMass M +
        (graphQ G - 1) / ((Fintype.card V : ℝ) - 2) * M.trace := by
  let qv : V → ℝ := fun v ↦ graphQ (deleteVertex G v)
  let Tv : V → ℝ := fun v ↦ totalMass (deleteMatrix M v)
  let Sv : V → ℝ :=
    fun v ↦ edgeSqrtMass (deleteVertex G v) (deleteMatrix M v)
  have hqv (v : V) : 0 ≤ qv v :=
    graphQ_nonneg (deleteVertex G v) (hdelete v)
  have hTv (v : V) : 0 ≤ Tv v :=
    (deleteMatrix_doublyNonnegative hM v).totalMass_nonneg
  have hSv (v : V) : 0 ≤ Sv v :=
    edgeSqrtMass_nonneg (deleteVertex G v) (deleteMatrix M v)
  have hroot (v : V) : Sv v ≤ √(qv v * Tv v) := by
    exact (sq_le_mul_iff_le_sqrt_mul (hSv v)
      (mul_nonneg (hqv v) (hTv v))).mp (hIH v)
  have hsumroot :
      (∑ v, Sv v) ≤
        √((∑ v, qv v) * (∑ v, Tv v)) := by
    calc
      (∑ v, Sv v) ≤ ∑ v, √(qv v * Tv v) :=
        Finset.sum_le_sum fun v _ ↦ hroot v
      _ ≤ √((∑ v, qv v) * (∑ v, Tv v)) :=
        sum_sqrt_mul_le_sqrt_sum_mul_sum Finset.univ qv Tv hqv hTv
  have hbound :
      ((Fintype.card V : ℝ) - 2) * edgeSqrtMass G M ≤
        √((((Fintype.card V : ℝ) - 2) * (graphQ G - 1)) *
          (((Fintype.card V : ℝ) - 2) * totalMass M + M.trace)) := by
    rw [← sum_edgeSqrtMass_deleteVertex G M,
      ← sum_graphQ_deleteVertex G,
      ← sum_totalMass_deleteMatrix M]
    exact hsumroot
  have hn : (2 : ℝ) < Fintype.card V := by
    exact_mod_cast (show 2 < Fintype.card V from lt_of_lt_of_le (by decide) hcard)
  exact oriented_averaged_estimate_of_sqrt_bound
    hn (one_le_graphQ_of_connected_of_three_le G hG hcard)
    (edgeSqrtMass_nonneg G M) hM.totalMass_nonneg
    hM.posSemidef.trace_nonneg hbound

end AveragedInduction

section NoCutStep

variable [Fintype V] [DecidableEq V]
variable (G : SimpleGraph V) [DecidableRel G.Adj]

/--
The no-cut-vertex induction step for graph-supported doubly nonnegative
matrices.
-/
theorem noCutVertex_step
    (hG : G.Connected)
    (hcard : 3 ≤ Fintype.card V)
    (hdelete : ∀ v, (deleteVertex G v).Connected)
    {M : Matrix V V ℝ}
    (hM : DoublyNonnegative M)
    (hSupported : SupportedOn G M)
    (hIH : ∀ v,
      edgeSqrtMass (deleteVertex G v) (deleteMatrix M v) ^ 2 ≤
        graphQ (deleteVertex G v) * totalMass (deleteMatrix M v)) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  let n : ℝ := Fintype.card V
  let m : ℝ := G.edgeFinset.card
  let q : ℝ := graphQ G
  let S : ℝ := edgeSqrtMass G M
  let d₀ : ℝ := M.trace
  let w : ℝ := edgeMass G M
  have htotal : totalMass M = d₀ + w := by
    exact totalMass_eq_trace_add_edgeMass_of_supported G hSupported
  have hn : 2 < n := by
    dsimp [n]
    exact_mod_cast (show 2 < Fintype.card V from lt_of_lt_of_le (by decide) hcard)
  have hd₀ : 0 ≤ d₀ := hM.posSemidef.trace_nonneg
  have hflat : S ^ 2 ≤ 2 * m * w := by
    exact edgeSqrtMass_sq_le_two_mul_card_edges_mul_edgeMass G hM.entrywise
  by_cases hcase : (n - 1) * w ≤ q * d₀
  · have hcaseOne : S ^ 2 ≤ q * (d₀ + w) :=
      oriented_paper_case_one
        (by
          dsimp [m, n, q]
          exact graphQ_edge_count_identity G)
        hflat hcase
    simpa [S, q, ← htotal] using hcaseOne
  · have hthreshold : q * d₀ < (n - 1) * w := lt_of_not_ge hcase
    have haverage :
        S ^ 2 ≤
          (q - 1) * (d₀ + w) + (q - 1) / (n - 2) * d₀ := by
      have havg :=
        averaged_estimate_of_deleteVertex_IH G hG hcard hdelete hM hIH
      simpa [S, q, n, d₀, htotal] using havg
    have hcaseTwo : S ^ 2 ≤ q * (d₀ + w) :=
      oriented_paper_case_two
        hn hd₀
        (by
          dsimp [q, n]
          exact graphQ_sub_one_eq_card_sub_two_add_two_mul_cycleRank G)
        (by
          dsimp [n]
          exact two_mul_graphCycleRank_le G)
        hthreshold haverage
    simpa [S, q, ← htotal] using hcaseTwo

end NoCutStep

end

end SquareEnergy

end

section

/-!
# Sparse matrix induction

This file closes the induction for the graph-supported sparse matrix
inequality and then removes the support hypothesis by folding nonedges onto
the diagonal.

The edge sum is oriented: every undirected edge occurs twice in
`edgeSqrtMass`.  Consequently its square is exactly the paper's factor
`4 * (∑ uv ∈ E(G), √(M uv)) ^ 2`.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

universe u

variable {V : Type u} [Fintype V] [DecidableEq V]

section CardinalityFacts

omit [DecidableEq V] in
/-- A two-element fintype can be enumerated by two distinct vertices. -/
lemma exists_pair_of_card_eq_two (hcard : Fintype.card V = 2) :
    ∃ u v : V, u ≠ v ∧ ∀ x : V, x = u ∨ x = v := by
  rw [← Nat.card_eq_fintype_card] at hcard
  obtain ⟨u, v, huv, huv_univ⟩ := Nat.card_eq_two_iff.mp hcard
  refine ⟨u, v, huv, fun x ↦ ?_⟩
  have hx : x ∈ ({u, v} : Set V) := by
    rw [huv_univ]
    exact Set.mem_univ x
  simpa [eq_comm] using hx

/-- The universal finset of a two-element type is its chosen pair. -/
lemma univ_eq_pair_of_card_eq_two
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) :
    (Finset.univ : Finset V) = {u, v} := by
  symm
  apply Finset.eq_of_subset_of_card_le (Finset.subset_univ _)
  simp [hcard, huv]

omit [DecidableEq V] in
/-- Every vertex of a two-element type is one of a fixed distinct pair. -/
lemma eq_left_or_right_of_card_eq_two
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) (x : V) :
    x = u ∨ x = v := by
  classical
  have hx : x ∈ ({u, v} : Finset V) := by
    rw [← univ_eq_pair_of_card_eq_two hcard huv]
    exact Finset.mem_univ x
  simpa [eq_comm] using hx

omit [DecidableEq V] in
/-- In a connected graph on two vertices, the two vertices are adjacent. -/
lemma adj_of_connected_card_two
    (G : SimpleGraph V) (hG : G.Connected)
    (hcard : Fintype.card V = 2) {u v : V} (huv : u ≠ v) :
    G.Adj u v := by
  let : Nontrivial V :=
    Fintype.one_lt_card_iff_nontrivial.mp (by omega)
  obtain ⟨w, huw⟩ := hG.preconnected.exists_adj_of_nontrivial u
  rcases eq_left_or_right_of_card_eq_two hcard huv w with rfl | rfl
  · exact (huw.ne rfl).elim
  · exact huw

omit [DecidableEq V] in
/-- A connected simple graph on two vertices is the complete graph. -/
lemma eq_top_of_connected_card_two
    (G : SimpleGraph V) (hG : G.Connected)
    (hcard : Fintype.card V = 2) :
    G = ⊤ := by
  ext u v
  simp only [SimpleGraph.top_adj]
  exact ⟨SimpleGraph.Adj.ne, adj_of_connected_card_two G hG hcard⟩

omit [DecidableEq V] in
/-- A connected graph on two vertices has graph parameter exactly one. -/
lemma graphQ_eq_one_of_connected_card_two
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 2) :
    graphQ G = 1 := by
  have hlower : Fintype.card V ≤ G.edgeFinset.card + 1 := by
    simpa only [Nat.card_eq_fintype_card, ← G.edgeFinset_card] using
      hG.card_vert_le_card_edgeSet_add_one
  have hupper := G.card_edgeFinset_le_card_choose_two
  have hedge : G.edgeFinset.card = 1 := by
    rw [hcard] at hlower hupper
    change G.edgeFinset.card ≤ 1 at hupper
    omega
  simp [graphQ, hcard, hedge]

omit [DecidableEq V] in
/-- A simple graph on one vertex has no edges. -/
lemma eq_bot_of_card_eq_one
    (G : SimpleGraph V) (hcard : Fintype.card V = 1) :
    G = ⊥ := by
  have : Subsingleton V :=
    Fintype.card_le_one_iff_subsingleton.mp (by omega)
  exact Subsingleton.elim G ⊥

omit [DecidableEq V] in
/-- The graph parameter is exactly zero on a one-vertex graph. -/
lemma graphQ_eq_zero_of_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hcard : Fintype.card V = 1) :
    graphQ G = 0 := by
  have hupper := G.card_edgeFinset_le_card_choose_two
  have hedge : G.edgeFinset.card = 0 := by
    have hz : G.edgeFinset.card ≤ 0 := by
      simpa [hcard] using hupper
    exact Nat.eq_zero_of_le_zero hz
  simp [graphQ, hcard, hedge]

omit [DecidableEq V] in
/--
The oriented square-root edge mass is zero on a connected one-vertex graph.
Connectedness supplies its unique vertex, and simplicity rules out its only
possible edge.
-/
lemma edgeSqrtMass_eq_zero_of_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 1)
    (M : Matrix V V ℝ) :
    edgeSqrtMass G M = 0 := by
  classical
  let u : V := Classical.choice hG.nonempty
  obtain ⟨a, ha⟩ := Fintype.card_eq_one_iff.mp hcard
  have hall (x : V) : x = u := (ha x).trans (ha u).symm
  have huniv : (Finset.univ : Finset V) = {u} := by
    ext x
    simp [hall x]
  have hneighbor : G.neighborFinset u = ∅ := by
    ext x
    rw [hall x]
    simp
  simp [edgeSqrtMass, huniv, hneighbor]

end CardinalityFacts

section TwoVertexFormulas

variable (G : SimpleGraph V) [DecidableRel G.Adj]

omit [DecidableEq V] in
/-- The two neighbor finsets in a connected two-vertex graph are singletons. -/
lemma neighborFinsets_of_connected_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v) :
    G.neighborFinset u = {v} ∧ G.neighborFinset v = {u} := by
  classical
  have hadj := adj_of_connected_card_two G hG hcard huv
  constructor <;> ext x
  · simp only [SimpleGraph.mem_neighborFinset, Finset.mem_singleton]
    rcases hcover x with rfl | rfl
    · simp [huv]
    · simp [hadj]
  · simp only [SimpleGraph.mem_neighborFinset, Finset.mem_singleton]
    rcases hcover x with rfl | rfl
    · simp [hadj.symm]
    · simp [huv.symm]

omit [DecidableEq V] in
/-- Explicit oriented square-root edge sum on two connected vertices. -/
lemma edgeSqrtMass_eq_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v)
    (M : Matrix V V ℝ) :
    edgeSqrtMass G M = Real.sqrt (M u v) + Real.sqrt (M v u) := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  obtain ⟨hnu, hnv⟩ :=
    neighborFinsets_of_connected_card_two G hG hcard huv hcover
  simp [edgeSqrtMass, huniv, hnu, hnv, huv]

omit [DecidableEq V] in
/-- For a symmetric nonnegative matrix, oriented edge mass squared is `4 M_uv`. -/
lemma edgeSqrtMass_sq_eq_four_mul_of_card_two
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    (hcover : ∀ x : V, x = u ∨ x = v)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 = 4 * M u v := by
  rw [edgeSqrtMass_eq_card_two G hG hcard huv hcover M]
  rw [← hM.apply_symm u v]
  rw [show (Real.sqrt (M u v) + Real.sqrt (M u v)) ^ 2 =
      4 * Real.sqrt (M u v) ^ 2 by ring]
  rw [Real.sq_sqrt (hM.entry_nonneg u v)]

omit [DecidableEq V] in
/-- Explicit total matrix mass after enumerating a two-element type. -/
lemma totalMass_eq_card_two
    (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    {M : Matrix V V ℝ} (hM : M.IsHermitian) :
    totalMass M = M u u + M v v + 2 * M u v := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  simp only [totalMass, huniv, Finset.sum_insert, Finset.sum_singleton,
    Finset.mem_singleton, huv, not_false_eq_true]
  have hsymm : M v u = M u v := by
    simpa using hM.apply u v
  rw [hsymm]
  ring

omit [DecidableEq V] in
/-- PSD evaluated at `e_u - e_v` gives the two-vertex diagonal bound. -/
lemma two_mul_offdiag_le_diag_sum_of_card_two
    (hcard : Fintype.card V = 2)
    {u v : V} (huv : u ≠ v)
    {M : Matrix V V ℝ} (hM : M.PosSemidef) :
    2 * M u v ≤ M u u + M v v := by
  classical
  have huniv := univ_eq_pair_of_card_eq_two hcard huv
  have hquad :=
    hM.dotProduct_mulVec_nonneg (basisDiff u v)
  simp only [dotProduct, Matrix.mulVec, huniv, Finset.sum_insert,
    Finset.sum_singleton, Finset.mem_singleton, huv, not_false_eq_true,
    basisDiff_apply_left huv, basisDiff_apply_right huv, star_trivial,
    one_mul, neg_mul, mul_one, mul_neg] at hquad
  have hsymm : M v u = M u v := by
    simpa using hM.isHermitian.apply u v
  rw [hsymm] at hquad
  linarith

end TwoVertexFormulas

section BaseCases

omit [DecidableEq V] in
/-- The exact one-vertex base of the sparse induction. -/
lemma supportedSparseMatrixInequality_card_one
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 1)
    {M : Matrix V V ℝ} (_hM : DoublyNonnegative M)
    (_hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  rw [edgeSqrtMass_eq_zero_of_card_one G hG hcard M,
    graphQ_eq_zero_of_card_one G hcard]
  norm_num

omit [DecidableEq V] in
/-- The paper's exact two-vertex base of the sparse induction. -/
lemma supportedSparseMatrixInequality_card_two
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected) (hcard : Fintype.card V = 2)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (_hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  obtain ⟨u, v, huv, hcover⟩ := exists_pair_of_card_eq_two hcard
  rw [edgeSqrtMass_sq_eq_four_mul_of_card_two G hG hcard huv hcover hM]
  rw [graphQ_eq_one_of_connected_card_two G hG hcard]
  rw [totalMass_eq_card_two hcard huv hM.isHermitian]
  have hdiag :=
    two_mul_offdiag_le_diag_sum_of_card_two hcard huv hM.posSemidef
  linarith

end BaseCases

section Induction

omit [DecidableEq V] in
/--
The supported sparse-matrix inequality for every finite connected simple
graph.  Since `edgeSqrtMass` is oriented, its square includes the paper's
factor `4`.
-/
theorem supportedSparseMatrixInequality
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M)
    (hSupport : SupportedOn G M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  let P : Nat → Prop := fun n ↦
    ∀ {W : Type u} [Fintype W] [DecidableEq W]
      (H : SimpleGraph W) [DecidableRel H.Adj],
      Fintype.card W = n →
      H.Connected →
      ∀ {N : Matrix W W ℝ},
        DoublyNonnegative N →
        SupportedOn H N →
        edgeSqrtMass H N ^ 2 ≤ graphQ H * totalMass N
  have hP : ∀ n, P n := by
    intro n
    induction n using Nat.strong_induction_on with
    | ind n ih =>
        dsimp only [P]
        intro W _ _ H _ hcard hH N hN hNSupport
        have hnpos : 0 < n := by
          rw [← hcard]
          exact Fintype.card_pos_iff.mpr hH.nonempty
        by_cases hn1 : n = 1
        · exact supportedSparseMatrixInequality_card_one
            H hH (hcard.trans hn1) hN hNSupport
        by_cases hn2 : n = 2
        · exact supportedSparseMatrixInequality_card_two
            H hH (hcard.trans hn2) hN hNSupport
        have hn3 : 3 ≤ Fintype.card W := by omega
        by_cases hcut : ∃ v, ¬(deleteVertex H v).Connected
        · obtain ⟨v, hv⟩ := hcut
          have hne : Nonempty {x : W // x ≠ v} := by
            obtain ⟨w, hw⟩ :=
              Fintype.exists_ne_of_one_lt_card (by omega : 1 < Fintype.card W) v
            exact ⟨⟨w, hw⟩⟩
          apply supported_sparse_bound_of_not_connected_delete
            H v hH hne hv hN hNSupport
          intro X _ _ K _ hK hlt L hL hLSupport
          exact ih (Fintype.card X) (by omega)
            K rfl hK hL hLSupport
        · have hdelete : ∀ v, (deleteVertex H v).Connected := by
            simpa only [not_exists, not_not] using hcut
          apply noCutVertex_step H hH hn3 hdelete hN hNSupport
          intro v
          have hlt : Fintype.card (DeletedVertex v) < n := by
            have := card_deletedVertex_lt v
            omega
          exact ih (Fintype.card (DeletedVertex v)) hlt
            (deleteVertex H v) rfl (hdelete v)
            (deleteMatrix_doublyNonnegative hN v)
            (deleteMatrix_supportedOn H hNSupport v)
  exact hP (Fintype.card V) G rfl hG hM hSupport

omit [DecidableEq V] in
/--
The sparse-matrix inequality for an arbitrary doubly nonnegative matrix.
Nonedge entries are folded onto the diagonal before applying the supported
theorem.  The oriented edge mass encodes the paper's factor `4`.
-/
theorem sparseMatrixInequality
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hG : G.Connected)
    {M : Matrix V V ℝ} (hM : DoublyNonnegative M) :
    edgeSqrtMass G M ^ 2 ≤ graphQ G * totalMass M := by
  classical
  exact supported_sparse_inequality_implies_unrestricted G
    (fun N hN hNSupport ↦
      supportedSparseMatrixInequality G hG hN hNSupport)
    hM

end Induction

end

end SquareEnergy

end

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# Square-energy deduction helpers

This file connects the spectral decomposition of a graph adjacency matrix to
the sparse doubly-nonnegative matrix inequality. It contains the matrix,
trace, quadratic, and lower-bound lemmas used by the final results in
`Sq.Main`.

All edge sums below are **oriented**: an undirected edge `{u, v}` occurs once
as `(u, v)` and once as `(v, u)`. Thus `edgeSqrtMass` already contains the
factor two whose square is the factor four in the unoriented formulation.
-/

open scoped BigOperators

namespace SquareEnergy

open Matrix

noncomputable section

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The signed sum of matrix entries over oriented adjacent vertex pairs. -/
def orientedSignedEdgeSum (G : SimpleGraph V) [DecidableRel G.Adj]
    (X : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, X u v

/-- The sum of absolute matrix entries over oriented adjacent vertex pairs. -/
def orientedAbsEdgeSum (G : SimpleGraph V) [DecidableRel G.Adj]
    (X : Matrix V V ℝ) : ℝ :=
  ∑ u, ∑ v ∈ G.neighborFinset u, |X u v|

omit [Fintype V] [DecidableEq V] in
/-- The Hadamard self-square of a positive semidefinite real matrix is doubly
nonnegative. -/
lemma hadamard_self_doublyNonnegative {X : Matrix V V ℝ}
    (hX : X.PosSemidef) :
    DoublyNonnegative (X ⊙ X) := by
  refine ⟨hX.hadamard hX, ?_⟩
  intro i j
  rw [Matrix.hadamard_apply]
  exact mul_self_nonneg (X i j)

omit [DecidableEq V] in
/-- Taking entrywise square roots of a Hadamard self-square gives absolute
values, term by term, on the oriented adjacency sum. -/
lemma edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    edgeSqrtMass G (X ⊙ X) = orientedAbsEdgeSum G X := by
  simp only [edgeSqrtMass, orientedAbsEdgeSum]
  apply Finset.sum_congr rfl
  intro u _
  apply Finset.sum_congr rfl
  intro v _
  rw [Matrix.hadamard_apply, ← pow_two, Real.sqrt_sq_eq_abs]

/-- For a real Hermitian matrix, the total mass of its Hadamard self-square is
the trace of its ordinary square. -/
lemma totalMass_hadamard_self_eq_trace_sq {X : Matrix V V ℝ}
    (hX : X.IsHermitian) :
    totalMass (X ⊙ X) = Matrix.trace (X ^ 2) := by
  have hsymm : X.IsSymm := by
    simpa using hX
  rw [totalMass, Matrix.sum_hadamard_eq, hsymm.eq, pow_two]

omit [DecidableEq V] in
/-- Multiplication by the adjacency matrix and taking the trace extracts the
signed sum over oriented adjacent pairs. -/
lemma trace_adjMatrix_mul_eq_orientedSignedEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    Matrix.trace (G.adjMatrix ℝ * X) = orientedSignedEdgeSum G X := by
  calc
    Matrix.trace (G.adjMatrix ℝ * X) =
        Matrix.trace (X * G.adjMatrix ℝ) := Matrix.trace_mul_comm _ _
    _ = orientedSignedEdgeSum G X := by
      simp [Matrix.trace, orientedSignedEdgeSum]

omit [DecidableEq V] in
/-- A signed oriented edge sum is bounded by the corresponding absolute sum. -/
lemma orientedSignedEdgeSum_le_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    orientedSignedEdgeSum G X ≤ orientedAbsEdgeSum G X := by
  unfold orientedSignedEdgeSum orientedAbsEdgeSum
  refine Finset.sum_le_sum fun u _ ↦ ?_
  exact Finset.sum_le_sum fun v _ ↦ le_abs_self (X u v)

omit [DecidableEq V] in
/-- The negative of a signed oriented edge sum is also bounded by the
corresponding absolute sum. -/
lemma neg_orientedSignedEdgeSum_le_orientedAbsEdgeSum
    (G : SimpleGraph V) [DecidableRel G.Adj] (X : Matrix V V ℝ) :
    -orientedSignedEdgeSum G X ≤ orientedAbsEdgeSum G X := by
  unfold orientedSignedEdgeSum orientedAbsEdgeSum
  rw [← Finset.sum_neg_distrib]
  refine Finset.sum_le_sum fun u _ ↦ ?_
  rw [← Finset.sum_neg_distrib]
  exact Finset.sum_le_sum fun v _ ↦ neg_le_abs (X u v)

/-- The oriented signed edge sum of the positive spectral part is the positive
square energy. -/
lemma orientedSignedEdgeSum_adjacencyPosPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    orientedSignedEdgeSum G (adjacencyPosPart G) = positiveSquareEnergy G := by
  rw [← trace_adjMatrix_mul_eq_orientedSignedEdgeSum]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul,
    adjacencyNegPart_mul_posPart, sub_zero, ← pow_two,
    trace_sq_adjacencyPosPart]

/-- The oriented signed edge sum of the absolute negative spectral part is the
negative of the negative square energy. -/
lemma orientedSignedEdgeSum_adjacencyNegPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    orientedSignedEdgeSum G (adjacencyNegPart G) = -negativeSquareEnergy G := by
  rw [← trace_adjMatrix_mul_eq_orientedSignedEdgeSum]
  rw [adjacency_eq_posPart_sub_negPart, Matrix.sub_mul,
    adjacencyPosPart_mul_negPart, zero_sub, Matrix.trace_neg, ← pow_two,
    trace_sq_adjacencyNegPart]

/-- The total mass of the positive-part Hadamard square is the positive square
energy. -/
lemma totalMass_hadamard_self_adjacencyPosPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    totalMass (adjacencyPosPart G ⊙ adjacencyPosPart G) =
      positiveSquareEnergy G := by
  calc
    totalMass (adjacencyPosPart G ⊙ adjacencyPosPart G) =
        Matrix.trace (adjacencyPosPart G ^ 2) :=
      totalMass_hadamard_self_eq_trace_sq
        (adjacencyPosPart_posSemidef G).isHermitian
    _ = positiveSquareEnergy G := trace_sq_adjacencyPosPart G

/-- The total mass of the negative-part Hadamard square is the negative square
energy. -/
lemma totalMass_hadamard_self_adjacencyNegPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    totalMass (adjacencyNegPart G ⊙ adjacencyNegPart G) =
      negativeSquareEnergy G := by
  calc
    totalMass (adjacencyNegPart G ⊙ adjacencyNegPart G) =
        Matrix.trace (adjacencyNegPart G ^ 2) :=
      totalMass_hadamard_self_eq_trace_sq
        (adjacencyNegPart_posSemidef G).isHermitian
    _ = negativeSquareEnergy G := trace_sq_adjacencyNegPart G

/-- The positive square energy is at most the square-root edge mass of the
positive-part Hadamard square. -/
lemma positiveSquareEnergy_le_edgeSqrtMass_hadamard_posPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    positiveSquareEnergy G ≤
      edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) := by
  calc
    positiveSquareEnergy G =
        orientedSignedEdgeSum G (adjacencyPosPart G) :=
      (orientedSignedEdgeSum_adjacencyPosPart G).symm
    _ ≤ orientedAbsEdgeSum G (adjacencyPosPart G) :=
      orientedSignedEdgeSum_le_orientedAbsEdgeSum G _
    _ = edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) :=
      (edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum G _).symm

/-- The negative square energy is at most the square-root edge mass of the
negative-part Hadamard square. -/
lemma negativeSquareEnergy_le_edgeSqrtMass_hadamard_negPart
    (G : SimpleGraph V) [DecidableRel G.Adj] :
    negativeSquareEnergy G ≤
      edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) := by
  calc
    negativeSquareEnergy G =
        -orientedSignedEdgeSum G (adjacencyNegPart G) := by
      rw [orientedSignedEdgeSum_adjacencyNegPart]
      ring
    _ ≤ orientedAbsEdgeSum G (adjacencyNegPart G) :=
      neg_orientedSignedEdgeSum_le_orientedAbsEdgeSum G _
    _ = edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) :=
      (edgeSqrtMass_hadamard_self_eq_orientedAbsEdgeSum G _).symm

/-- Applying the sparse DNN theorem to the positive-part Hadamard square gives
the cancellable quadratic estimate. -/
lemma positiveSquareEnergy_sq_le_graphQ_mul
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    positiveSquareEnergy G ^ 2 ≤ graphQ G * positiveSquareEnergy G := by
  have hsparse :=
    sparseMatrixInequality G hG
      (hadamard_self_doublyNonnegative (adjacencyPosPart_posSemidef G))
  rw [totalMass_hadamard_self_adjacencyPosPart] at hsparse
  have henergy : 0 ≤ positiveSquareEnergy G :=
    positiveSquareEnergy_nonneg G
  have hedge :
      0 ≤ edgeSqrtMass G (adjacencyPosPart G ⊙ adjacencyPosPart G) :=
    edgeSqrtMass_nonneg G _
  exact
    (sq_le_sq₀ henergy hedge).mpr
      (positiveSquareEnergy_le_edgeSqrtMass_hadamard_posPart G) |>.trans hsparse

/-- Applying the sparse DNN theorem to the negative-part Hadamard square gives
the cancellable quadratic estimate. -/
lemma negativeSquareEnergy_sq_le_graphQ_mul
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    negativeSquareEnergy G ^ 2 ≤ graphQ G * negativeSquareEnergy G := by
  have hsparse :=
    sparseMatrixInequality G hG
      (hadamard_self_doublyNonnegative (adjacencyNegPart_posSemidef G))
  rw [totalMass_hadamard_self_adjacencyNegPart] at hsparse
  have henergy : 0 ≤ negativeSquareEnergy G :=
    negativeSquareEnergy_nonneg G
  have hedge :
      0 ≤ edgeSqrtMass G (adjacencyNegPart G ⊙ adjacencyNegPart G) :=
    edgeSqrtMass_nonneg G _
  exact
    (sq_le_sq₀ henergy hedge).mpr
      (negativeSquareEnergy_le_edgeSqrtMass_hadamard_negPart G) |>.trans hsparse

/-- On a nontrivial connected graph, strict positivity permits cancellation in
the positive-energy quadratic estimate. -/
lemma positiveSquareEnergy_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    positiveSquareEnergy G ≤ graphQ G :=
  positive_cancel_sq_le_mul
    (positiveSquareEnergy_pos_of_connected G hG)
    (positiveSquareEnergy_sq_le_graphQ_mul G hG)

/-- On a nontrivial connected graph, strict positivity permits cancellation in
the negative-energy quadratic estimate. -/
lemma negativeSquareEnergy_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    negativeSquareEnergy G ≤ graphQ G :=
  positive_cancel_sq_le_mul
    (negativeSquareEnergy_pos_of_connected G hG)
    (negativeSquareEnergy_sq_le_graphQ_mul G hG)

/-- The upper bound on negative energy and the trace identity give the lower
bound on positive energy by the literal formula
`graphQ G = 2 |E(G)| - |V| + 1`. -/
lemma card_sub_one_le_positiveSquareEnergy_of_negative_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hneg : negativeSquareEnergy G ≤ graphQ G) :
    (Fintype.card V : ℝ) - 1 ≤ positiveSquareEnergy G := by
  have hsum := squareEnergies_add_eq_twice_card_edges G
  rw [graphQ] at hneg
  linarith

/-- The upper bound on positive energy and the trace identity give the lower
bound on negative energy by the literal formula
`graphQ G = 2 |E(G)| - |V| + 1`. -/
lemma card_sub_one_le_negativeSquareEnergy_of_positive_le_graphQ
    (G : SimpleGraph V) [DecidableRel G.Adj]
    (hpos : positiveSquareEnergy G ≤ graphQ G) :
    (Fintype.card V : ℝ) - 1 ≤ negativeSquareEnergy G := by
  have hsum := squareEnergies_add_eq_twice_card_edges G
  rw [graphQ] at hpos
  linarith

end

end SquareEnergy

end

section
/-
Copyright (c) 2026 Shengtong Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shengtong Zhang
-/


/-!
# The square-energy theorem

This file exposes the two component lower bounds and their combined final
form. The square energies use strict positive and strict negative filters, so
zero adjacency eigenvalues contribute to neither energy.
-/

namespace SquareEnergy

noncomputable section

variable {V : Type*} [Fintype V] [DecidableEq V]

/-- The positive square energy of a nontrivial connected graph is at least
`|V| - 1`. -/
lemma card_sub_one_le_positiveSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤ positiveSquareEnergy G :=
  card_sub_one_le_positiveSquareEnergy_of_negative_le_graphQ G
    (negativeSquareEnergy_le_graphQ G hG)

/-- The negative square energy of a nontrivial connected graph is at least
`|V| - 1`. -/
lemma card_sub_one_le_negativeSquareEnergy
    (G : SimpleGraph V) [DecidableRel G.Adj] [Nontrivial V]
    (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤ negativeSquareEnergy G :=
  card_sub_one_le_negativeSquareEnergy_of_positive_le_graphQ G
    (positiveSquareEnergy_le_graphQ G hG)

/--
Every finite connected simple undirected graph has both positive and negative
square energy at least `|V| - 1`. Adjacency eigenvalues are the real
eigenvalues counted with algebraic multiplicity; the strict sign filters omit
zero eigenvalues. The one-vertex graph is handled separately, while
connectedness excludes the zero-vertex case.
-/
theorem card_sub_one_le_min_squareEnergy
    {V : Type*} [Fintype V] [DecidableEq V]
    (G : SimpleGraph V) [DecidableRel G.Adj] (hG : G.Connected) :
    (Fintype.card V : ℝ) - 1 ≤
      min (positiveSquareEnergy G) (negativeSquareEnergy G) := by
  by_cases hcard : Fintype.card V = 1
  · have hleft : (Fintype.card V : ℝ) - 1 = 0 := by
      norm_num [hcard]
    rw [hleft]
    exact le_min (positiveSquareEnergy_nonneg G) (negativeSquareEnergy_nonneg G)
  · have hcard_pos : 0 < Fintype.card V :=
      Fintype.card_pos_iff.mpr hG.nonempty
    have hcard_gt : 1 < Fintype.card V := by
      omega
    let : Nontrivial V :=
      Fintype.one_lt_card_iff_nontrivial.mp hcard_gt
    exact le_min
      (card_sub_one_le_positiveSquareEnergy G hG)
      (card_sub_one_le_negativeSquareEnergy G hG)

end

end SquareEnergy

end


/- Adapted from Tristan Cazenave, SpectralLean/Invariants.lean and Empirical/RandicL1.lean. -/
namespace Spectral

open Matrix SimpleGraph

variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]

/-- Adjacency matrix over `ℝ` is Hermitian (real symmetric). -/
theorem adj_isHermitian : (G.adjMatrix ℝ).IsHermitian := by
  ext i j
  simp [Matrix.conjTranspose_apply, SimpleGraph.adjMatrix_apply, G.adj_comm]

/-- eigenvalues of the adjacency matrix in decreasing order. -/
noncomputable def adjEig (i : Fin (Fintype.card (Fin n))) : ℝ := (adj_isHermitian G).eigenvalues₀ i

/-- Randić index: sum over edges of `1 / sqrt(d(u) d(v))`. -/
noncomputable def randic : ℝ :=
  ∑ e ∈ G.edgeFinset, Sym2.lift ⟨fun u v => 1 / Real.sqrt ((G.degree u : ℝ) * G.degree v),
    fun u v => by simp [mul_comm]⟩ e


section Spec

variable {n : ℕ} {A : Matrix (Fin n) (Fin n) ℝ} (hA : A.IsHermitian)

omit hA in
lemma herm_transpose (hA : A.IsHermitian) : Aᵀ = A := by
  have : Aᴴ = A := hA; rwa [conjTranspose_eq_transpose_of_trivial] at this

lemma parseval (y z : Fin n → ℝ) :
    ∑ i, (y ⬝ᵥ ⇑(hA.eigenvectorBasis i)) * (⇑(hA.eigenvectorBasis i) ⬝ᵥ z) = y ⬝ᵥ z := by
  have := (hA.eigenvectorBasis).sum_inner_mul_inner (WithLp.toLp 2 y) (WithLp.toLp 2 z)
  simp only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] at this
  simpa [dotProduct_comm] using this

lemma eig_le_top (h : 0 < n) (i : Fin n) : hA.eigenvalues i ≤ hA.eigenvalues₀ ⟨0, by simpa⟩ := by
  unfold IsHermitian.eigenvalues
  exact hA.eigenvalues₀_antitone (Fin.mk_le_mk.2 (Nat.zero_le _))

lemma rayleigh_le (h : 0 < n) (y : Fin n → ℝ) :
    y ⬝ᵥ (A *ᵥ y) ≤ hA.eigenvalues₀ ⟨0, by simpa⟩ * (y ⬝ᵥ y) := by
  rw [← parseval hA y (A *ᵥ y), ← parseval hA y y, Finset.mul_sum]
  apply Finset.sum_le_sum
  intro i _
  have e : ⇑(hA.eigenvectorBasis i) ⬝ᵥ (A *ᵥ y) = hA.eigenvalues i * (⇑(hA.eigenvectorBasis i) ⬝ᵥ y) := by
    rw [dotProduct_mulVec, ← mulVec_transpose, herm_transpose hA, hA.mulVec_eigenvectorBasis,
      smul_dotProduct, smul_eq_mul]
  rw [e, dotProduct_comm y]
  have := eig_le_top hA h i
  have := mul_self_nonneg (⇑(hA.eigenvectorBasis i) ⬝ᵥ y)
  nlinarith

end Spec

section Graph

variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]

lemma edge_sum (f : Fin n → Fin n → ℝ) (hf : ∀ u v, f u v = f v u) :
    2 * ∑ e ∈ G.edgeFinset, Sym2.lift ⟨f, hf⟩ e = ∑ u, ∑ v, G.adjMatrix ℝ u v * f u v := by
  have h1 : ∑ u, ∑ v, G.adjMatrix ℝ u v * f u v = ∑ d : G.Dart, f d.fst d.snd := by
    simp only [adjMatrix_apply, ite_mul, one_mul, zero_mul]
    rw [← Fintype.sum_prod_type' (f := fun u v => if G.Adj u v then f u v else 0),
      ← Finset.sum_filter]
    refine Finset.sum_bij' (fun p h => (⟨p, (Finset.mem_filter.1 h).2⟩ : G.Dart))
      (fun d _ => (d.fst, d.snd)) ?_ ?_ ?_ ?_ ?_ <;> simp
  have h2 : ∑ d : G.Dart, f d.fst d.snd = ∑ d : G.Dart, Sym2.lift ⟨f, hf⟩ d.edge := by
    apply Finset.sum_congr rfl; intro d _; rfl
  rw [h1, h2, ← Finset.sum_fiberwise_of_maps_to (s := Finset.univ) (t := G.edgeFinset)
    (g := Dart.edge) (fun d _ => by simp), Finset.mul_sum]
  apply Finset.sum_congr rfl
  intro e he
  rw [Finset.sum_congr rfl (g := fun _ => Sym2.lift ⟨f, hf⟩ e)
    (fun d hd => by rw [(Finset.mem_filter.1 hd).2]), Finset.sum_const, nsmul_eq_mul]
  rw [G.dart_edge_fiber_card e (by simpa using he)]
  norm_num

lemma row_sum (u : Fin n) : ∑ v, G.adjMatrix ℝ u v = (G.degree u : ℝ) := by
  have := G.adjMatrix_mulVec_const_apply (a := (1 : ℝ)) (v := u)
  simpa [mulVec, dotProduct] using this

lemma deg_sum : ∑ u, (G.degree u : ℝ) = 2 * G.edgeFinset.card := by
  exact_mod_cast G.sum_degrees_eq_twice_card_edges

lemma deg_pos (h2 : 2 ≤ n) (hc : G.Connected) (v : Fin n) : (1 : ℝ) ≤ G.degree v := by
  obtain ⟨w, hw⟩ : ∃ w : Fin n, w ≠ v :=
    if h : v.val = 0 then ⟨⟨1, by omega⟩, fun e => by rw [← e] at h; simp at h⟩
    else ⟨⟨0, by omega⟩, fun e => h (by rw [← e])⟩
  obtain ⟨p, -, -⟩ := hc.exists_path_of_dist v w
  have : 1 ≤ G.degree v := by
    cases p with
    | nil => exact absurd rfl hw
    | cons h _ => exact (G.degree_pos_iff_exists_adj v).2 ⟨_, h⟩
  exact_mod_cast this

/-- `λ₁ R ≥ m` (Favaron–Mahéo–Saclé), from the Rayleigh quotient of `√d`. -/
lemma l1_R_ge_m (h2 : 2 ≤ n) (hc : G.Connected) :
    0 < adjEig G ⟨0, by simp; omega⟩ ∧
    (G.edgeFinset.card : ℝ) ≤ adjEig G ⟨0, by simp; omega⟩ * randic G := by
  set A := G.adjMatrix ℝ
  set l := adjEig G ⟨0, by simp; omega⟩
  set d : Fin n → ℝ := fun u => (G.degree u : ℝ)
  set m : ℝ := (G.edgeFinset.card : ℝ)
  have hd : ∀ u, 1 ≤ d u := deg_pos G h2 hc
  let y : Fin n → ℝ := fun u => Real.sqrt (d u)
  have hray := rayleigh_le (adj_isHermitian G) (by omega) y
  have hyy : y ⬝ᵥ y = 2 * m := by
    simp only [dotProduct, y]
    rw [← deg_sum G]; apply Finset.sum_congr rfl; intro u _
    rw [Real.mul_self_sqrt (by linarith [hd u])]
  set S := ∑ u, ∑ v, A u v * (y u * y v)
  have hyAy : y ⬝ᵥ (A *ᵥ y) = S := by
    simp only [dotProduct, mulVec, Finset.mul_sum, S]
    apply Finset.sum_congr rfl; intro u _; apply Finset.sum_congr rfl; intro v _; ring
  have hR : 2 * randic G = ∑ u, ∑ v, A u v * (1 / Real.sqrt (d u * d v)) :=
    edge_sum G _ _
  have hA2m : ∑ u, ∑ v, A u v = 2 * m := by
    rw [← deg_sum G]; exact Finset.sum_congr rfl (fun u _ => row_sum G u)
  have hS : S ≤ l * (2 * m) := by rw [← hyAy, ← hyy]; exact hray
  obtain ⟨u0, v0, huv⟩ : ∃ u v, G.Adj u v := by
    obtain ⟨p, -, -⟩ := hc.exists_path_of_dist (⟨0, by omega⟩ : Fin n) ⟨1, by omega⟩
    cases p with
    | cons h _ => exact ⟨_, _, h⟩
  have hypos : ∀ u, 0 < y u := fun u => Real.sqrt_pos.2 (by linarith [hd u])
  have hterm : ∀ u v, 0 ≤ A u v * (y u * y v) := fun u v => by
    have : 0 ≤ A u v := by by_cases h : G.Adj u v <;> simp [A, adjMatrix_apply, h]
    have := hypos u; have := hypos v; positivity
  have hSpos : 0 < S := by
    apply Finset.sum_pos' (fun u _ => Finset.sum_nonneg (fun v _ => hterm u v))
    refine ⟨u0, Finset.mem_univ _, Finset.sum_pos' (fun v _ => hterm u0 v) ⟨v0, Finset.mem_univ _, ?_⟩⟩
    have := hypos u0; have := hypos v0
    simp [A, adjMatrix_apply, huv]; positivity
  have hm : 0 < m := by
    have : 0 < l * (2 * m) := lt_of_lt_of_le hSpos hS
    by_contra hneg; push Not at hneg
    have hm0 : (0 : ℝ) ≤ m := by positivity
    have : m = 0 := le_antisymm hneg hm0
    rw [this] at hS; linarith
  have hl : 0 < l := by
    by_contra hneg; push Not at hneg; nlinarith
  refine ⟨hl, ?_⟩
  -- AM-GM on each edge
  have hpt : ∀ u v, A u v * 2 ≤ A u v * (y u * y v) / l + l * (A u v * (1 / Real.sqrt (d u * d v))) := by
    intro u v
    by_cases h : G.Adj u v
    · simp only [A, adjMatrix_apply, h, ite_true, one_mul]
      have hs : Real.sqrt (d u * d v) = y u * y v := Real.sqrt_mul (by linarith [hd u]) _
      rw [hs]
      have ha : 0 < y u * y v := mul_pos (hypos u) (hypos v)
      rw [div_add' _ _ _ hl.ne', le_div_iff₀ hl]
      have : l * (1 / (y u * y v)) * l = l ^ 2 / (y u * y v) := by field_simp
      rw [this, show y u * y v + l ^ 2 / (y u * y v) = ((y u * y v) ^ 2 + l ^ 2) / (y u * y v) by
        field_simp]
      rw [le_div_iff₀ ha]; nlinarith [sq_nonneg (y u * y v - l)]
    · simp [A, adjMatrix_apply, h]
  have hsum : ∑ u, ∑ v, A u v * 2 ≤ S / l + l * (2 * randic G) := by
    rw [hR, Finset.sum_div, Finset.mul_sum, ← Finset.sum_add_distrib]
    apply Finset.sum_le_sum; intro u _
    rw [Finset.sum_div, Finset.mul_sum, ← Finset.sum_add_distrib]
    exact Finset.sum_le_sum fun v _ => hpt u v
  have h4m : ∑ u, ∑ v, A u v * 2 = 2 * (2 * m) := by
    rw [← hA2m, Finset.mul_sum]; apply Finset.sum_congr rfl; intro u _
    rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro v _; ring
  have hSl : S / l ≤ 2 * m := by rw [div_le_iff₀ hl]; linarith
  linarith


end Graph
end Spectral


open Matrix WithLp
open scoped BigOperators

namespace RandicSecondBound

private theorem randic_quad_upper {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj]
    (x : Fin n → ℝ) (hx : ∑ i, x i = 0) :
    2 * (((G.adjMatrix ℝ) *ᵥ x) ⬝ᵥ x) +
      2 * (x ⬝ᵥ x) ≤ (n : ℝ) * (x ⬝ᵥ x) := by
  classical
  let a := G.adjMatrix ℝ
  have pt (i j : Fin n) :
      (4 * a i j + (if i = j then 4 else 0) - 2) * x i * x j ≤ (x i)^2 + (x j)^2 := by
    by_cases he : i = j
    · subst j
      simp [a]
      nlinarith
    · by_cases h : G.Adj i j
      · simp [a, he, h]
        nlinarith [sq_nonneg (x i - x j)]
      · simp [a, he, h]
        nlinarith [sq_nonneg (x i + x j)]
  have hsum := Finset.sum_le_sum (s := Finset.univ) fun i _ =>
    Finset.sum_le_sum (s := Finset.univ) fun j _ => pt i j
  have hi (i : Fin n) :
      ∑ j, (4 * a i j + (if i = j then 4 else 0) - 2) * x i * x j =
      4 * (∑ j, a i j * x j) * x i + 4 * (x i * x i) := by
    calc
      _ = ∑ j, ((4 * x i) * (a i j * x j) + (if i = j then 4 * x i * x j else 0)
          - 2 * x i * x j) := by
            apply Finset.sum_congr rfl
            intro j _
            split_ifs <;> ring
      _ = _ := by
        rw [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, ← Finset.mul_sum, hx]
        simp
        ring
  simp_rw [hi, Finset.sum_add_distrib] at hsum
  simp [← Finset.mul_sum, pow_two] at hsum
  change 2 * ∑ i, (∑ j, a i j * x j) * x i + 2 * ∑ i, x i * x i ≤
    n * ∑ i, x i * x i
  have hf : ∑ i, 4 * (∑ j, a i j * x j) * x i =
      4 * ∑ i, (∑ j, a i j * x j) * x i := by
    rw [Finset.mul_sum]
    apply Finset.sum_congr rfl
    intro i _
    ring
  rw [hf] at hsum
  linarith

theorem randic_second_bound {n : ℕ} (hn : 2 ≤ n) (G : SimpleGraph (Fin n))
    [DecidableRel G.Adj] :
    (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ + 1 ≤ (n : ℝ) / 2 := by
  classical
  let hA := G.isHermitian_adjMatrix ℝ
  let e : Fin (Fintype.card (Fin n)) ≃ Fin n := Fintype.equivOfCardEq (Fintype.card_fin _)
  let k0 : Fin (Fintype.card (Fin n)) := ⟨0, by simp; omega⟩
  let k1 : Fin (Fintype.card (Fin n)) := ⟨1, by simp; omega⟩
  let f (k : Fin (Fintype.card (Fin n))) : Fin n → ℝ := ⇑(hA.eigenvectorBasis (e k))
  have ev (k) : (G.adjMatrix ℝ) *ᵥ f k = hA.eigenvalues₀ k • f k := by
    simp [f, hA.mulVec_eigenvectorBasis, Matrix.IsHermitian.eigenvalues, e]
  have orth (k l) : f k ⬝ᵥ f l = if k = l then 1 else 0 := by
    have h := orthonormal_iff_ite.mp hA.eigenvectorBasis.orthonormal (e l) (e k)
    rw [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] at h
    simpa [f, eq_comm] using h
  have h01 : k0 ≠ k1 := by simp [k0, k1, Fin.ext_iff]
  have hle : hA.eigenvalues₀ k1 ≤ hA.eigenvalues₀ k0 :=
    hA.eigenvalues₀_antitone (show k0 ≤ k1 by exact Fin.mk_le_mk.mpr (by decide))
  have key (a b : ℝ) (hab : a ≠ 0 ∨ b ≠ 0)
      (hz : ∑ i, (a • f k0 + b • f k1) i = 0) :
      hA.eigenvalues₀ k1 + 1 ≤ (n : ℝ) / 2 := by
    have H := randic_quad_upper G (a • f k0 + b • f k1) hz
    simp only [mulVec_add, mulVec_smul, ev, add_dotProduct, dotProduct_add, smul_dotProduct,
      dotProduct_smul, smul_eq_mul, orth, ite_true, ite_eq_right h01, ite_eq_right (Ne.symm h01),
      mul_one, mul_zero, zero_add, add_zero] at H
    have pos : 0 < a*a + b*b := by
      rcases hab with ha | hb
      · nlinarith [sq_pos_of_ne_zero ha, sq_nonneg b]
      · nlinarith [sq_pos_of_ne_zero hb, sq_nonneg a]
    apply le_of_mul_le_mul_right _ pos
    nlinarith [mul_nonneg (sub_nonneg.mpr hle) (sq_nonneg a)]
  by_cases hs : ∑ i, f k0 i = 0
  · exact key 1 0 (Or.inl one_ne_zero) (by simpa using hs)
  · refine key (∑ i, f k1 i) (-(∑ i, f k0 i)) (Or.inr (neg_ne_zero.mpr hs)) ?_
    simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul, Finset.sum_add_distrib,
      ← Finset.mul_sum]
    ring

end RandicSecondBound

/-- For a connected graph with at least two vertices, its second largest adjacency
eigenvalue plus one is at most its Randić index. -/
theorem nullius_main {n : ℕ} (hn : 2 ≤ n) (G : SimpleGraph (Fin n))
    [DecidableRel G.Adj] (hc : G.Connected) :
    (G.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ + 1 ≤ Spectral.randic G := by
  classical
  haveI : Nontrivial (Fin n) := Fin.nontrivial_iff_two_le.mpr hn
  let ev := (G.isHermitian_adjMatrix ℝ).eigenvalues₀
  let a : Fin (Fintype.card (Fin n)) := ⟨0, by simp; omega⟩
  let b : Fin (Fintype.card (Fin n)) := ⟨1, by simp; omega⟩
  let e : Fin (Fintype.card (Fin n)) ≃ Fin n := Fintype.equivOfCardEq (Fintype.card_fin _)
  obtain ⟨hfirst, hfms⟩ := Spectral.l1_R_ge_m G hn hc
  change 0 < ev a at hfirst
  have hsize := RandicSecondBound.randic_second_bound hn G
  have henergy := SquareEnergy.positiveSquareEnergy_le_graphQ G hc
  rw [SquareEnergy.positiveSquareEnergy,
    ← SquareEnergy.sum_sq_posPart_eq_filter, SquareEnergy.graphQ, Fintype.card_fin] at henergy
  let f := fun j => (max (ev j) 0)^2
  have hu : (∑ i, f (e.symm i)) = ∑ j, f j := e.symm.sum_comp f
  change (∑ i, f (e.symm i)) ≤ _ at henergy
  rw [hu] at henergy
  have hab : a ≠ b := fun h => by have := congrArg Fin.val h; change 0 = 1 at this; omega
  have hp := Finset.sum_le_sum_of_subset_of_nonneg
    (Finset.subset_univ ({a, b} : Finset (Fin (Fintype.card (Fin n)))))
    (fun j _ _ => show 0 ≤ f j from sq_nonneg _)
  rw [Finset.sum_pair hab] at hp
  change (max (ev a) 0)^2 + (max (ev b) 0)^2 ≤ _ at hp
  rw [max_eq_left hfirst.le] at hp
  have ht : (max (ev b) 0) + 1 ≤ (n : ℝ) / 2 := by
    rw [← max_add_add_right, max_le_iff]
    refine ⟨hsize, ?_⟩
    have hn' : (2 : ℝ) ≤ n := by exact_mod_cast hn
    linarith
  change (G.edgeFinset.card : ℝ) ≤ ev a * Spectral.randic G at hfms
  have hprod : ev a * (max (ev b) 0 + 1) ≤ (G.edgeFinset.card : ℝ) := by
    nlinarith [hp.trans henergy, sq_nonneg (ev a - (max (ev b) 0 + 1))]
  have hR := (le_of_mul_le_mul_left (hprod.trans hfms) hfirst)
  exact (add_le_add_left (le_max_left (ev b) 0) 1).trans hR

-- ===== Bridge =====

lemma nullius_bridge_eig {m m' : Type*} [Fintype m] [DecidableEq m] [Fintype m'] [DecidableEq m']
    {A : Matrix m m ℝ} {B : Matrix m' m' ℝ} (hA : A.IsHermitian) (hB : B.IsHermitian)
    (hch : A.charpoly = B.charpoly) (k : ℕ) (h1 : k < Fintype.card m) (h2 : k < Fintype.card m') :
    hA.eigenvalues₀ ⟨k, h1⟩ = hB.eigenvalues₀ ⟨k, h2⟩ := by
  have h : List.ofFn hA.eigenvalues₀ = List.ofFn hB.eigenvalues₀ := by
    rw [← hA.sort_roots_charpoly_eq_eigenvalues₀, ← hB.sort_roots_charpoly_eq_eigenvalues₀, hch]
  have := congrArg (fun l => l[k]?) h
  simpa [List.getElem?_ofFn, h1, h2] using this

theorem nullius_bridge : NulliusClaim := by
  classical
  intro V _ G hn hc
  intro lam R
  let n := Fintype.card V
  let e : V ≃ Fin n := Fintype.equivFin V
  let G' : SimpleGraph (Fin n) := G.comap e.symm
  let φ : G' ≃g G := SimpleGraph.Iso.comap e.symm G
  have hc' : G'.Connected := φ.connected_iff.mpr hc
  have main := nullius_main (n := n) hn G' hc'
  have hR : Spectral.randic G' = R := by
    unfold Spectral.randic
    refine Finset.sum_nbij' (Sym2.map e.symm) (Sym2.map e) ?_ ?_ ?_ ?_ ?_
    · intro x
      induction x using Sym2.ind with | _ a b => ?_
      simp [G']
    · intro x
      induction x using Sym2.ind with | _ a b => ?_
      simp [G']
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      simp
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      simp
    · intro x _
      induction x using Sym2.ind with | _ a b => ?_
      have ha : G'.degree a = G.degree (e.symm a) := (φ.degree_eq a).symm
      have hb : G'.degree b = G.degree (e.symm b) := (φ.degree_eq b).symm
      simp [Sym2.mul_mk, ha, hb]
  have hE : (G'.isHermitian_adjMatrix ℝ).eigenvalues₀ ⟨1, by simp; omega⟩ = lam := by
    apply nullius_bridge_eig
    have : G'.adjMatrix ℝ = Matrix.reindex e e (G.adjMatrix ℝ) := by
      ext i j
      simp [G', SimpleGraph.adjMatrix_apply]
    rw [this, Matrix.charpoly_reindex]
  rw [hE, hR] at main
  exact main

-- ===== Gate =====
theorem nullius_final_check : _root_.NulliusClaim := nullius_bridge
#print axioms nullius_final_check