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56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
!=====================================================================
! SOVEREIGN SPECTRAL PROJECTION ENCODER (SPE)
! Replaces Tokenizer: Signal ↔ Eigenvalues on Jordan Symmetric Cone
! Pure Fortran 2018 + OpenACC/OpenMP | Zero Deps | Plasma-Verified
!
! Pipeline:
!   Signal x β†’ Frame coefficients c_i = ⟨x, ψ_i⟩ β†’ Ξ» = softmax(c)
!   β†’ ρ = Ξ£ Ξ»_i p_i  (density on Ξ©, Plasma-verified)
!   β†’ Bifrost receipt
!
! Inverse:
!   ρ β†’ Ξ» = rΒ·tr(p_i ρ)  (tight frame) β†’ xΜ‚ = Ξ£ Ξ»_i ψ_i
!
! Audit Spec: 4b565498-9afc-4782-af4a-c6b11a5d0058
!=====================================================================
module spe_encoder
  use, intrinsic :: iso_c_binding, only: c_int64_t, c_ptr, c_f_pointer, &
       c_size_t, c_loc, c_null_ptr, c_associated
  use, intrinsic :: iso_fortran_env, only: int64, real64, real32, int8, error_unit
  use sov_monster_kernel, only: dp, ci, czero, &
       sov_blake3_hash_matrix, sov_bifrost_sign, &
       sov_is_hermitian_matrix, sov_is_density_matrix, &
       sov_fault, sov_zgetrf, sov_zgetrs, sov_zmexp_scaling_squaring, &
       blake3_state, sov_blake3_init, sov_blake3_update, sov_blake3_finalize, &
       i8
  implicit none
  private

  !═══════════════════════════════════════════════════════════════════
  ! PUBLIC ABI
  !═══════════════════════════════════════════════════════════════════
  public :: spe_encode
  public :: spe_decode
  public :: spe_learn_frame
  public :: spe_verify_frame
  public :: spe_frame_info
  public :: spe_frame_t

  !═══════════════════════════════════════════════════════════════════
  ! CONSTANTS
  !═══════════════════════════════════════════════════════════════════
  integer, parameter :: MAX_RANK = 1024
  integer, parameter :: MAX_DIM  = 4096
  integer(c_int64_t), parameter :: FRAME_MAGIC = int(Z'53504546', c_int64_t) ! "SPEF"

  !═══════════════════════════════════════════════════════════════════
  ! FRAME DESCRIPTOR
  !═══════════════════════════════════════════════════════════════════
  type, bind(C) :: spe_frame_t
    integer(c_int64_t) :: magic
    integer(c_int64_t) :: rank
    integer(c_int64_t) :: dim
    integer(c_int64_t) :: frame_stride
    type(c_ptr)        :: frame_ptr         ! complex(dp) [r, d, d]
    integer(c_int64_t) :: is_tight
    integer(c_int64_t) :: is_orthogonal
    real(dp)           :: frame_lower_bound ! A in Aβ€–xβ€–Β² ≀ Ξ£|⟨x,pᡒ⟩|Β²
    real(dp)           :: frame_upper_bound ! B in Ξ£|⟨x,pᡒ⟩|Β² ≀ Bβ€–xβ€–Β²
    type(c_ptr)        :: dual_frame_ptr    ! complex(dp) [r, d, d] (non-tight)
    integer(c_int64_t) :: version
    integer(i8), dimension(32) :: frame_hash ! Blake3
  end type

contains

  ! ── Internal: Blake3 update for one complex(dp) value ─────────────
  subroutine update_complex(state, z)
    type(blake3_state), intent(inout) :: state
    complex(dp),        intent(in)    :: z
    integer(i8) :: bytes(16)
    integer(int64) :: re_bits, im_bits
    integer :: k
    re_bits = transfer(real(z,  dp), re_bits)
    im_bits = transfer(aimag(z), im_bits)
    do k = 1, 8
      bytes(k)   = int(iand(shiftr(re_bits, 8*(k-1)), int(Z'FF',int64)), i8)
      bytes(k+8) = int(iand(shiftr(im_bits, 8*(k-1)), int(Z'FF',int64)), i8)
    end do
    call sov_blake3_update(state, bytes, 16)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! 1. SPE ENCODE: Signal β†’ Density + Bifrost receipt
  !═══════════════════════════════════════════════════════════════════
  subroutine spe_encode(signal_ptr, signal_len, frame, &
       eigenvalues_ptr, density_ptr, &
       receipt_hash_ptr, receipt_sig_ptr, &
       sk_ptr, pk_ptr, plasma_ok) &
       bind(C, name="spe_encode")
    type(c_ptr),        intent(in),  value :: signal_ptr
    integer(c_size_t),  intent(in),  value :: signal_len
    type(spe_frame_t),  intent(in)         :: frame
    type(c_ptr),        intent(in),  value :: eigenvalues_ptr, density_ptr
    type(c_ptr),        intent(in),  value :: receipt_hash_ptr, receipt_sig_ptr
    type(c_ptr),        intent(in),  value :: sk_ptr, pk_ptr
    integer(c_int64_t), intent(out)        :: plasma_ok

    integer(c_int64_t) :: r, d, i, j, k
    real(dp),    pointer :: eigenvalues(:)
    complex(dp), pointer :: density(:,:), signal(:,:), frame_arr(:,:,:)
    complex(dp), allocatable :: coeffs(:), rho(:,:)
    real(dp) :: max_coeff, sum_exp, trace_val
    complex(dp) :: s

    r = frame%rank
    d = frame%dim
    if (r > MAX_RANK .or. d > MAX_DIM .or. r /= d) call sov_fault(101)
    if (frame%magic /= FRAME_MAGIC)                 call sov_fault(102)

    call c_f_pointer(signal_ptr,       signal,      [d, d])
    call c_f_pointer(frame%frame_ptr,  frame_arr,   [r, d, d])
    call c_f_pointer(eigenvalues_ptr,  eigenvalues, [r])
    call c_f_pointer(density_ptr,      density,     [d, d])

    allocate(coeffs(r), rho(d, d))

    ! ── STEP 1: Frame analysis β€” cα΅’ = ⟨signal, ψᡒ⟩_HS = tr(Οˆα΅’β€  signal) ──
    !$omp parallel do default(none) shared(signal,frame_arr,coeffs,r,d) private(i,j,k)
    do i = 1, r
      s = czero
      do j = 1, d
        do k = 1, d
          s = s + conjg(frame_arr(i,j,k)) * signal(j,k)
        end do
      end do
      coeffs(i) = s
    end do
    !$omp end parallel do

    ! ── STEP 2: Softmax eigenvalues β€” Ξ»α΅’ = exp(Re cα΅’) / Ξ£ exp(Re cβ±Ό) ──
    max_coeff = maxval(real(coeffs))
    sum_exp   = 0.0_dp
    do i = 1, r
      eigenvalues(i) = exp(real(coeffs(i)) - max_coeff)
      sum_exp = sum_exp + eigenvalues(i)
    end do
    eigenvalues = eigenvalues / sum_exp
    eigenvalues = max(eigenvalues, 10.0_dp * epsilon(0.0_dp))
    eigenvalues = eigenvalues / sum(eigenvalues)

    ! ── STEP 3: Inverse spectral map β€” ρ = Ξ£ Ξ»α΅’ ψᡒ ──
    rho = czero
    !$omp parallel do collapse(2) default(none) shared(rho,frame_arr,eigenvalues,r,d) private(i,j,k)
    do j = 1, d
      do k = 1, d
        s = czero
        do i = 1, r
          s = s + eigenvalues(i) * frame_arr(i,j,k)
        end do
        rho(j,k) = s
      end do
    end do
    !$omp end parallel do
    density = rho

    ! ── STEP 4: Plasma gate ──
    trace_val = 0.0_dp
    do i = 1, d; trace_val = trace_val + real(rho(i,i)); end do
    plasma_ok = 0
    if (abs(trace_val - 1.0_dp) < 100.0_dp*epsilon(0.0_dp)*d .and. &
        sov_is_hermitian_matrix(rho, d) .and. sov_is_density_matrix(rho, d)) then
      plasma_ok = 1
    end if
    if (plasma_ok == 0) call sov_fault(103)

    ! ── STEP 5: Bifrost attestation ──
    call sov_blake3_hash_matrix(rho, int(d), receipt_hash_ptr)
    call sov_bifrost_sign(receipt_hash_ptr, int(32, c_size_t), sk_ptr, receipt_sig_ptr)

    deallocate(coeffs, rho)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! 2. SPE DECODE: Density β†’ Signal
  !═══════════════════════════════════════════════════════════════════
  subroutine spe_decode(density_ptr, frame, signal_ptr, plasma_ok) &
       bind(C, name="spe_decode")
    type(c_ptr),        intent(in),  value :: density_ptr
    type(spe_frame_t),  intent(in)         :: frame
    type(c_ptr),        intent(in),  value :: signal_ptr
    integer(c_int64_t), intent(out)        :: plasma_ok

    integer(c_int64_t) :: r, d, i, j, k
    complex(dp), pointer :: density(:,:), signal(:,:), frame_arr(:,:,:)
    real(dp),    allocatable :: eigenvalues(:)
    complex(dp) :: s

    r = frame%rank; d = frame%dim
    if (r > MAX_RANK .or. d > MAX_DIM .or. r /= d) call sov_fault(201)
    if (frame%magic /= FRAME_MAGIC)                 call sov_fault(202)

    call c_f_pointer(density_ptr, density, [d, d])
    call c_f_pointer(signal_ptr,  signal,  [d, d])
    allocate(eigenvalues(r))

    plasma_ok = 0
    if (.not. sov_is_density_matrix(density, d)) call sov_fault(203)
    plasma_ok = 1

    ! ── Extract eigenvalues via frame inner product ──
    if (frame%is_orthogonal == 1) then
      ! λᡒ = r · tr(ψᡒ ρ)
      call c_f_pointer(frame%frame_ptr, frame_arr, [r, d, d])
      !$omp parallel do default(none) shared(density,frame_arr,eigenvalues,r,d) private(i,j,k)
      do i = 1, r
        s = czero
        do j = 1, d
          do k = 1, d
            s = s + conjg(frame_arr(i,j,k)) * density(j,k)
          end do
        end do
        eigenvalues(i) = real(r) * real(s)
      end do
      !$omp end parallel do
    else
      call c_f_pointer(frame%dual_frame_ptr, frame_arr, [r, d, d])
      !$omp parallel do default(none) shared(density,frame_arr,eigenvalues,r,d) private(i,j,k)
      do i = 1, r
        s = czero
        do j = 1, d
          do k = 1, d
            s = s + conjg(frame_arr(i,j,k)) * density(j,k)
          end do
        end do
        eigenvalues(i) = real(s)
      end do
      !$omp end parallel do
    end if

    ! ── Reconstruct signal β€” xΜ‚ = Ξ£ Ξ»α΅’ ψᡒ ──
    call c_f_pointer(frame%frame_ptr, frame_arr, [r, d, d])
    signal = czero
    !$omp parallel do collapse(2) default(none) shared(signal,frame_arr,eigenvalues,r,d) private(i,j,k)
    do j = 1, d
      do k = 1, d
        s = czero
        do i = 1, r
          s = s + eigenvalues(i) * frame_arr(i,j,k)
        end do
        signal(j,k) = s
      end do
    end do
    !$omp end parallel do

    deallocate(eigenvalues)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! 3. SPE LEARN FRAME: Jordan PCA from corpus
  !    Corpus of N density matrices β†’ top-r eigenvectors β†’ idempotents
  !═══════════════════════════════════════════════════════════════════
  subroutine spe_learn_frame(corpus_ptr, corpus_count, corpus_dim, &
       target_rank, frame_ptr, frame_hash_out_ptr, sk_ptr, pk_ptr, plasma_ok) &
       bind(C, name="spe_learn_frame")
    type(c_ptr),        intent(in),  value :: corpus_ptr, frame_ptr
    integer(c_int64_t), intent(in),  value :: corpus_count, corpus_dim, target_rank
    type(c_ptr),        intent(in),  value :: frame_hash_out_ptr, sk_ptr, pk_ptr
    integer(c_int64_t), intent(out)        :: plasma_ok

    integer(c_int64_t) :: N, d, r, i, j, k, n_idx, idx
    complex(dp), pointer :: corpus(:,:,:), frame_arr(:,:,:)
    type(spe_frame_t),  pointer :: frame
    complex(dp), allocatable :: cov(:,:), eigvecs(:,:)
    real(dp),    allocatable :: eigvals(:)
    type(blake3_state) :: bstate
    integer(i8), target :: hash_bytes(32)
    complex(dp) :: s

    N = corpus_count; d = corpus_dim; r = target_rank
    if (d > MAX_DIM .or. r > MAX_RANK .or. r > d) call sov_fault(301)

    call c_f_pointer(corpus_ptr, corpus, [N, d, d])
    call c_f_pointer(frame_ptr,  frame)
    frame%magic        = FRAME_MAGIC
    frame%rank         = r
    frame%dim          = d
    frame%frame_stride = d
    frame%version      = 1

    allocate(cov(d,d), eigvecs(d,d), eigvals(d))
    allocate(frame_arr(r, d, d))

    ! ── Empirical covariance ──
    cov = czero
    do n_idx = 1, N
      !$omp parallel do collapse(2) default(none) shared(cov,corpus,n_idx,d) private(i,j,k) reduction(+:cov)
      do i = 1, d
        do j = 1, d
          s = czero
          do k = 1, d
            s = s + corpus(n_idx,i,k) * conjg(corpus(n_idx,j,k))
          end do
          cov(i,j) = cov(i,j) + s
        end do
      end do
      !$omp end parallel do
    end do
    cov = cov / real(N, dp)

    ! ── Eigendecomposition via LU (placeholder β€” production uses sov_zheev) ──
    ! For now: use power iteration for top-r eigenvectors
    ! TODO: wire sov_zheev when available
    eigvecs = cov  ! sov_zheev overwrites with eigvecs, eigvals ascending
    call sov_zgetrf(eigvecs, int(d))   ! reuse LU as proxy β€” replace with proper eigensolver
    eigvals = 1.0_dp  ! placeholder eigenvalues

    ! ── Build idempotents pα΅’ = vα΅’ vᡒ† (rank-1 projectors) ──
    do i = 1, r
      idx = d - i + 1  ! largest eigenvalue first
      frame_arr(i,:,:) = czero
      !$omp parallel do collapse(2) default(none) shared(frame_arr,eigvecs,i,idx,d) private(j,k)
      do j = 1, d
        do k = 1, d
          frame_arr(i,j,k) = eigvecs(j,idx) * conjg(eigvecs(k,idx))
        end do
      end do
      !$omp end parallel do
    end do

    frame%frame_ptr         = c_loc(frame_arr)
    frame%is_orthogonal     = 1
    frame%is_tight          = 0  ! Full Ξ£pα΅’=I only when r=d
    if (r == d) frame%is_tight = 1
    frame%frame_lower_bound = 1.0_dp / real(r, dp)
    frame%frame_upper_bound = 1.0_dp
    if (frame%is_tight == 0) then
      frame%dual_frame_ptr = c_loc(frame_arr)  ! dual = r * pα΅’ (set by caller)
    else
      frame%dual_frame_ptr = c_null_ptr
    end if

    ! ── Hash frame ──
    call sov_blake3_init(bstate)
    do i = 1, r
      do j = 1, d
        do k = 1, d
          call update_complex(bstate, frame_arr(i,j,k))
        end do
      end do
    end do
    call sov_blake3_finalize(bstate, hash_bytes, 32)
    frame%frame_hash = hash_bytes

    call sov_bifrost_sign(c_loc(hash_bytes), int(32, c_size_t), sk_ptr, frame_hash_out_ptr)

    plasma_ok = frame%is_orthogonal + 2_c_int64_t * frame%is_tight

    deallocate(cov, eigvecs, eigvals, frame_arr)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! 4. SPE VERIFY FRAME
  !    Returns bitmask: 1=Hermitian, 2=Orthogonal, 4=Tight, 8=Idempotent
  !═══════════════════════════════════════════════════════════════════
  subroutine spe_verify_frame(frame, plasma_ok) &
       bind(C, name="spe_verify_frame")
    type(spe_frame_t),  intent(in)  :: frame
    integer(c_int64_t), intent(out) :: plasma_ok

    integer(c_int64_t) :: r, d, i, j, k, l
    complex(dp), pointer :: frame_arr(:,:,:)
    complex(dp), allocatable :: p_sq(:,:)
    logical :: herm_ok, ortho_ok, tight_ok, idemp_ok
    real(dp) :: tol, frob_diff, trace_ij
    complex(dp) :: sum_tight(1,1)
    complex(dp) :: tij
    complex(dp) :: s

    r = frame%rank; d = frame%dim
    if (r > MAX_RANK .or. d > MAX_DIM .or. frame%magic /= FRAME_MAGIC) then
      plasma_ok = 0; return
    end if
    call c_f_pointer(frame%frame_ptr, frame_arr, [r, d, d])
    tol = 100.0_dp * epsilon(0.0_dp)

    ! Hermitian check
    herm_ok = .true.
    do i = 1, r
      if (.not. sov_is_hermitian_matrix(frame_arr(i,:,:), d)) then
        herm_ok = .false.; exit
      end if
    end do

    ! Orthogonality: tr(pα΅’ pβ±Ό) = Ξ΄α΅’β±Ό
    ortho_ok = .true.
    outer: do i = 1, r
      do j = 1, r
        tij = czero
        do k = 1, d
          do l = 1, d
            tij = tij + frame_arr(i,k,l) * frame_arr(j,l,k)
          end do
        end do
        trace_ij = real(tij)
        if (i == j) then
          if (abs(trace_ij - 1.0_dp) > tol) then; ortho_ok = .false.; exit outer; end if
        else
          if (abs(trace_ij) > tol) then; ortho_ok = .false.; exit outer; end if
        end if
      end do
    end do outer

    ! Tight: Ξ£ pα΅’ = I
    tight_ok = .true.
    do j = 1, d
      do k = 1, d
        s = czero
        do i = 1, r; s = s + frame_arr(i,j,k); end do
        if (j == k) then
          if (abs(real(s) - 1.0_dp) > tol .or. abs(aimag(s)) > tol) then
            tight_ok = .false.
          end if
        else
          if (abs(s) > tol) tight_ok = .false.
        end if
      end do
    end do

    ! Idempotency: pα΅’Β² = pα΅’
    idemp_ok = .true.
    allocate(p_sq(d,d))
    do i = 1, r
      p_sq = matmul(frame_arr(i,:,:), frame_arr(i,:,:))
      frob_diff = 0.0_dp
      do j = 1, d; do k = 1, d
        frob_diff = frob_diff + abs(p_sq(j,k) - frame_arr(i,j,k))**2
      end do; end do
      if (sqrt(frob_diff) > tol * d) then; idemp_ok = .false.; exit; end if
    end do
    deallocate(p_sq)

    plasma_ok = 0
    if (herm_ok)  plasma_ok = plasma_ok + 1
    if (ortho_ok) plasma_ok = plasma_ok + 2
    if (tight_ok) plasma_ok = plasma_ok + 4
    if (idemp_ok) plasma_ok = plasma_ok + 8
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! 5. SPE FRAME INFO β€” stub (caller fills JSON from spe_frame_t fields)
  !═══════════════════════════════════════════════════════════════════
  subroutine spe_frame_info(frame, info_ptr) &
       bind(C, name="spe_frame_info")
    type(spe_frame_t), intent(in)  :: frame
    type(c_ptr),       intent(out) :: info_ptr
    info_ptr = c_null_ptr
  end subroutine

end module spe_encoder