
    `gj              	       F   d Z ddlZddlZddlZddlZ	 ddlZdZ ej                  e
      Zdej                  z  ZddZdded	edd
fdZddZd dZd!dZdd
dd
defdZdded	edd
fdZddedee   d	edd
fdZdd
defdZdedd
fdZd	ededefdZy# e$ r dZY w xY w)"u  Holographic Reduced Representations (HRR) with phase encoding.

HRRs are a vector symbolic architecture for encoding compositional structure
into fixed-width distributed representations. This module uses *phase vectors*:
each concept is a vector of angles in [0, 2π). The algebraic operations are:

  bind   — circular convolution (phase addition)  — associates two concepts
  unbind — circular correlation (phase subtraction) — retrieves a bound value
  bundle — superposition (circular mean)           — merges multiple concepts

Phase encoding is numerically stable, avoids the magnitude collapse of
traditional complex-number HRRs, and maps cleanly to cosine similarity.

Atoms are generated deterministically from SHA-256 so representations are
identical across processes, machines, and language versions.

References:
  Plate (1995) — Holographic Reduced Representations
  Gayler (2004) — Vector Symbolic Architectures answer Jackendoff's challenges
    NTF       @returnc                  &    t         st        d      y )Nz,numpy is required for holographic operations)
_HAS_NUMPYRuntimeError     Y/root/.hermes/venv/lib/python3.12/site-packages/plugins/memory/holographic/holographic.py_require_numpyr   &   s    IJJ r	   worddim
np.ndarrayc                    t                d}t        j                  ||z        }g }t        |      D ]]  }t	        j
                  |  d| j                               j                         }|j                  t        j                  d|             _ t        j                  |d| t        j                        t        dz  z  }|S )u  Deterministic phase vector via SHA-256 counter blocks.

    Uses hashlib (not numpy RNG) for cross-platform reproducibility.

    Algorithm:
    - Generate enough SHA-256 blocks by hashing f"{word}:{i}" for i=0,1,2,...
    - Concatenate digests, interpret as uint16 values via struct.unpack
    - Scale to [0, 2π): phases = values * (2π / 65536)
    - Truncate to dim elements
    - Returns np.float64 array of shape (dim,)
       :z<16HNdtypeg      @)r   mathceilrangehashlibsha256encodedigestextendstructunpacknparrayfloat64_TWO_PI)r   r   values_per_blockblocks_neededuint16_valuesir   phasess           r
   encode_atomr'   +   s      IIc$445M!M=! <4&! 4 4 67>>@V]]66:;< XXmDS)<'@QRFMr	   abc                 .    t                | |z   t        z  S )zCircular convolution = element-wise phase addition.

    Binding associates two concepts into a single composite vector.
    The result is dissimilar to both inputs (quasi-orthogonal).
    r   r!   r(   r)   s     r
   bindr-   F   s     EWr	   c                 .    t                | |z
  t        z  S )u   Circular correlation = element-wise phase subtraction.

    Unbinding retrieves the value associated with a key from a memory vector.
    unbind(bind(a, b), a) ≈ b  (up to superposition noise)
    r+   )memorykeys     r
   unbindr1   P   s     SLG##r	   c            	          t                t        j                  | D cg c]  }t        j                  d|z         c}d      }t        j                  |      t
        z  S c c}w )zSuperposition via circular mean of complex exponentials.

    Bundling merges multiple vectors into one that is similar to each input.
    The result can hold O(sqrt(dim)) items before similarity degrades.
    y              ?r   )axis)r   r   sumexpangler!   )vectorsvcomplex_sums      r
   bundler:   Z   sJ     &&':Q"&&a.:CK88K 7** ;s   A"c                 ~    t                t        t        j                  t        j                  | |z
                    S )zPhase cosine similarity. Range [-1, 1].

    Returns 1.0 for identical vectors, near 0.0 for random (unrelated) vectors,
    and -1.0 for perfectly anti-correlated vectors.
    )r   floatr   meancosr,   s     r
   
similarityr?   e   s*     A'((r	   textc                 *   t                | j                         j                         D cg c]  }|j                  d       }}|D cg c]  }|s|	 }}|st	        d|      S |D cg c]  }t	        ||       }}t        | S c c}w c c}w c c}w )a7  Bag-of-words: bundle of atom vectors for each token.

    Tokenizes by lowercasing, splitting on whitespace, and stripping
    leading/trailing punctuation from each token.

    Returns bundle of all token atom vectors.
    If text is empty or produces no tokens, returns encode_atom("__hrr_empty__", dim).
    z.,!?;:"'()[]{}__hrr_empty__)r   lowersplitstripr'   r:   )r@   r   tokentokenstatom_vectorss         r
   encode_textrJ   o   s      ZZ\'') 	%&F   %A1a%F%?C009?@Ks+@L@<   &
 As   B	BB)Bcontententitiesc           	          t                t        d|      }t        d|      }t        t        | |      |      g}|D ]5  }|j	                  t        t        |j                         |      |             7 t        | S )u  Structured encoding: content bound to ROLE_CONTENT, each entity bound to ROLE_ENTITY, all bundled.

    Role vectors are reserved atoms: "__hrr_role_content__", "__hrr_role_entity__"

    Components:
    1. bind(encode_text(content, dim), encode_atom("__hrr_role_content__", dim))
    2. For each entity: bind(encode_atom(entity.lower(), dim), encode_atom("__hrr_role_entity__", dim))
    3. bundle all components together

    This enables algebraic extraction:
        unbind(fact, bind(entity, ROLE_ENTITY)) ≈ content_vector
    __hrr_role_content____hrr_role_entity__)r   r'   r-   rJ   appendrC   r:   )rK   rL   r   role_contentrole_entity
componentsentitys          r
   encode_factrU      s     5s;L3S9K 	[#&5$J  O${6<<>3?MNO :r	   r&   c                 6    t                | j                         S )uF   Serialize phase vector to bytes. float64 tobytes — 8 KB at dim=1024.)r   tobytes)r&   s    r
   phases_to_bytesrX      s    >>r	   datac                 |    t                t        j                  | t        j                        j	                         S )zDeserialize bytes back to phase vector. Inverse of phases_to_bytes.

    The .copy() call is required because frombuffer returns a read-only view
    backed by the bytes object; callers expect a mutable array.
    r   )r   r   
frombufferr    copy)rY   s    r
   bytes_to_phasesr]      s(     ==RZZ05577r	   n_itemsc                     t                |dk  rt        d      S t        j                  | |z        }|dk  rt        j                  d|| |       |S )a  Signal-to-noise ratio estimate for holographic storage.

    SNR = sqrt(dim / n_items) when n_items > 0, else inf.

    The SNR falls below 2.0 when n_items > dim / 4, meaning retrieval
    errors become likely. Logs a warning when this threshold is crossed.
    r   infr   zHRR storage near capacity: SNR=%.2f (dim=%d, n_items=%d). Retrieval accuracy may degrade. Consider increasing dim or reducing stored items.)r   r<   r   sqrtloggerwarning)r   r^   snrs      r
   snr_estimatere      sV     !|U|
))C'M
"C
Sy`	
 Jr	   )r   N)i   )r(   r   r)   r   r   r   )r/   r   r0   r   r   r   )r7   r   r   r   )__doc__r   loggingr   r   numpyr   r   ImportError	getLogger__name__rb   pir!   r   strintr'   r-   r1   r:   r<   r?   rJ   listrU   bytesrX   r]   re   r   r	   r
   <module>rq      s%  *    J 
		8	$
-K
c  | 6$+), )< )E )!c ! !| !0 S	  | 8L U 8% 8L 8c C E k  Js   B B B 