File size: 16,188 Bytes
9425aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
!=====================================================================
! MEASUREMENT HEAD β€” Born Rule on the Jordan Symmetric Cone
!
! The output layer. No softmax over vocab. No unembedding matrix.
! Pure spectral measurement: project ρ onto idempotents, read eigenvalues.
!
! Born rule:  p_j = tr(q_j ∘ ρ) = tr(q_j ρ)  (q_j Hermitian projector)
! Reconstruction:  xΜ‚ = Ξ£_j p_j ψ_j            (inverse spectral synthesis)
!
! APL glyph map:
!   tr(q_j ρ)     ≑  +/ (q_j Γ— ρ)     β€” reduce + over elementwise Γ—
!   Ξ£_j p_j ψ_j  ≑  p +.Γ— ψ           β€” inner product +.Γ—
!   p ∈ Ξ”^{m-1}  ≑  (+/p) = 1          β€” reduce + equals 1
!   argmax p      ≑  ⍒p               β€” grade down ⍒
!   sample p      ≑  p ⌸ ⍳m            β€” key ⌸ over index ⍳
!   entropy       ≑  -+/(p Γ— ⍟p)       β€” reduce + of p Γ— log p
!
! Liquid Haskell:
!   {-@ type Projector d = {q : M d d β„‚ | hermitian q ∧ qΒ·q = q ∧ tr q = 1} @-}
!   {-@ type Simplex  m  = {p : Vec m ℝ  | βˆ€i. p!i β‰₯ 0 ∧ sum p = 1}         @-}
!   {-@ born_rule  :: Vec m (Projector d) β†’ Density d β†’ Simplex m            @-}
!   {-@ reconstruct :: Simplex m β†’ Frame m d β†’ Signal d                       @-}
!
! Fibonacci temperature schedule:
!   Ο„_k = φ⁻ᡏ  (temperature decays by golden ratio each annealing step)
!   p_j(Ο„) = exp(tr(q_j ρ)/Ο„) / Ξ£ exp(tr(q_k ρ)/Ο„)
!   Ο„β†’0: argmax  (mode collapse to sharpest eigenvalue)
!   Ο„β†’βˆž: uniform (maximum entropy, pure spectral democracy)
!
! Audit Spec: 4b565498-9afc-4782-af4a-c6b11a5d0058
!=====================================================================
module measurement_head
  use, intrinsic :: iso_c_binding, only: c_int64_t, c_ptr, c_f_pointer, &
       c_size_t, c_loc, c_char, c_associated
  use, intrinsic :: iso_fortran_env, only: int64, real64, int8
  use sov_monster_kernel, only: dp, czero, &
       sov_blake3_hash_matrix, sov_bifrost_sign, &
       sov_is_hermitian_matrix, sov_is_density_matrix, sov_fault, i8
  use sov_knowledge, only: knowledge_tau, ensure_sovereign_kb, sovereign_kb, &
       knowledge_chunk
  implicit none
  private

  public :: born_rule
  public :: born_rule_temperature
  public :: born_rule_knowledge
  public :: reconstruct
  public :: entropy
  public :: argmax_spectral
  public :: sample_spectral
  public :: fib_anneal

  real(dp), parameter :: PHI_INV = 0.6180339887498948482_dp
  real(dp), parameter :: LOG2    = 0.6931471805599453094_dp

contains

  !═══════════════════════════════════════════════════════════════════
  ! born_rule β€” p_j = tr(q_j ρ)  (zero temperature: exact projection)
  !
  ! {-@ born_rule :: {m:Int | m>0} β†’ {d:Int | d>0}
  !               β†’ Vec m (Projector d) β†’ Density d
  !               β†’ Simplex m                                       @-}
  !
  ! APL:  p ← +/ (q_j Γ— ρ)   for each j    β€” inner +.Γ— across dΓ—d
  !       assert (+/p) = 1                  β€” reduce + equals 1
  !═══════════════════════════════════════════════════════════════════
  subroutine born_rule(q_ptr, rho_ptr, m, d, p_ptr, plasma_ok) &
       bind(C, name="born_rule")
    type(c_ptr),        intent(in),  value :: q_ptr, rho_ptr, p_ptr
    integer(c_int64_t), intent(in),  value :: m, d
    integer(c_int64_t), intent(out)        :: plasma_ok

    complex(dp), pointer :: q(:,:,:), rho(:,:)
    real(dp),    pointer :: p(:)
    integer(c_int64_t) :: j, k, l
    real(dp) :: p_sum, s

    call c_f_pointer(q_ptr,   q,   [m, d, d])
    call c_f_pointer(rho_ptr, rho, [d, d])
    call c_f_pointer(p_ptr,   p,   [m])

    ! {-@ assert density rho @-}
    if (.not. sov_is_density_matrix(rho, d)) call sov_fault(801)

    ! APL:  p_j ← +/ (q_j Γ— ρ)    β€” tr(q_j ρ) = Ξ£_{kl} (q_j)_{kl} ρ_{lk}
    !$omp parallel do default(none) shared(p,q,rho,m,d) private(j,k,l)
    do j = 1, m
      s = 0.0_dp
      do k = 1, d
        do l = 1, d
          ! tr(q_j ρ) = Σ_k (q_j ρ)_{kk} = Σ_{kl} q_j(k,l) ρ(l,k)
          s = s + real(q(j,k,l) * rho(l,k))
        end do
      end do
      p(j) = max(s, 0.0_dp)   ! Born probabilities β‰₯ 0
    end do
    !$omp end parallel do

    ! APL:  assert (+/p) = 1    β€” normalize (should already be ~1 for tight frame)
    p_sum = sum(p)
    if (p_sum < epsilon(0.0_dp)) call sov_fault(802)
    p = p / p_sum

    plasma_ok = 1
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! born_rule_temperature β€” softmax Born rule at temperature Ο„
  !
  ! {-@ born_rule_temperature :: Ο„:Float β†’ Vec m (Projector d)
  !                           β†’ Density d β†’ Simplex m              @-}
  !
  ! APL:  raw_j ← tr(q_j ρ)                  β€” exact Born
  !       p_j   ← ⍟ raw_j Γ· Ο„               β€” divide by temperature
  !       p     ← *p Γ· +/*p                  β€” softmax: exp Γ· sum exp
  !       Ο„β†’0: argmax  Ο„β†’βˆž: uniform
  !═══════════════════════════════════════════════════════════════════
  subroutine born_rule_temperature(q_ptr, rho_ptr, m, d, tau, p_ptr, plasma_ok) &
       bind(C, name="born_rule_temperature")
    type(c_ptr),        intent(in),  value :: q_ptr, rho_ptr, p_ptr
    integer(c_int64_t), intent(in),  value :: m, d
    real(dp),           intent(in),  value :: tau
    integer(c_int64_t), intent(out)        :: plasma_ok

    complex(dp), pointer :: q(:,:,:), rho(:,:)
    real(dp),    pointer :: p(:)
    real(dp),    allocatable :: raw(:)
    integer(c_int64_t) :: j, k, l
    real(dp) :: max_raw, s, acc

    call c_f_pointer(q_ptr,   q,   [m, d, d])
    call c_f_pointer(rho_ptr, rho, [d, d])
    call c_f_pointer(p_ptr,   p,   [m])

    if (tau <= 0.0_dp) call sov_fault(803)
    if (.not. sov_is_density_matrix(rho, d)) call sov_fault(804)

    allocate(raw(m))

    ! APL:  raw ← {tr(q_j ρ)}_j    β€” exact Born projections
    !$omp parallel do default(none) shared(raw,q,rho,m,d) private(j,k,l)
    do j = 1, m
      acc = 0.0_dp
      do k = 1, d; do l = 1, d
        acc = acc + real(q(j,k,l) * rho(l,k))
      end do; end do
      raw(j) = acc
    end do
    !$omp end parallel do

    ! APL:  p ← *((raw - ⌈/raw) Γ· Ο„)   β€” numerically stable softmax
    !       ⌈/ = max reduction
    max_raw = maxval(raw)
    s = 0.0_dp
    do j = 1, m
      p(j) = exp((raw(j) - max_raw) / tau)
      s = s + p(j)
    end do
    p = p / s

    plasma_ok = 1
    deallocate(raw)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! born_rule_knowledge β€” Born rule with sovereign knowledge annealing
  !
  ! SOVEREIGN KNOWLEDGE INJECTION (before output signing):
  !   1. Query KB for measurement context
  !   2. Ο„_k = Ο„β‚€ Β· φ⁻ⁿ  where n = # verified context chunks
  !   3. Softmax Born at knowledge-derived temperature
  !
  ! No softmax inversion. No external vector DB. WORM-attested only.
  !═══════════════════════════════════════════════════════════════════
  subroutine born_rule_knowledge(q_ptr, rho_ptr, m, d, tau_0, &
       context_ptr, context_len, p_ptr, plasma_ok) &
       bind(C, name="born_rule_knowledge")
    type(c_ptr),        intent(in),  value :: q_ptr, rho_ptr, p_ptr, context_ptr
    integer(c_int64_t), intent(in),  value :: m, d, context_len
    real(dp),           intent(in),  value :: tau_0
    integer(c_int64_t), intent(out)        :: plasma_ok

    type(knowledge_chunk), allocatable :: context_chunks(:)
    character(len=:), allocatable :: context
    character(kind=c_char), pointer :: cbuf(:)
    integer :: i, n_hits, nctx
    real(dp) :: tau_k
    integer :: n_verified

    call ensure_sovereign_kb()

    nctx = max(0, int(context_len))
    if (nctx > 0 .and. c_associated(context_ptr)) then
      call c_f_pointer(context_ptr, cbuf, [nctx])
      allocate(character(len=nctx) :: context)
      do i = 1, nctx
        context(i:i) = transfer(cbuf(i), ' ')
      end do
      call sovereign_kb%search(context, 5, context_chunks, n_hits)
    else
      n_hits = 0
    end if

    n_verified = 0
    if (allocated(context_chunks)) then
      do i = 1, size(context_chunks)
        if (context_chunks(i)%is_verified) n_verified = n_verified + 1
      end do
    end if

    tau_k = knowledge_tau(tau_0, n_verified)
    call born_rule_temperature(q_ptr, rho_ptr, m, d, tau_k, p_ptr, plasma_ok)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! reconstruct β€” xΜ‚ = Ξ£_j p_j ψ_j  (inverse spectral synthesis)
  !
  ! {-@ reconstruct :: Simplex m β†’ Frame m d β†’ Signal d            @-}
  !
  ! APL:  xΜ‚ ← p +.Γ— ψ    β€” inner product: weights dotted into frame
  !       This is the EXACT inverse of SPE encode when frame is tight
  !═══════════════════════════════════════════════════════════════════
  subroutine reconstruct(p_ptr, psi_ptr, m, d, signal_ptr) &
       bind(C, name="reconstruct")
    type(c_ptr),        intent(in),  value :: p_ptr, psi_ptr, signal_ptr
    integer(c_int64_t), intent(in),  value :: m, d

    real(dp),    pointer :: p(:)
    complex(dp), pointer :: psi(:,:,:), signal(:,:)
    integer(c_int64_t) :: j, k, l
    complex(dp) :: s

    call c_f_pointer(p_ptr,      p,      [m])
    call c_f_pointer(psi_ptr,    psi,    [m, d, d])
    call c_f_pointer(signal_ptr, signal, [d, d])

    ! APL:  xΜ‚ ← p +.Γ— ψ    β€” Ξ£_j p_j Β· ψ_j(k,l)
    signal = czero
    !$omp parallel do collapse(2) default(none) shared(signal,p,psi,m,d) private(j,k,l)
    do k = 1, d
      do l = 1, d
        s = czero
        do j = 1, m; s = s + p(j) * psi(j,k,l); end do
        signal(k,l) = s
      end do
    end do
    !$omp end parallel do
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! entropy β€” von Neumann / Shannon entropy of measurement distribution
  !
  ! {-@ entropy :: Simplex m β†’ {e : Float | e β‰₯ 0}                 @-}
  !
  ! APL:  H ← - +/ (p Γ— ⍟p)    β€” reduce + of p Γ— log p
  !       H = 0: pure state (one eigenvalue dominates)
  !       H = log m: maximally mixed (all eigenvalues equal 1/m)
  !═══════════════════════════════════════════════════════════════════
  function entropy(p_ptr, m) result(H) &
       bind(C, name="spectral_entropy")
    type(c_ptr),        intent(in), value :: p_ptr
    integer(c_int64_t), intent(in), value :: m
    real(dp) :: H

    real(dp), pointer :: p(:)
    integer(c_int64_t) :: j

    call c_f_pointer(p_ptr, p, [m])

    ! APL:  H ← - +/ (p Γ— ⍟p)
    H = 0.0_dp
    do j = 1, m
      if (p(j) > epsilon(0.0_dp)) then
        H = H - p(j) * log(p(j))
      end if
    end do
    ! Normalize to [0,1]: divide by log(m)  (APL: H ÷ ⍟m)
    if (m > 1) H = H / log(real(m, dp))
  end function

  !═══════════════════════════════════════════════════════════════════
  ! argmax_spectral β€” ⍒p: grade down (index of maximum eigenvalue)
  !
  ! {-@ argmax_spectral :: Simplex m β†’ {i : Int | 0 ≀ i < m}      @-}
  !
  ! APL:  βŠƒβ’p    β€” first of grade-down = argmax
  !═══════════════════════════════════════════════════════════════════
  function argmax_spectral(p_ptr, m) result(idx) &
       bind(C, name="argmax_spectral")
    type(c_ptr),        intent(in), value :: p_ptr
    integer(c_int64_t), intent(in), value :: m
    integer(c_int64_t) :: idx

    real(dp),    pointer :: p(:)
    real(dp)             :: max_val
    integer(c_int64_t)   :: j

    call c_f_pointer(p_ptr, p, [m])

    ! APL:  βŠƒβ’p    β€” index of maximum (1-based β†’ 0-based for C ABI)
    idx = 0; max_val = -huge(0.0_dp)
    do j = 1, m
      if (p(j) > max_val) then; max_val = p(j); idx = j - 1; end if
    end do
  end function

  !═══════════════════════════════════════════════════════════════════
  ! sample_spectral β€” p ⌸ ⍳m: sample index from Born distribution
  !
  ! {-@ sample_spectral :: Simplex m β†’ Uniform01 β†’ {i : Int | 0 ≀ i < m} @-}
  !
  ! APL:  (p ⌸ ⍳m) u    β€” key ⌸: partition ⍳m by cumulative p, pick bucket u
  !       Uses quantum entropy seed u ∈ [0,1) (passed from ANU QRNG)
  !═══════════════════════════════════════════════════════════════════
  function sample_spectral(p_ptr, m, u) result(idx) &
       bind(C, name="sample_spectral")
    type(c_ptr),        intent(in), value :: p_ptr
    integer(c_int64_t), intent(in), value :: m
    real(dp),           intent(in), value :: u    ! ∈ [0,1) from QRNG
    integer(c_int64_t) :: idx

    real(dp), pointer :: p(:)
    real(dp)          :: cdf
    integer(c_int64_t) :: j

    call c_f_pointer(p_ptr, p, [m])

    ! APL:  p ⌸ ⍳m    β€” cumulative sum (APL +\p), find first bucket β‰₯ u
    idx = m - 1   ! default: last bucket
    cdf = 0.0_dp
    do j = 1, m
      cdf = cdf + p(j)
      if (u < cdf) then; idx = j - 1; exit; end if
    end do
  end function

  !═══════════════════════════════════════════════════════════════════
  ! fib_anneal β€” Fibonacci temperature schedule for annealing inference
  !
  ! {-@ fib_anneal :: {k:Int | kβ‰₯0} β†’ {Ο„:Float | Ο„ > 0}           @-}
  !
  ! APL:  Ο„_k ← φ⁻ᡏ Γ— Ο„_0    β€” φ⁻¹ contraction each step
  !       k=0: Ο„_0 (hot, explores)
  !       kβ†’βˆž: 0   (cold, argmax)
  !       Converges at Fibonacci rate: exactly the Banach rate of jordan_block
  !═══════════════════════════════════════════════════════════════════
  function fib_anneal(tau_0, k) result(tau_k) &
       bind(C, name="fib_anneal")
    real(dp),           intent(in), value :: tau_0
    integer(c_int64_t), intent(in), value :: k
    real(dp) :: tau_k

    ! APL:  Ο„_k ← Ο„_0 Γ— φ⁻ᡏ   β€” power of golden ratio inverse
    tau_k = tau_0 * PHI_INV**k
    tau_k = max(tau_k, 1.0e-12_dp)  ! Never exactly zero
  end function

end module measurement_head