module

public import SubentropyCertificates.RobustContinuity
public import SubentropyCertificates.UniformInverseLimit

/-! Certified inversion with both state uncertainty and numerical uncertainty. -/
@[expose] public section
noncomputable section
set_option autoImplicit false
set_option backward.isDefEq.respectTransparency false
open Matrix Set Filter
open scoped BigOperators ComplexOrder MatrixOrder Matrix.Norms.L2Operator Kronecker Topology
namespace SubentropyCertificates.Robust
open D5.S3.Quantum.Foundation.FiniteStateChannel (DensityState)
open D5.S3.Quantum.Information.PartialTraceMutualInformation (productState)
open D5.S3.Quantum.Subentropy.ClassicalQuantumGram (conditionalSubentropy)
open SubentropyCertificates.CompactStability
open SubentropyCertificates.MixedQubit (traceDistance)
open SubentropyCertificates.ConditionalContinuity
open SubentropyCertificates.SpectralContinuity (maximallyMixed)
open SubentropyCertificates.AncillaCalibration
open SubentropyCertificates.Discrimination

variable {X D : Type*} [Fintype X] [DecidableEq X] [Fintype D] [DecidableEq D]

/-- The clipped argument lies below the true value, within twice the combined error. -/
theorem clipped_bracket {q s v η r : ℝ} (hq : 0 ≤ q) (hev : |v-s| ≤ η) (hst : |s-q| ≤ r) :
    q - 2*(η+r) ≤ max 0 (v-η-r) ∧ max 0 (v-η-r) ≤ q := by
  rw [abs_le] at hev hst
  exact ⟨le_trans (by linarith [hev.1,hst.1]) (le_max_right _ _),
    max_le hq (by linarith [hev.2,hst.2])⟩

/-- Eq. (robust-certificate) for every certified state error radius, in particular
the three-term radius of conditional_continuity and its fixed-marginal refinement. -/
theorem ordinary_certificate (l : ℕ) (hn : Fintype.card X = l + 2) (E F : Ensemble X D)
    {v η R : ℝ} (hv : |v - conditional F| ≤ η) (hR : |conditional F - conditional E| ≤ R) :
    ∃ h : max 0 (v-η-R) ∈ curveRange l, phiInverse l (max 0 (v-η-R)) h ≤ guessingError E := by
  have hr := conditional_subentropy_range l hn E.1 E.1.2.1 E.1.2.2 (fun x ↦ asState (E.2 x))
  have h := (clipped_bracket hr.1 hv hR).2
  have hi : max 0 (v-η-R) ∈ curveRange l := ⟨le_max_left _ _, h.trans hr.2⟩
  refine ⟨hi, error_threshold_lower_bound l hn E.1 E.1.2.1 E.1.2.2 (fun x ↦ asState (E.2 x))
    _ (phiInverse_mem l _ hi) ?_⟩
  simpa only [phi_phiInverse] using h


/-- The lower bound using the full three-term radius in §6.4. -/
theorem ordinary_certificate_of_trace_distance (l : ℕ) (hn : Fintype.card X = l + 2)
    (E F : Ensemble X D) {v η δ : ℝ} (hv : |v - conditional F| ≤ η)
    (hd : traceDistance (record E) (record F) ≤ δ) :
    let R := min δ (min (SpectralContinuity.quantumModulus (Fintype.card X * Fintype.card D) δ +
      SpectralContinuity.quantumModulus (Fintype.card D) δ)
      (Real.log (Fintype.card X) - (harmonic (Fintype.card X) : ℝ) + 1))
    ∃ h : max 0 (v-η-R) ∈ curveRange l, phiInverse l (max 0 (v-η-R)) h ≤ guessingError E :=
  ordinary_certificate l hn E F hv (conditional_continuity l hn E F hd)

/-- Fixing the marginal state improves the first term of the certified radius. -/
theorem ordinary_certificate_fixed_marginal (l : ℕ) (hn : Fintype.card X = l + 2)
    (E F : Ensemble X D) (hEF : average E = average F) {v η δ : ℝ}
    (hv : |v - conditional F| ≤ η) (hd : traceDistance (record E) (record F) ≤ δ) :
    let R := min (‖spatialSign (BinarySpectra.densityMatrix (average E))‖ * δ)
      (min (SpectralContinuity.quantumModulus (Fintype.card X * Fintype.card D) δ +
        SpectralContinuity.quantumModulus (Fintype.card D) δ)
        (Real.log (Fintype.card X) - (harmonic (Fintype.card X) : ℝ) + 1))
    ∃ h : max 0 (v-η-R) ∈ curveRange l, phiInverse l (max 0 (v-η-R)) h ≤ guessingError E :=
  ordinary_certificate l hn E F hv (fixed_conditional_continuity l hn E F hEF hd)

/-- Conditional subentropy of the product extension of a CQ ensemble. -/
def extendedConditional {C : Type*} [Fintype C] [DecidableEq C] (ν : DensityState C)
    (E : Ensemble X D) : ℝ :=
  conditionalSubentropy E.1 E.1.2.1 E.1.2.2 (fun x ↦ productState (asState (E.2 x)) ν)

theorem extended_conditional_blocks {C : Type*} [Fintype C] [DecidableEq C] (ν : DensityState C)
    (E : Ensemble X D) :
    extendedConditional ν E = blockConditionalQ (ancillaBlocks ν (ensembleBlocks E)) := by
  let F := ofEnsemble E.1 E.1.2.1 E.1.2.2 (fun x ↦ productState (asState (E.2 x)) ν)
  change conditional F = _
  rw [conditional_blocks]
  congr 1
  funext x
  change E.1.1 x • ((E.2 x).1 ⊗ₖ BinarySpectra.densityMatrix ν) =
    (E.1.1 x • (E.2 x).1) ⊗ₖ BinarySpectra.densityMatrix ν
  rw [smul_kronecker]

/-- The error in the extended conditional subentropy is at most δ divided by the ancilla dimension. -/
theorem calibrated_state_error (C : Type*) [Fintype C] [DecidableEq C] [Nonempty C]
    (E F : Ensemble X D) {δ : ℝ} (hδ : traceDistance (record E) (record F) ≤ δ) :
    |extendedConditional (maximallyMixed C) F - extendedConditional (maximallyMixed C) E| ≤
      δ / (Fintype.card C : ℝ) := by
  rw [extended_conditional_blocks, extended_conditional_blocks]
  have h := (cq_maximallyMixed_ancilla_continuity C (ensembleBlocks E) (ensembleBlocks F)
    (ensembleBlocks_pos E) (ensembleBlocks_pos F) (ensembleBlocks_trace E) (ensembleBlocks_trace F)).2
  exact h.trans (div_le_div_of_nonneg_right ((record_distance_blocks E F).symm.le.trans hδ) (by positivity))

/-- Eq. (calibrated-robust-certificate), including the inverse-domain guarantee. -/
theorem calibrated_certificate (C : Type*) [Fintype C] [DecidableEq C] [Nonempty C]
    (l : ℕ) (hn : Fintype.card X = l + 2) (E F : Ensemble X D) {v η δ : ℝ}
    (hv : |v - extendedConditional (maximallyMixed C) F| ≤ η)
    (hδ : traceDistance (record E) (record F) ≤ δ) :
    let q := max 0 (v-η-δ/(Fintype.card C : ℝ))
    let ν := maximallyMixed C
    ∃ h : q ∈ calibratedCurveRange ν l, calibratedPhiInverse ν l q h ≤ guessingError E := by
  dsimp only
  let ν := maximallyMixed C
  have hr := conditional_product_mem_calibratedRange ν l hn E.1 E.1.2.1 E.1.2.2 (fun x ↦ asState (E.2 x))
  have h := (clipped_bracket hr.1 hv (calibrated_state_error C E F hδ)).2
  have hi : max 0 (v-η-δ/(Fintype.card C : ℝ)) ∈ calibratedCurveRange ν l :=
    ⟨le_max_left _ _,h.trans hr.2⟩
  refine ⟨hi, (calibratedPhiInverse_le_iff ν l hi
    (optimal_error_range l hn E.1 E.1.2.1 E.1.2.2 (fun x ↦ asState (E.2 x)))).2 ?_⟩
  exact h.trans (ancilla_optimal_curve_bound ν l hn _ _ _ _)

end SubentropyCertificates.Robust
