module
public import SubentropyCertificates.EqualPriorSubentropy
public import SubentropyCertificates.CurveInverse
public import SubentropyCertificates.CurveTangent

/-! The scalar overlap curves and the inverse subentropy bound on the
physical interval, expressed using the paper's ensemble quantities. -/
@[expose] public section
noncomputable section
set_option autoImplicit false
open Set
open scoped BigOperators
namespace SubentropyCertificates.SmallOverlap
open SubentropyCertificates.ClassicalCurve
open SubentropyCertificates.Discrimination
open SubentropyCertificates.BinarySpectra
open SubentropyCertificates.Helstrom
open SubentropyCertificates.PinchingEquality
open D5.S3.Quantum.Subentropy.ClassicalQuantumGram
open D5.S3.Quantum.Subentropy.GuessingProbability

def conditionalCurve (s : ℝ) := phi 0 (1/2) - phi 0 ((1-s)/2)
def errorCurve (s : ℝ) := (1-Real.sqrt (1-s^2))/2

/-- Both scalar functions are the original operational quantities. -/
theorem ensemble_curves {D : Type*} [Fintype D] [DecidableEq D] (v w : D → ℂ)
    (hv : amplitude v v=1) (hw : amplitude w w=1) :
    let s := ‖amplitude v w‖
    let ρ := purePair v w hv hw
    conditionalSubentropy halfPrior halfPrior_nonneg halfPrior_sum ρ = conditionalCurve s ∧
    1-pGuess halfPrior ρ = errorCurve s := by
  have h := phi_uniform_endpoint 0
  norm_num [uniformError,harmonic_succ,harmonic_zero] at h
  have hu : phi 0 (1/2) = Real.log 2-1/2 := by linarith
  simpa only [conditionalCurve,errorCurve,hu] using equal_prior_conditional_subentropy v w hv hw

theorem conditionalCurve_mem (s : Icc (0:ℝ) 1) : conditionalCurve s ∈ curveRange 0 := by
  obtain ⟨v,w,hv,hw,hs⟩ := realize_overlap s.property
  have h := (ensemble_curves v w hv hw).1
  rw [hs] at h
  rw [← h]
  exact conditional_subentropy_range 0 (by decide) _ _ _ _

/-- Evaluate the genuine increasing-branch inverse at the conditional
subentropy. Its argument is in range on the entire physical interval. -/
def subentropyBound (s : Icc (0:ℝ) 1) := phiInverse 0 (conditionalCurve s) (conditionalCurve_mem s)

theorem bound_nonneg_le_error (s : Icc (0:ℝ) 1) :
    0 ≤ subentropyBound s ∧ subentropyBound s ≤ errorCurve s := by
  obtain ⟨v,w,hv,hw,hs⟩ := realize_overlap s.property
  obtain ⟨hq,he⟩ := ensemble_curves v w hv hw
  rw [hs] at hq he
  have h := inverse_discrimination_bound 0 (by decide : Fintype.card (Fin 2)=0+2)
    halfPrior halfPrior_nonneg halfPrior_sum (purePair v w hv hw)
  rw [he] at h
  refine ⟨(phiInverse_mem 0 _ _).1,?_⟩
  convert h using 1
  unfold subentropyBound
  congr 1
  exact hq.symm

theorem phi_bound (s : Icc (0:ℝ) 1) : phi 0 (subentropyBound s) = conditionalCurve s :=
  phi_phiInverse 0 _ _

end SubentropyCertificates.SmallOverlap
