
    XiU                         d dl Zd dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZ d dlmZmZ d dlZe G d d             Ze G d d             Ze G d	 d
             Z G d d      Zy)    N)entropy)ListDictTupleOptionalCallable)	dataclassfieldc                       e Zd ZU dZeed<   eej                  gej                  f   ed<   dZ	e
ed<   dZe
ed<   dZeed<   d	Zeed
<    ee      Zeed<   d Zy)FunctionGatez6Represents a single function gate in the superpositiongate_idfunction        weightcollapse_potentialr   ageTactive)default_factorymetadatac                 >    d| j                    d| j                  ddS )NzGate(z, w=.4f))r   r   selfs    X/home/per/Documents/human logic for functions over floats/CCT_ODE_TIME_SERIES_FITTING.py__str__zFunctionGate.__str__   s"    t||nDS(9;;    N)__name__
__module____qualname____doc__str__annotations__r   npndarrayr   floatr   r   intr   boolr
   dictr   r   r    r   r   r   r      s`    @L

|RZZ/00FE ##CLFD40Hd0<r   r   c                   x    e Zd ZU dZeeeef      ed<   de	j                  deeef   de	j                  fdZd Zy)	Circuitz4Represents a circuit (combination of multiple gates)gatesXgate_registryreturnc                     t        j                  t        |            }| j                  D ]$  \  }}||v s||||   j	                  |      z  z  }& |S )zHEvaluate the circuit by combining gate outputs weighted by their weights)r$   zeroslenr-   r   )r   r.   r/   resultr   r   s         r   evaluatezCircuit.evaluate   s[    #a&!#zz 	FOGV-'&=#9#B#B1#EEE	F r   c                     | j                   D cg c]  \  }}| d|dd }}}dt        | j                          ddj                  |       S c c}}w )N(r   r   zCircuit[z]: z + )r-   r3   join)r   r   wpartss       r   r   zCircuit.__str__'   sX    9=D:7AG9AaWA&DD#djj/*#ejj.?-@AA Es   AN)r   r   r    r!   r   r   r"   r&   r#   r$   r%   r   r   r5   r   r*   r   r   r,   r,      sN    >c5j!"""** T#|:K5L QSQ[Q[ Br   r,   c                       e Zd ZU dZeed<   eed<   eed<   eed<   eed<   eed<   eed<   eed	<   eed
<   eed<   eed<   eed<   eed<   e	e   ed<   e	e
j                     ed<   y)FittingResultz0Stores results from semantic function regressionstatus	best_gatebest_circuit
confidencefinal_entropyr2_score
r2_circuitmsemse_circuit
iterationsgates_evaluatedgates_activecircuit_sizeentropy_trajectoryweight_historyN)r   r   r    r!   r"   r#   r,   r&   r'   r   r$   r%   r*   r   r   r<   r<   +   sg    :KNO	JOU#$$r   r<   c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d/dededededededed	ed
edefdZd Z	 d0de	de
ej                  gej                  f   defdZd1dedefdZdej                  dej                  dedefdZdej                  dej                  ddfdZdefdZdedefdZdedej                  dej                  fdZdedefdZ	 	 d2dej                  dej                  d ed!edef
d"Z	 	 d3dej                  d#e	d$edej                  fd%Zd& Zd4d'efd(Zd5d)ej                  d*ej                  fd+Zd, Zd- Zdefd.Zy)6SemanticFunctionRegressoru  
    🛸 CCT-ODE Semantic Function Regressor
    
    Fits time series data to a superposition of function gates
    using Conditional Collapse Theory dynamics.
    
    Key Features:
    - Maintains probability distribution over function space
    - Uses replicator ODE for weight evolution
    - Entropy-gated memory pruning
    - Symbolic function discovery
    - ODE-CCT periodicity detection
    alphaentropy_thresholdprune_thresholdmax_active_gates
decay_rate	gain_ratemutation_raterI   periodicity_detectionverbosec                 p   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        g | _
        g | _        g | _        g | _        t        j                  g       | _        g | _        d| _        d| _        d| _        d| _        d| _        | j/                          y)ap  
        Args:
            alpha: Learning rate for replicator ODE
            entropy_threshold: Target entropy for collapse
            prune_threshold: Weight below which gates are pruned
            max_active_gates: Maximum gates to keep active
            decay_rate: Weight decay for unused gates
            gain_rate: Weight gain from collapse potential
            mutation_rate: Rate of symbolic mutation for new gates
            circuit_size: Number of gates to include in best circuit
            periodicity_detection: Enable ODE-CCT cycle detection
            verbose: Print progress during fitting
        NF)rN   epsilonprune_thresh	MAX_GATESrR   rS   rT   rI   detect_periodicityrV   r-   active_indicesentropy_historyrK   r$   arraycollapse_potentialsstate_hashesperiod_detectedperiod_start_iterfittedX_trainy_train_initialize_gate_library)r   rN   rO   rP   rQ   rR   rS   rT   rI   rU   rV   s              r   __init__z"SemanticFunctionRegressor.__init__U   s    0 
(+)$"*("7 *,
)+ -/02/1xx|  (*.204 -1-1 	%%'r   c           
         g | _         | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        d	d
 dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd dddd             | j                   j                  t        dd  dd!dd             | j                   j                  t        d"d# dd!dd             | j                   j                  t        d$d% dd$dd             | j                   j                  t        d&d' dd$dd             | j                   j                  t        d(d) dd(dd             | j                   j                  t        d*d+ dd*d,d             | j                   j                  t        d-d. dd*d,d             | j                   j                  t        d/d0 dd/dd             | j                   j                  t        d1d2 dd3dd             | j                   j                  t        d4d5 dd6dd             | j                   j                  t        d7d8 dd9dd             t        t	        t        | j                                     | _        y:);z2Initialize standard function gates for time serieslinearc                     | S Nr*   xs    r   <lambda>zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    q r   皙?   type
complexityr   r   r   r   linear_offsetc                     | dz   S N      ?r*   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s
    q3w r   	quadraticc                     | dz  S N   r*   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   
    qAv r   
polynomialr|   cubicc                     | dz  S )N   r*   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   r}   r   r   sinec                 T    t        j                  dt         j                  z  | z        S r{   r$   sinpirl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>       rvva"%%i!m4 r   periodiccosinec                 T    t        j                  dt         j                  z  | z        S r{   )r$   cosr   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   r   r   	sine_halfc                 N    t        j                  t         j                  | z        S rk   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rvvbeeai0 r   expc                 2    t        j                  | dz
        S Nrp   r$   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rvva!e} r   exponential	exp_decayc                 .    t        j                  |        S rk   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rvvqbz r   logc                 X    t        j                  t        j                  |       dz         S )N皙?)r$   r   absrl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rvvbffQi#o6 r   logarithmicsin_expc                 `    t        j                  |       t        j                  |  dz        z  S )N   )r$   r   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s!    rvvay2661"q&>9 r   	compositepoly_sinc                 Z    | t        j                  dt         j                  z  | z        z  S r{   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s     q266!bee)a-#88 r   sigmoidc                 D    ddt        j                  d| dz
  z        z   z  S )Nrp   rx   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s!    qArQW~(>$>? r   tanhc                 8    t        j                  d| dz
  z        S )Nr   rx   )r$   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rwwqAG}5 r   stepc                 2    | dkD  j                  t              S rw   )astyper&   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>  s    C//6 r   constantc                 2    t        j                  |       dz  S rw   )r$   	ones_likerl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>
  s    r||A4 r   r   zeroc                 ,    t        j                  |       S rk   )r$   
zeros_likerl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>  s    r}}Q/ r   gaussianc                 @    t        j                  | dz
  dz   dz        S )Nrx   r|   r   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>  s    rvvSQ&7#&=> r   r   c                 2    t        j                  | dz
        S rw   r$   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>   s    rvva#g r   	piecewisesqrtc                 R    t        j                  t        j                  |             S rk   )r$   r   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>'  s    rwwrvvay1 r   radicalinvc                 8    dt        j                  |       dz   z  S )Nrp   r   r   rl   s    r   rn   zDSemanticFunctionRegressor._initialize_gate_library.<locals>.<lambda>.  s    qBFF1IO4 r   rationalN)r-   appendr   listranger3   r\   r   s    r   rf   z2SemanticFunctionRegressor._initialize_gate_library   s   
 	

, &a8	
 	 	

,#&&a8	
 	 	

,%*!<	
 	 	

,%*!<	
 	 	

,4(:	
 	 	

,4(:	
 	 	

,0(:	
 	 	

,,+1=	
 	 	

,)+1=	
 	 	

,6+1=	
 	 	

,9);	
 	 	

,8);	
 	 	

,?'q9	
 	 	

,5'q9	
 	 	

,6$A6	
 	 	

,4(:	
 	 	

,/(:	
 	 	

,>(:	
 	 	

,.);	
 	 	

,1'q9	
 	 	

,4(:	
 	 #5TZZ#9:r   r   r   rs   c                     t        ||dt        | j                        dz   z  d|d      }| j                  j                  |       | j                  j                  t        | j                        dz
         y)z/Add a custom function gate to the superposition      ?rp   customrq   rt   N)r   r3   r-   r   r\   )r   r   r   rs   gates        r   add_custom_gatez)SemanticFunctionRegressor.add_custom_gate6  sf    
 #djj/A-.&jA	
 	

$""3tzz?Q#67r   Ntop_kr0   c                     | j                   } j                  st        g       S t         j                   fdd      }|d| }t	         fd|D              }|dkD  rC|D cg c]7  } j
                  |   j                   j
                  |   j                  |z  f9 }}n4|D cg c])  } j
                  |   j                  dt        |      z  f+ }}t        |      S c c}w c c}w )	z
        Get the best circuit (combination of top K gates by weight)
        
        Args:
            top_k: Number of gates to include (defaults to self.circuit_size)
        
        Returns:
            Circuit object with top K gates
        Nr-   c                 6    j                   |    j                  S rk   r-   r   rm   r   s    r   rn   z<SemanticFunctionRegressor.get_best_circuit.<locals>.<lambda>[  s    $**Q-.. r   Tkeyreversec              3   P   K   | ]  }j                   |   j                    y wrk   r   ).0idxr   s     r   	<genexpr>z=SemanticFunctionRegressor.get_best_circuit.<locals>.<genexpr>c  s     Gc4::c?11G   #&r   r   )	rI   r\   r,   sortedsumr-   r   r   r3   )r   r   sorted_gates	top_gatestotal_weightr   circuit_gatess   `      r   get_best_circuitz*SemanticFunctionRegressor.get_best_circuitH  s    =%%E""$$ .
 !%(	 GYGG! % C(($**S/*@*@<*OPM  % C((#I*>?M 
 ]++
s   %<C$(.C)r.   ygate_idxc                 >   |t        | j                        k\  ry| j                  |   }	 |j                  |      }t        j                  |ddd      }t        j
                  |dd      }t        j                  ||z
  dz        }| S # t        $ r
}Y d}~yd}~ww xY w)us   
        Calculate collapse potential Δ_f for a function gate.
        Higher = better fit (negative MSE)
        g    _r   g    _B)nanposinfneginfr|   N)r3   r-   r   r$   
nan_to_numclipmean	Exception)r   r.   r   r   r   y_predrD   es           r   calculate_collapse_potentialz6SemanticFunctionRegressor.calculate_collapse_potentialq  s     s4::&zz(#
	]]1%F]]6s4NFWWVUD1F ''6A:!+,C4K 		s   AB	 		BBc                     t         j                        dk(  ryt        j                  t         j                              } j                  D ]  } j                  |||      ||<    | _        t        j                   j                  D cg c]  } j                  |   j                   c}      }| j                     }t        j                  ||z        } j                  |z  ||z
  z  }	t         j                        D ]A  \  }} j                  |   xj                  |	|   z  c_        ||    j                  |   _        C t         fd j                  D              }
|
dkD  r3 j                  D ]$  } j                  |   xj                  |
z  c_        &  j                  D ]B  }t        j                   j                  |   j                  dd       j                  |   _        D yc c}w )uy   
        CCT Replicator ODE: dp/dt = α·p·(Δ - Δ̄)
        Updates gate weights based on collapse potential
        r   Nc              3   P   K   | ]  }j                   |   j                    y wrk   r   r   ir   s     r   r   z>SemanticFunctionRegressor.replicator_update.<locals>.<genexpr>  s     MA4::a=//Mr   绽|=r   )r3   r\   r$   r2   r-   r   r_   r^   r   r   rN   	enumerater   r   )r   r.   r   deltasr   r   active_weightsactive_deltas	avg_deltadpr   s   `          r   replicator_updatez+SemanticFunctionRegressor.replicator_update  s   
 t""#q( #djj/*&& 	GC;;Aq#FF3K	G $*  ATAT"UA4::a=#7#7"UVt223 FF>M9:	 ZZ.(MI,EF   3 34 	=FAsJJsO""be+"17DJJsO.	=
 M9L9LMM!** 7

3&&,6&7 && 	QC%'WWTZZ_-C-CUC%PDJJsO"	Q+ #Vs    G2c                 >   t        | j                        dk(  ryt        j                  | j                  D cg c]  }| j                  |   j
                   c}      }t        j                  |dd      }|t        j                  |      z  }t        |d      S c c}w )z2Calculate Shannon entropy over function gate spacer   r   r   r   r|   )base)	r3   r\   r$   r^   r-   r   r   r   r   )r   r   weightss      r   calculate_entropyz+SemanticFunctionRegressor.calculate_entropy  s|    t""#q((($:M:MNQDJJqM00NO'''5#.266'?"wQ''	 Os    B	iterationc                     g } j                   D ]  } j                  |   }|xj                  dz  c_        |j                  dk  r"|xj                  d j
                  z
  z  c_        |j                   j                  k  sr|j                  |        |D ]1  } j                   j                  |       d j                  |   _	        3 t         j                          j                  kD  r`t         j                    fdd      }| j                  d }|D ]1  } j                   j                  |       d j                  |   _	        3 t        |      S )zb
        Prune low-potential gates to save compute
        Returns number of gates pruned
        rp   g      Fc                 6    j                   |    j                  S rk   r   r   s    r   rn   z8SemanticFunctionRegressor.prune_memory.<locals>.<lambda>  s    djjm22 r   Tr   N)r\   r-   r   r   r   rR   rY   r   remover   r3   rZ   r   )r   r   gates_to_pruner   r   sorted_indices
to_archives   `      r   prune_memoryz&SemanticFunctionRegressor.prune_memory  s=   
 && 	+C::c?D HHMH &&-DOO 34 {{T...%%c*	+ " 	+C&&s+%*DJJsO"	+
 t""#dnn4###2N
 (8J! /##**3/).

3&/ >""r   c                      j                         }| j                  k  s"t         j                         j                  k\  ryt
        j                  j                          j                  kD  ryt         j                        dkD  rt         j                   fd      } j                  |   }|j                   d| }|j                  }t
        j                  j                  dd      }	||	fd}
t        ||
d	d
|j                  d      } j                  j                  |        j                  j                  t         j                        dz
         yy)z|
        Symbolic Discovery: Generate new gates via mutation
        Only when entropy is high (exploration needed)
        Nr   c                 6    j                   |    j                  S rk   r   r   s    r   rn   z?SemanticFunctionRegressor.mutate_and_discover.<locals>.<lambda>      

1(<(< r   r   _mut_g      rx   c           	           ||       |t        j                  dt         j                  z  | z  t         j                  j	                  dd      z        z  z   S )Nr|   rx          @)r$   r   r   randomuniform)rm   r   ps      r   mutated_functionzGSemanticFunctionRegressor.mutate_and_discover.<locals>.mutated_function  sB    AwRVVAIMBII<M<McSV<W,W%X!XXXr   {Gz?mutated)rr   parentrt   rp   )r   rX   r3   r\   rZ   r$   r  rT   maxr-   r   r   r  r   r   )r   r   r.   r   current_entropybest_idxr>   new_gate_id	base_funcperturbationr  new_gates   `           r   mutate_and_discoverz-SemanticFunctionRegressor.mutate_and_discover  s4   
 002 T\\)S1D1D-E-W99 2 22 t""#a'4..<>H

8,I '../uYK@K "**I99,,T37L)2l Y $#)"+y7H7HI	H JJh'&&s4::':;/ (r   c           	      (     j                   syt        t         fd j                  dd D                    } j                  j                  |       t         j                        dkD  rt        dt        dt         j                        dz
              D ]x  } j                  d    j                  |dz       k(  s't         j                        |d	z   kD  sC j                  d
    j                  |d	z       k(  sg| _	        ||z
   _
         y y)z}
        Detect limit cycles in weight trajectory (ODE-CCT Periodicity)
        Returns True if periodicity detected
        Fc              3   d   K   | ]'  }t        j                  |   j                  d        ) yw)   N)roundr-   r   r   s     r   r   zFSemanticFunctionRegressor._detect_periodicity_cycle.<locals>.<genexpr>  s0      !D%& "'tzz!}';';Q!? !Ds   -0N
   r   2   rp   r|   T)r[   hashtupler\   r`   r   r3   r   minra   rb   )r   r   weight_hashks   `   r   _detect_periodicity_cyclez3SemanticFunctionRegressor._detect_periodicity_cycle  s   
 && 5 !D*.*=*=cr*B!D D E 	  - t  !B&1c"c$*;*;&<q&@AB ($$R(D,=,=!f,EE4,,-A5,,R0D4E4E!f4MM34D05>]D2#'( r   	max_iters
early_stopc                     | _         | _        d _         j                  rtt	        d       t	        d       t	        d       t	        dt        |       dt         j                                t	        d j                   d|        t	        d        j                         } j                  j                  |        j                  j                  t        j                   j                  D cg c]  } j                  |   j                   c}              j                  rt	        d	|d
d       t!        |      D ]  } j#                  ||        j                         } j                  j                  |        j                  j                  t        j                   j                  D cg c]  } j                  |   j                   c}              j%                  |      }	 j'                  |||        j)                  |      r< j                  rt	        d| d j*                   d       | j                  dz  k  r nى j                  r|dz  dk(  r j                  rt-         j                   fd      nd}
|
r j                  |
   j                  nd}t	        d|dd|d
dt         j                         d|
r j                  |
   j.                  nd d|dd|	        |s| j                  k  sˉ j                  rt	        d|         n  j                  rt-         j                   fd      nd}|n j                  |   }
|
j1                  |      }t        j2                  ||z
  dz        }t        j4                  ||z
  dz        }t        j4                  |t        j2                  |      z
  dz        }d ||d!z   z  z
  } j7                         }t        |j                        dkD  r j                  D ci c])  } j                  |   j.                   j                  |   + }}|j9                  ||      }t        j2                  ||z
  dz        }t        j4                  ||z
  dz        }d ||d!z   z  z
  }t        |j                        }n:t;        d"      }d#}d}n*t;        d"      }d#}t;        d"      }d#}d}
t=        g $      }d}d% _        t?         j                  d&    j                  k  rd'nd(|
r|
j.                  nd)||
r|
j                  nd# j                  d&   ||||t         j                        d z
  t         j                        t         j                        | j                   j                  *      } j                  r{t	        d       t	        d+       t	        d,|j@                          t	        d-|jB                          t	        d.|jD                          t	        d/|jF                  d       t	        d0|jH                  d
       t	        d1|jJ                  d
       t	        d2|jL                  d3       t	        d4|jN                  d3       t	        d5|jP                  d
d       t	        d6|jR                          t	        d7|jT                   d8|jV                          t	        d9|jX                   d:        j*                  rt	        d; j*                   d       t	        d       |S c c}w c c}w c c}w )<ar  
        Fit time series data to function gate superposition
        
        Args:
            X: Input features (time or independent variable)
            y: Target values
            max_iters: Maximum fitting iterations
            early_stop: Stop when entropy collapses
            
        Returns:
            FittingResult with metrics and trajectories
        FzF======================================================================u1   🛸 SEMANTIC FUNCTION REGRESSOR: CCT-ODE FITTINGz	Samples: z | Initial Gates: zEntropy Threshold: z | Max Iterations: zF----------------------------------------------------------------------zInitial Entropy: r   z bitsz%[PERIOD] Cycle detected at iteration z	 (period=r   r|   r  r   c                 6    j                   |    j                  S rk   r   r   s    r   rn   z/SemanticFunctionRegressor.fit.<locals>.<lambda>v  s    TZZ]-A-A r   r   NzIter 3dz: H=z	 | Gates=z | Best=zN/Az (z.2%z) | Pruned=u%   
[✓] ENTROPY COLLAPSE at iteration c                 6    j                   |    j                  S rk   r   r   s    r   rn   z/SemanticFunctionRegressor.fit.<locals>.<lambda>  s    A)=)= r   rp   r   infr   r   Tr  	COLLAPSEDPARTIALNONE)r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   zFITTING RESULTS:z
  Status: z  Best Single Gate: z  Best Circuit: z  Confidence (Single): u     R² Score (Single Gate): u     R² Score (Circuit): z  MSE (Single Gate): z.6fz  MSE (Circuit): z  Final Entropy: z  Iterations: z  Gates Active: z / z  Circuit Size: z gatesz   Periodicity: Detected (period=)-rd   re   rc   rV   printr3   r\   rX   r   r]   r   rK   r$   r^   r-   r   r   r   r   r  r  ra   r	  r   r   r   r   r   r5   r&   r,   r<   r=   r>   r?   r@   rB   rC   rD   rE   rA   rF   rH   rG   rI   )r   r.   r   r  r   H0r   tHprunedr>   best_weightbest_gate_idxy_pred_singlerD   ss_resss_totr2r?   registryy_pred_circuitrE   ss_res_circuitrC   rI   r4   s   `                         r   fitzSemanticFunctionRegressor.fit4  s   " <<(OEF(OIc!fX%7D<O<O8P7QRS'~5HTU(O ##%##B'""2887;7J7J-L23 .2ZZ]-A-A -L $M 	N <<%bXU34 y! %	A""1a( &&(A  ''*&&rxx;?;N;N1P67 26A1E1E 1P (Q R &&q)F $$Q1- --a0<<A!IdNbNbMccdeft||a'' ||B!FJFYFY   3 3#AC_c >Gdjj3::QaV4#wiD<O<O8P7Q R?Hdjj3;;eT U%c*+fX? @
 a$,,.<<B1#FGK%	R CGBUBU D//=?[_ 	 $

=1I%..q1M''=1,23CVVQ.145FVVQ^12Ff/0B  002L<%%&*JNJ]J]^QDJJqM114::a=@^^!-!6!6q(!C gg~'9a&?@!#^);(A!B.FUN"CD
"<#5#56#El 
 ,CB,KJI",LL"&"6"6r":T\\"I;y+4i''&%+4y''#..r2!#4//014

OT001%#33..
$ <<(O$%Jv}}o./()9)9(:;<$V%8%8$9:;+F,=,=c+BCD//DEF+F,=,=c+BCD)&**S)9:;%f&8&8%=>?%f&:&:3%?uEFN6#4#4"567$V%8%8$9V=S=S<TUV$V%8%8$9@A##89M9M8NaPQ(Oq-L1P` _s   4 \39 \8.\=modereturn_uncertaintyc                      j                   st        d      |dk(  r9t         j                   fd      } j                  |   j                  |      }n|dk(  ra j                         } j                  D ci c])  } j                  |   j                   j                  |   + }}|j                  ||      }njt        j                  t        |            } j                  D ]=  }	| j                  |	   j                   j                  |	   j                  |      z  z  }? |rt         j                        dkD  rut        j                   j                  D cg c]   } j                  |   j                  |      " c}      }
t        j                  |
d       j                         z  }||fS t        j                  t        |            }||fS |S c c}w c c}w )	a  
        Make predictions using fitted function gates

        Args:
            X: Input features
            mode: Prediction mode:
                  - "circuit": Use best circuit (weighted combination, default)
                  - "ensemble": Use all active gates (full superposition)
                  - "single": Use best single gate only (legacy)
            return_uncertainty: Also return prediction uncertainty

        Returns:
            Predictions (and optionally uncertainty)
        z&Model must be fitted before predictionsinglec                 6    j                   |    j                  S rk   r   r   s    r   rn   z3SemanticFunctionRegressor.predict.<locals>.<lambda>  r   r   r   circuitrp   r   )axis)rc   
ValueErrorr	  r\   r-   r   r   r   r5   r$   r2   r3   r   r^   stdr   )r   r.   r8  r9  r  r   r?   r   r4  r   predictionsuncertaintys   `           r   predictz!SemanticFunctionRegressor.predict  s   $ {{EFF84..<>HZZ)2215FY002LFJFYFYZ

1--tzz!}<ZHZ!**1h7F XXc!f%F** O$**S/004::c?3K3KA3NNNO 4&&'!+ hh040C0C(E+, )-

1(>(>q(A (E F ff[q9D<R<R<TT ;&& !hhs1v.;&&% [(Es   :.G%Gc                    t        j                  d       t        j                  | j                  ddd       t        j                  | j
                  ddd	| j
                   d
       t        j                  d       t        j                  d       t        j                  d       t        j                          t        j                  dd       t        j                          t        j                          y)z-Plot entropy collapse over fitting iterations)r  r   figsizezb-or|      )	linewidth
markersizer--zCollapse Threshold (r   )r   color	linestylelabel	Iterationu   Semantic Entropy H(Ψ) [bits]z#CCT-ODE Entropy Collapse TrajectoryT333333?rN   N)pltfigureplotr]   axhlinerX   xlabelylabeltitlelegendgridtight_layoutshowr   s    r   plot_entropy_trajectoryz1SemanticFunctionRegressor.plot_entropy_trajectory  s    

7#%%uaHdll#/~Q?	A

;

23		78

S!
r   top_nc                    t        | j                        dk(  ryt        j                  d       | j                  D cg c]  }|| j
                  |   j                  f }}t        |d d      d| }|D ]a  \  }}| j                  D cg c]  }|t        |      k  r||   nd }}t        j                  |d| j
                  |   j                   	       c t        j                  d
       t        j                  d       t        j                  d       t        j                  dd       t        j                  dd       t        j                          t        j                           yc c}w c c}w )z"Plot evolution of top gate weightsr   N)   rG  rE  c                     | d   S r   r*   rl   s    r   rn   zASemanticFunctionRegressor.plot_weight_evolution.<locals>.<lambda>  s
    !A$ r   Tr   r|   rH  rN  rO  zGate Weightz7Function Gate Weight Evolution (Superposition Collapse)zupper right   )locfontsizerP  rQ  )r3   rK   rR  rS  r\   r-   r   r   rT  r   rV  rW  rX  rY  rZ  r[  r\  )	r   r^  r   final_weightstop_indicesr   _r9   weights_over_times	            r   plot_weight_evolutionz/SemanticFunctionRegressor.plot_weight_evolution  s:   t""#q(

7# =A<O<OPq!TZZ]112PP]MfuU! 	8FC)-)<)<!>$% ,/Q<3Q!> !> !>HH&!!ZZ_4458	8 	

;

=!		KL

}q1S!
 Q!>s   "E0
E5X_testy_testc                 :     j                   syt        j                  d       t        j                  ddd       t        j                   j
                   j                  ddd	       t        j                   j
                  j                          j
                  j                         d
      } j                  |d      } j                         }t        j                  ||dddt        |j                         d        j                  |d      }t        j                  ||dddd j                  t         j                    fd         j"                          t        j$                  d       t        j&                  d       t        j(                  d       t        j*                          t        j,                  dd       t        j                  ddd        j                   j
                  d      } j                   j
                  d      } j                  |z
  }	 j                  |z
  }
t        j                  ||	ddd !       t        j                  ||
dd"d#!       t        j.                  d$d%d&'       t        j$                  d(       t        j&                  d)       t        j(                  d*       t        j*                          t        j,                  dd       t        j0                          t        j2                          y)+z!Plot fitted function against dataN)r`  r   rE  rp   r|   rx   zTraining Datablue)rN   rN  rL     r=  r8  r-z	Circuit ( gates)rb  r;  zg--      ?gffffff?zBest Single: c                 6    j                   |    j                  S rk   r   r   s    r   rn   z4SemanticFunctionRegressor.plot_fit.<locals>.<lambda>D  s    X\XbXbcdXeXlXl r   r   )rH  rN   rN  r.   r   z.Semantic Function Fit (Circuit vs Single Gate)TrP  rQ  redzCircuit residuals)rN   rL  rN  greenzSingle gate residualsr   rJ  rK  )r   rL  rM  	PredictedResidualz!Residual Plot (Circuit vs Single))rc   rR  rS  subplotscatterrd   re   r$   linspacer  r	  rC  r   rT  r3   r-   r\   r   rV  rW  rX  rY  rZ  rU  r[  r\  )r   rk  rl  X_smoothr5  r?   r0  y_train_pred_circuity_train_pred_singleresiduals_circuitresiduals_singles   `          r   plot_fitz"SemanticFunctionRegressor.plot_fit.  sJ   {{

7# 	Aq!DLL$,,c(	8 ;;t||//14<<3C3C3EsKhY?,,.>41!#l&8&8"9!:'B	D XH==%3c%djjT5H5HNl1m&n&v&v%wx	z 	

3

3		BC

S! 	Aq!#||DLLy|I"ll4<<hlG LL+??<<*==(*;3&9	;')9 (?	Aasd3

;

:		56

S!
r   c                 \   | j                   syt        j                  d       | j                  D cg c]  }| j                  |   j
                   }}| j                  D cg c]  }| j                  |   j                   }}t        j                  |      ddd   }t        j                  |      |   }t        j                  |      |   }t        j                  t        t        |            |d       t        j                  t        t        |            |dd	       t        j                  d
       t        j                  d       t        j                   d       t        j"                  ddd       t        j$                          t        j&                          yc c}w c c}w )z#Plot final gate weight distributionN)   rG  rE  r  	steelbluerL  Z   rc  )rotationre  zFunction GatezWeight (Probability)z:Final Function Gate Distribution (Collapsed Superposition)TrP  r   rN   r>  )rc   rR  rS  r\   r-   r   r   r$   argsortr^   barr   r3   xticksrV  rW  rX  rZ  r[  r\  )r   r   r   
gate_names
sorted_idxs        r   plot_gate_distributionz0SemanticFunctionRegressor.plot_gate_distributiona  s-   {{

7#151D1DEA4::a=''EE595H5HIdjjm++I
I ZZ(2.
((7#J/XXj)*5
c'l#WK@

5W&
R!L

?#

)*		NOSs+
 FIs    F$" F)c                 z   | j                   sy| j                         }t        |j                        dk(  rt	        d       yt        j                  ddd      \  }}|j                  D cg c]  }|d   	 }}|j                  D cg c]  }|d   	 }}t
        j                  j                  t        j                  dd	t        |                  }|d   j                  t        t        |            ||
      }t        ||      D ]T  \  }	}
|d   j                  |	j                         |	j!                         dz  z   |	j#                         dz   |
dddd       V |d   j%                  t        t        |                   |d   j'                  |dd       |d   j)                  d       |d   j+                  d       |d   j-                  dt        |       d       |d   j/                  ddd       t        j                  | j0                  j3                         | j0                  j5                         d      }|d   j7                  | j0                  | j8                  dddd !       |j                  D ]v  \  }}
| j:                  D ]b  }| j                  |   j<                  |k(  s | j                  |   j?                  |      |
z  }|d   jA                  ||d"d#d$| d%|
dd&'        v x | jC                  |d()      }|d   jA                  ||d*d+d,d-.       |d   j)                  d/       |d   j+                  d       |d   j-                  d0       |d   jE                  d1d23       |d   j/                  dd4       t        jF                          t        jH                          yc c}w c c}w )5z0Plot the best circuit showing gate contributionsNr   zNo circuit foundrp   r|   )r  r   rE  g?g?r  r  r  z.3fcenterbottom	   )havare  -   right)r  r  GatezNormalized WeightzCircuit Composition (rr  TrP  r   r  ro  Datablackr  )rN   rN  rL  srK  g333333?rs  u    (×r   )rN   rH  rN  r=  rp  rq  g      @zCircuit Totalg?)rH  rN  rN   r.   zCircuit Gate Contributions   best)re  rd  rQ  )%rc   r   r3   r-   r)  rR  subplotscmRdYlGnr$   r{  r  r   ziptextget_x	get_width
get_height
set_xticksset_xticklabels
set_xlabel
set_ylabel	set_titlerZ  rd   r  r	  rz  re   r\   r   r   rT  rC  rY  r[  r\  )r   r?   figaxesggate_idsgate_weightscolorsbarsr  r   r|  r   r   y_gate	y_circuits                   r   plot_circuit_compositionz2SemanticFunctionRegressor.plot_circuit_compositiony  s_   {{,,.|!!"a'$%LLAw7	T #/"4"45QAaD55&2&8&89!99r{{3S]CDAw{{5X/V{L t\2 	OKCGLLs}}r'993>>;Kd;R!#,HA  O	O 	Q5X/0Q2'BQ6"Q./Q1#h-HIQT3/ ;;t||//14<<3C3C3EsKQdll#VSZ^`a+11 	OGV** ::c?**g5!ZZ_55h?&HFGLL64s),witF3<q4Q ! S	 LL	L:	QXy$#_\_`Q3Q3Q67Qv.QT%
W 69s   +N3N8c           
           j                   sddiS t         j                   fd      } j                         }d j                  |   j
                  t        |      t        |j                         j                  |   j                   j                  d   t         j                        t         j                         j                  d	S )zGet summary of fitted modelr=   
NOT_FITTEDc                 6    j                   |    j                  S rk   r   r   s    r   rn   z7SemanticFunctionRegressor.get_summary.<locals>.<lambda>  s    DJJqM$8$8 r   r   FITTEDr  )	r=   r>   r?   rI   r@   r   active_gatestotal_gatesperiodicity_detected)rc   r	  r\   r   r-   r   r"   r3   r   r]   ra   )r   r  r?   s   `  r   get_summaryz%SemanticFunctionRegressor.get_summary  s    {{l++t**8:,,. H-55- 2 23**X.55++B/ 3 34tzz?$($8$8

 
	
r   )
ro   r   r  r  r  r   ro   r   TT)r|   rk   )d   T)r=  F)r  )NN) r   r   r    r!   r&   r'   r(   rg   rf   r"   r   r$   r%   r   r,   r   r   r   r   r   r  r  r<   r7  rC  r]  rj  r  r  r  r   r  r*   r   r   rM   rM   B   sW   & !%,/*.)+%)$'(,%&/3!%7(7($)7( #(7( $'	7(
 #7( "7( !&7(  #7( )-7( 7(zb;N +,8!$8"*BJJ<+C"D8 %(8$',c ',W ',R(*

(*

 03 8=0&Q2:: &Q"** &Q &QP	(5 	('#c '#c '#R&<S &<RZZ &<BJJ &<X3 4 D !#	XzzXzzX X 	X )6	X@ &+0/::// %)/ 68ZZ/j3 21rzz 1"** 1f09~
T 
r   rM   )numpyr$   matplotlib.pyplotpyplotrR  scipy.statsr   typingr   r   r   r   r   dataclassesr	   r
   hashlibr   r,   r<   rM   r*   r   r   <module>r     st       8 8 (  < < < B B B  % % %,I
 I
r   