
    ,iG              
           d dl Z G d d      Zd2dZd Zd Z G d d      Zed	k(  rf ed
        ed        ed
        ed       ej                  dddd      Z
ej                  dddd      Z ede
         ede        e
ez   Z ede        e
j                  e      Z ede         ed       ej                  dddd      Z edej!                         d       dZ ed      D ]3  Zej)                  e      Z ededz    dej!                         d       5  ed         ed!d"      Zej,                  j/                  d#d!      Zej3                  e      \  ZZ ed$ej8                           ed%ej8                           ed&ej;                         d        ed'ej=                         d        ed(        ed!      D ]  Zej,                  j/                  d!d      dz  Zej,                  j/                  dd      d)z  Z ejC                  ee d)d*+       ed,z  d k(  s_ ed-e d.ejD                  j!                         dd/ej=                         d         ed0        ed1        ed
       yy)3    Nc                       e Zd ZdZddZed        Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd ZddZddZddZedd       Zed d       Zd!dZd Zd Zd Zd Zd Zd Zy)"
FluxMatrixa  
    A matrix in Flux Algebra where each element is a Flux Number.
    
    The matrix is represented as three aligned matrices:
    - V: Value matrix (the current "mean" state)
    - S: Entropy matrix (uncertainty/spread of each element)
    - T: Flux matrix (rate of change/velocity of each element)
    
    This enables tracking uncertainty and evolution in ML weights,
    gradients, and activations.
    Nc                 H   t        j                  |t         j                        | _        |%t        j                  | j                        | _        n*t        j                  |t         j                        | _        |%t        j                  | j                        | _        n*t        j                  |t         j                        | _        | j                  j                  | j
                  j                  cxk(  r| j                  j                  k(  sJ d        J d       y)z
        Initialize a FluxMatrix.
        
        Args:
            V: Value matrix (numpy array or scalar)
            S: Entropy matrix (same shape as V, default: zeros)
            T: Flux matrix (same shape as V, default: zeros)
        dtypeNz V, S, T must have the same shape)nparrayfloat64V
zeros_likeSTshape)selfr   r   r   s       //home/per/Documents/flux algebra/flux_matrix.py__init__zFluxMatrix.__init__   s     !2::.9]]466*DFXXarzz2DF9]]466*DFXXarzz2DFvv||tvv||;tvv||; 	/.	/; 	/.	/;    c                 .    | j                   j                  S N)r   r   r   s    r   r   zFluxMatrix.shape'   s    vv||r   c                 r   d| j                    d| j                  j                         dd| j                  j                         dd| j                  j                         dd| j                  j                         dd| j
                  j                         dd| j
                  j                         ddS )NzFluxMatrix(shape=z, V_range=[z.3fz, z], S_range=[z], T_range=[z]))r   r   minmaxr   r   r   s    r   __repr__zFluxMatrix.__repr__+   s    #DJJ< 0 FFJJL-R

S/A B FFJJL-R

S/A B FFJJL-R

S/AE 	Fr   c                    t        |t        t        f      rJt        | j                  |z   | j
                  j                         | j                  j                               S t        |t              rq| j                  |j                  z   }t        j                  | j
                  dz  |j
                  dz  z         }| j                  |j                  z   }t        |||      S t        dt        |             )u   
        Flux Addition (⊕): Merging of two trajectories.
        
        z1 ⊕ z2 = ⟨v1 + v2, √(σ1² + σ2²), τ1 + τ2⟩
           zCannot add FluxMatrix and 
isinstanceintfloatr   r   r   copyr   r   sqrt	TypeErrortyper   othernew_Vnew_Snew_Ts        r   __add__zFluxMatrix.__add__5   s     ec5\* 
 z*FFUWW$EGGDFFAI
23EFFUWW$EeUE228eFGGr   c                 $    | j                  |      S r   )r*   r   r&   s     r   __radd__zFluxMatrix.__radd__I   s    ||E""r   c                    t        |t        t        f      rJt        | j                  |z
  | j
                  j                         | j                  j                               S t        |t              rq| j                  |j                  z
  }t        j                  | j
                  dz  |j
                  dz  z         }| j                  |j                  z
  }t        |||      S t        dt        |       d      )zFlux Subtraction.r   zCannot subtract z from FluxMatrixr   r%   s        r   __sub__zFluxMatrix.__sub__L   s    ec5\* 
 z*FFUWW$EGGDFFAI
23EFFUWW$EeUE22.tE{m;KLMMr   c                     t        |t        t        f      rC| j                  |z  }| j                  t        |      z  }| j                  |z  }t        |||      S t        dt        |             )u\   
        Scalar Multiplication.
        
        α ⊗ z = ⟨αv, |α|σ, ατ⟩
        zCannot multiply FluxMatrix by )
r   r   r    r   r   absr   r   r#   r$   )r   scalarr'   r(   r)   s        r   __mul__zFluxMatrix.__mul__\   sd     fsEl+FFVOEFFS[(EFFVOEeUE22<T&\NKLLr   c                 $    | j                  |      S r   )r3   )r   r2   s     r   __rmul__zFluxMatrix.__rmul__j   s    ||F##r   c                    t        |t              r| j                  |j                  z  }t        j                  | j                  |j
                  z  dz  |j                  | j
                  z  dz  z         }| j                  |j                  z  |j                  | j                  z  z   }t        |||      S t        |t        t        f      r| j                  |      S t        dt        |             )u   
        Element-wise Flux Multiplication (⊗).
        
        z1 ⊗ z2 = ⟨v1*v2, √((v1*σ2)² + (v2*σ1)²), v1*τ2 + v2*τ1⟩
        r   zCannot hadamard FluxMatrix and )r   r   r   r   r"   r   r   r   r    r3   r#   r$   r%   s        r   hadamardzFluxMatrix.hadamardm   s     eZ(FFUWW$EGGTVVegg-1UWWtvv5E4IIJEFFUWW$uww'77EeUE22U|,<<&&=d5k]KLLr   c           	         t        |t              st        dt        |             | j                  |j                  z  }t        j                  |j                        }t        j                  |j                        }t        | j                  j                  d         D ]  }t        |j                  j                  d         D ]  }d}d}t        | j                  j                  d         D ]  }	|| j                  ||	f   |j                  |	|f   z  dz  |j                  |	|f   | j                  ||	f   z  dz  z   z  }|| j                  ||	f   |j                  |	|f   z  |j                  |	|f   | j                  ||	f   z  z   z  } t        j                  |      |||f<   ||||f<     t        |||      S )u   
        Flux Matrix Multiplication.
        
        For C = A @ B:
        C[i,j] = Σ_k A[i,k] ⊗ B[k,j]
        
        This propagates entropy through the matrix multiplication chain.
        zCannot matmul FluxMatrix and r              r   )r   r   r#   r$   r   r   zerosr   ranger   r   r"   )
r   r&   r'   r(   r)   ijs_sq_sumt_sumks
             r   matmulzFluxMatrix.matmul}   s    %,;DK=IJJ  
 %%tvv||A' 	$A577==+, $tvv||A/ :A11!= A!&A1!= A!B BH TVVAqD\EGGAqDM9"WWQT]TVVAqD\9: :E: !ggh/ad#ad$	$ %..r   c                 $    | j                  |      S )z#Matrix multiplication operator (@).)rB   r,   s     r   
__matmul__zFluxMatrix.__matmul__   s    {{5!!r   c                 6   t        |t        t        f      r$t        j                  d| j
                  |z
        }n#t        j                  d| j
                  |z
        }t        | j                  j                         || j                  j                               S )u  
        Collapse Operator (C): Reduce entropy by paying Work.
        
        C(z, W) = ⟨v, max(0, σ - W), τ⟩
        
        Args:
            W: Work budget (scalar or matrix of same shape)
        
        Returns:
            New FluxMatrix with reduced entropy
        r   )
r   r   r    r   maximumr   r   r   r!   r   )r   Wr(   s      r   collapsezFluxMatrix.collapse   se     a#u&JJq$&&1*-EJJq$&&1*-E$&&++->>r   c                     | j                   | j                  |z  z   }| j                  dz  }t        ||| j                  j	                               S )u  
        Flux Derivative / ODE step.
        
        d/dt ⟨v, σ, τ⟩ = ⟨τ, σ̇, τ̇⟩
        
        For discrete evolution:
        - v_new = v + τ * dt
        - σ_new = σ * decay (natural entropy decay)
        - τ stays constant (unless specified otherwise)
        
        Args:
            dt: Time step
        
        Returns:
            New evolved FluxMatrix
        gGz?)r   r   r   r   r!   )r   dtr'   r(   s       r   evolvezFluxMatrix.evolve   s@    " "$%66r   c                      | j                   |z  S )u   
        Compute entropy velocity (σ̇).
        
        σ̇ = (σ_t - σ_{t-1}) / dt
        
        Returns:
            Matrix of entropy velocities
        )r   )r   rJ   s     r   entropy_velocityzFluxMatrix.entropy_velocity   s     vv{r   c                 (    | j                         |k  S )z
        Check if the system is collapsing (learning/stabilizing).
        
        Returns:
            Boolean matrix where True indicates collapsing elements
        rM   r   	thresholds     r   is_collapsingzFluxMatrix.is_collapsing        $$&22r   c                 (    | j                         |kD  S )z
        Check if the system is expanding (hallucinating/diverging).
        
        Returns:
            Boolean matrix where True indicates expanding elements
        rO   rP   s     r   is_expandingzFluxMatrix.is_expanding   rS   r   c                     t        j                  j                  | |z  }t        j                  |      |z  }t        j                  j                  | |z  } | |||      S )ab  
        Create a random FluxMatrix for initializing ML weights.
        
        Args:
            shape: Tuple specifying matrix shape
            v_scale: Scale for value initialization (Xavier-like)
            s_init: Initial entropy
            t_scale: Scale for flux initialization
        
        Returns:
            Random FluxMatrix
        )r   randomrandnones)clsr   v_scales_initt_scaler   r   r   s           r   from_randomzFluxMatrix.from_random   sR     IIOOU#g-GGENV#IIOOU#g-1a|r   c                     t        j                  |t         j                        }t        j                  |      |z  }t        j                  |      |z  } | |||      S )aD  
        Create a FluxMatrix from a standard numpy array.
        
        Args:
            array: numpy array of values
            entropy: Initial entropy for all elements
            flux: Initial flux for all elements
        
        Returns:
            FluxMatrix with given values and uniform entropy/flux
        r   )r   r	   r
   	ones_like)rZ   r	   entropyfluxr   r   r   s          r   
from_arrayzFluxMatrix.from_array  sJ     HHU"**-LLOg%LLOd"1a|r   c                    t        |t              r|| z  }nY| |z  }t        j                  |      }t	        |d      r|j                         nt        j                  |      }t        |||      }| |z   }|j                  |      S )u  
        Perform a gradient descent step in Flux Algebra.
        
        This is the Flux Algebra equivalent of:
        θ_new = θ_old - lr * gradient
        
        Implemented as:
        θ_{t+1} = θ_t ⊕ (-lr * gradient)
        Then collapse to reduce uncertainty.
        
        Args:
            gradient: FluxMatrix or standard matrix of gradients
            learning_rate: Learning rate (scalar)
            work_budget: Work to pay for collapse
        
        Returns:
            Updated FluxMatrix
        r!   )r   r   r   r   hasattrr!   r	   rH   )	r   gradientlearning_ratework_budgetdeltadelta_Vdelta_Sdelta_Tnew_selfs	            r   gradient_stepzFluxMatrix.gradient_step  s    & h
+/E %nx/GmmG,G)06)BhmmoQYHZGw9E %<   --r   c                     t        |t              r|| z  }|j                  |j                  fS t	        j
                  |      }|| j                  z  }t	        j                  |dz  | j                  dz  z        }||fS )a-  
        Make predictions with uncertainty propagation.
        
        For y = X @ W:
        Returns both prediction and uncertainty.
        
        Args:
            X: Input FluxMatrix or standard matrix
        
        Returns:
            Tuple of (prediction, uncertainty) matrices
        r   )r   r   r   r   r   r	   r"   )r   XresultX_arrresult_Vresult_Ss         r   predictzFluxMatrix.predict9  sp     a$XF88VXX%% HHQKEtvv~Hwwq46619 46HX%%r   c                 V    t         j                  j                  | j                  d      S )z6Get total entropy of the matrix (Frobenius norm of S).fro)r   linalgnormr   r   s    r   total_entropyzFluxMatrix.total_entropyP      yy~~dffe,,r   c                 V    t         j                  j                  | j                  d      S )z/Get total flux magnitude (Frobenius norm of T).rw   )r   rx   ry   r   r   s    r   
total_fluxzFluxMatrix.total_fluxT  r{   r   c                     | j                         }|dk(  ryt        j                  t        j                  d| j	                                      }d||z  z
  S )z
        Compute stability score: ratio of collapsed entropy to total.
        
        Higher score = more stable/certain system.
        r         ?)rz   r   sumrF   rM   )r   total	collapseds      r   stability_scorezFluxMatrix.stability_scoreX  sQ     ""$A:FF2::a$*?*?*A)ABC	i%'((r   c                 6    | j                   j                         S )z/Extract just the value matrix as a numpy array.)r   r!   r   s    r   to_arrayzFluxMatrix.to_arrayd  s    vv{{}r   c                     t        | j                  j                         | j                  j                         | j                  j                               S )z&Create a deep copy of this FluxMatrix.)r   r   r!   r   r   r   s    r   r!   zFluxMatrix.copyh  s/    $&&++-FFr   )NN)r   )r:   )皙?{Gz?MbP?)r   r:   r   r   )__name__
__module____qualname____doc__r   propertyr   r   r*   r-   r/   r3   r5   r7   rB   rD   rH   rK   rM   rR   rU   classmethodr^   rc   rn   ru   rz   r}   r   r   r!    r   r   r   r      s    
/,  FH(#N M$M #/J"?$7*	33  $  " .D&.--
)Gr   r   c                     t        t        j                  |       t        j                  | | f      |z   t        j                  | | f      |z         S )z$Create a FluxMatrix identity matrix.)r   r   eyer;   )nsts      r   flux_eyer   q  s=    bffQi1a&!1A!5rxxA7G!7KLLr   c                 >    t        t        j                  |             S )zCreate a FluxMatrix of zeros.)r   r   r;   r   s    r   
flux_zerosr   v  s    bhhuo&&r   c                 >    t        t        j                  |             S )zCreate a FluxMatrix of ones.)r   r   rY   r   s    r   	flux_onesr   {  s    bggen%%r   c                   ,    e Zd ZdZddZd ZddZd Zy)	FluxLinearLayeru   
    A linear layer using Flux Algebra for uncertainty-aware learning.
    
    This tracks not just the weights, but their uncertainty and
    evolution over time—enabling automatic confidence estimation.
    c                     t        j                  d|z        }t        j                  ||f|||dz        | _        t        j                  d|fd|d      | _        y )Ng       @r   r[   r\   r]   r9   r:   r   )r   r"   r   r^   weightsbias)r   in_featuresout_featuresinit_entropyscales        r   r   zFluxLinearLayer.__init__  sk    k)*!--,'DL	 . 
 **	 + 
	r   c                    || j                   j                  z  | j                  j                  z   }t        j                  |dz  | j                   j
                  dz  z  | j                  j
                  dz  z         }||fS )z
        Forward pass with uncertainty propagation.
        
        Args:
            X: Input matrix (standard numpy array)
        
        Returns:
            Tuple of (output_value, output_entropy)
        r   )r   r   r   r   r"   r   )r   rp   out_Vout_Ss       r   forwardzFluxLinearLayer.forward  sb     DLLNN"TYY[[0A 11TYY[[!^CDe|r   c                     | j                   j                  |||      | _         | j                  j                  |||      | _        y)a  
        Update weights using gradient descent with entropy collapse.
        
        Args:
            grad_weights: Gradient for weights
            grad_bias: Gradient for bias
            lr: Learning rate
            work: Work budget for collapse
        N)r   rn   r   )r   grad_weights	grad_biaslrworks        r   updatezFluxLinearLayer.update  s8     ||11,DIII++Ir4@	r   c                 b    | j                   j                         }t        j                  |       S )zs
        Get confidence in this layer's weights.
        1.0 = fully confident, 0.0 = maximum uncertainty.
        )r   rz   r   exp)r   rz   s     r   
confidencezFluxLinearLayer.confidence  s'    
 224vv}n%%r   N)r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r     s    
 A&r   r   __main__z<============================================================z-FLUX ALGEBRA FOR MATRICES - ML Iteration Demoz$
--- Example 1: Basic Operations ---)   r   r   g      ?r   r   g333333?g?zA = zB = u
   A ⊕ B = u   A ⊗ B (matmul) = z0
--- Example 2: Learning as Entropy Collapse ---)   r   zInitial total entropy: z.4f   zEpoch r9   z: entropy = z-
--- Example 3: Flux Neural Network Layer ---
   )r   r       zInput shape: zOutput shape: zOutput uncertainty (mean): zLayer confidence: z
Training simulation:r   g{Gzt?)r   r   r   z  Epoch z: weight_entropy=z, confidence=z=
============================================================z5Flux Algebra enables uncertainty-aware ML iterations!)r:   r:   )#numpyr   r   r   r   r   r   r   printr^   ABCrB   Dmodelrz   rh   r<   epochrH   layerrW   rX   rp   r   outputuncertaintyr   meanr   grad_Wgrad_br   r   r   r   r   <module>r      s   fG fGZM
'
&;& ;&D z	(O	
9:	(O 

12vs3LAvs3MA	D*	D*	AA	Jqc
	A	s
#$ 

=>""63sC"PE	#E$7$7$9##>
?@Kq I{+uQwi|E,?,?,A#+FGHI
 

:;;E
		BA--*FK	M!''
#$	N6<<.
)*	'(8(8(:3'?
@A	u//1#6
78 

"#r :Q'#-A&-VV5919>HUG#4U]]5P5P5RSV4W X  % 0 0 2379 :: 
/	
AB	(Ok r   