module

public import SubentropyCertificates.MarginalDeterminants
public import SubentropyCertificates.PureMarginalDiagonal
public import SubentropyCertificates.SliceProducts

/-! Pointwise determinant comparison with the two partial traces,
including equality at each parameter (prop:pointwise-determinant). -/
@[expose] public section
noncomputable section
set_option autoImplicit false
set_option backward.isDefEq.respectTransparency false
open Matrix
open scoped BigOperators ComplexOrder MatrixOrder
namespace SubentropyCertificates.DeterminantComparison
open D5.S3.Quantum.Foundation.FiniteStateChannel
open D5.S3.Quantum.Information.PartialTraceMutualInformation
open D5.S3.Quantum.Information.InputInformationBalance
open D5.S3.Quantum.Subentropy.Basic
open D5.S3.Quantum.Subentropy.DensityKernel
open SubentropyCertificates.ClassicalSSA
open SubentropyCertificates.ClassicalCurve
open SubentropyCertificates.Subadditivity
open SubentropyCertificates.QuantumEquality
variable {D F : Type*} [Fintype D] [DecidableEq D] [Fintype F] [DecidableEq F]

private theorem single_atom_iff (w : D → ℝ) (hw : w ∈ probabilitySimplex D) :
    ¬ varies Finset.univ w ↔ ∃ i, w = pointMass i := by
  constructor
  · intro hn
    obtain ⟨i,hi⟩ : ∃ i, 0 < w i := by
      by_contra! hz
      have h := Finset.sum_nonpos (s := Finset.univ) (fun j _ => hz j)
      linarith only [h, hw.2]
    have hz (j) (_ : j ∈ Finset.univ) (hji : j ≠ i) : w j = 0 := by
      by_contra h0
      exact hn ⟨i, Finset.mem_univ _, j, Finset.mem_univ _, hji, hi,
        lt_of_le_of_ne (hw.1 j) (Ne.symm h0)⟩
    exact ⟨i, (eq_pointMass_iff_probability_one w hw i).mpr
      ((Finset.sum_eq_single_of_mem i (Finset.mem_univ i) hz).symm.trans hw.2)⟩
  · rintro ⟨i,rfl⟩ ⟨j,_,k,_,hne,hj,hk⟩
    by_cases eqj : j=i
    · have hki : k ≠ i := fun eq => hne (eq.trans eqj.symm)
      simp [pointMass, hki] at hk
    · simp [pointMass, eqj] at hj

private theorem pure_iff_point_spectrum (ρ : DensityState D) :
    IsPure ρ ↔ ∃ i, (density_posSemidef ρ).isHermitian.eigenvalues = pointMass i := by
  rw [← subentropy_zero_iff_pure, subentropy, subentropy_of_spectrum (density_posSemidef ρ).isHermitian]
  exact classical_zero_iff_pointMass _ (spectral_prob (density_posSemidef ρ) ρ.2.2)

private theorem reciprocal_diagonal (w : D → ℝ) (t : ℝ) :
    reciprocalDet t (diagonal (fun i => (w i : ℂ))) = kernel t w := by
  have hd : (1 : Matrix D D ℂ) + t • diagonal (fun i => (w i : ℂ)) =
      diagonal (fun i => ((1 + w i*t : ℝ) : ℂ)) := by
    ext i j
    by_cases hij : i=j
    · subst j; simp [Complex.real_smul, mul_comm]
    · simp [hij]
  unfold reciprocalDet kernel factor
  rw [hd, Matrix.det_diagonal, ← Complex.ofReal_prod, Complex.ofReal_re, Finset.prod_inv_distrib]

/-- The sum of the reciprocal marginal determinants is bounded above by
the joint reciprocal determinant plus 1/(1+t). For positive t equality
is equivalent to purity of a marginal. At zero every state attains equality. -/
theorem pointwise_determinant_comparison (ρ : DensityState (D × F)) {t : ℝ} (ht : 0 ≤ t) :
    let A := CStarMatrix.ofMatrix.symm (marginalRight ρ).1
    let B := CStarMatrix.ofMatrix.symm (marginalLeft ρ).1
    let M := CStarMatrix.ofMatrix.symm ρ.1
    reciprocalDet t A + reciprocalDet t B ≤ reciprocalDet t M + 1/(1+t) ∧
    (reciprocalDet t A + reciprocalDet t B = reciprocalDet t M + 1/(1+t) ↔
      t=0 ∨ IsPure (marginalRight ρ) ∨ IsPure (marginalLeft ρ)) := by
  rcases ht.eq_or_lt with hz | ht
  · subst t; simp [reciprocalDet]
  let M := CStarMatrix.ofMatrix.symm ρ.1
  let hR := (partialTraceRight_posSemidef (density_posSemidef ρ)).isHermitian
  let hL := (partialTraceLeft_posSemidef (density_posSemidef ρ)).isHermitian
  let a := hR.eigenvalues
  let b := hL.eigenvalues
  obtain ⟨K,hK,htr,hA,hB,hdet⟩ := marginal_eigenbasis_determinants ρ
  let p := fun (i : D) (j : F) => (K (i,j) (i,j)).re
  have hp (i j) : 0 ≤ p i j := (RCLike.nonneg_iff.mp (hK.diag_nonneg (i := (i,j)))).1
  have hr : rowMass p = a := by
    funext i
    simpa [rowMass, p, a, hR, partialTraceRight, Complex.re_sum] using
      congrArg (fun N => (N i i).re) hA
  have hc : colMass Finset.univ p = b := by
    funext j
    simpa [colMass, p, b, hL, partialTraceLeft, Complex.re_sum] using
      congrArg (fun N => (N j j).re) hB
  have hpa : a ∈ probabilitySimplex D := spectral_prob (density_posSemidef (marginalRight ρ)) (marginalRight ρ).2.2
  have hpb : b ∈ probabilitySimplex F := spectral_prob (density_posSemidef (marginalLeft ρ)) (marginalLeft ρ).2.2
  have hm : mass Finset.univ p = 1 := by unfold mass; rw [hr, hpa.2]
  have hcells : cells t Finset.univ p = kernel t (fun i => (K i i).re) := by
    simp only [cells, kernel, p, Fintype.prod_prod_type]
  have hclass := table_subadditivity ht.le Finset.univ p hp
  have he := table_subadditivity_eq_iff ht p hp
  change kernel t (rowMass p) + kernel t (colMass Finset.univ p) ≤ _ at hclass
  change (kernel t (rowMass p) + kernel t (colMass Finset.univ p) = _) ↔ _ at he
  rw [hr,hc,hm,hcells, factor, one_mul, ← one_div] at hclass he
  have ha := pure_iff_point_spectrum (marginalRight ρ)
  have hb := pure_iff_point_spectrum (marginalLeft ρ)
  change IsPure (marginalRight ρ) ↔ ∃ i, a = pointMass i at ha
  change IsPure (marginalLeft ρ) ↔ ∃ j, b = pointMass j at hb
  rw [single_atom_iff a hpa, single_atom_iff b hpb, ← ha, ← hb] at he
  change reciprocalDet t (partialTraceRight M) + reciprocalDet t (partialTraceLeft M) ≤ _ ∧
    (reciprocalDet t (partialTraceRight M) + reciprocalDet t (partialTraceLeft M) = _ ↔ _)
  rw [reciprocalDet_spectral hR, reciprocalDet_spectral hL, ← hdet t]
  change kernel t a + kernel t b ≤ reciprocalDet t K + 1/(1+t) ∧
    (kernel t a + kernel t b = reciprocalDet t K + 1/(1+t) ↔ _)
  have hdiag := diagonal_kernel_le_reciprocalDet hK ht.le
  refine ⟨hclass.trans (add_le_add hdiag (le_refl _)), ?_⟩
  constructor
  · intro eq
    exact Or.inr (he.mp (by linarith only [eq, hdiag, hclass]))
  · rintro (hz | hpure)
    · exact (ht.ne' hz).elim
    · have hd := diagonal_of_point_marginal hK a b hA hB (hpure.imp ha.mp hb.mp)
      exact (he.mpr hpure).trans (congrArg (fun z => z + 1/(1+t))
        ((reciprocal_diagonal _ t).symm.trans (congrArg (reciprocalDet t) hd.symm)))

/-- If both marginals are mixed, the comparison is strict at every positive parameter. -/
theorem pointwise_determinant_strict (ρ : DensityState (D × F)) {t : ℝ} (ht : 0 < t)
    (hA : ¬ IsPure (marginalRight ρ)) (hB : ¬ IsPure (marginalLeft ρ)) :
    reciprocalDet t (CStarMatrix.ofMatrix.symm (marginalRight ρ).1) +
        reciprocalDet t (CStarMatrix.ofMatrix.symm (marginalLeft ρ).1) <
      reciprocalDet t (CStarMatrix.ofMatrix.symm ρ.1) + 1/(1+t) := by
  obtain ⟨hle, heq⟩ := pointwise_determinant_comparison ρ ht.le
  apply lt_of_le_of_ne hle
  intro h
  rcases heq.mp h with hz | ha | hb
  · exact ht.ne' hz
  · exact hA ha
  · exact hB hb

end SubentropyCertificates.DeterminantComparison
