
    j
&                     ,   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZ	 d dlZ	dZdZeez  ZdZdZdZd	Zd
ZdZdZ G d dej,                        Zd Z G d d      Zedk(  r e       Zej9                          yy# e
$ r  ed        ed       dZ	Y pw xY w)    Nz@Warning: sounddevice not found. Audio features will be disabled.z7Please run: pip install sounddevice numpy opencv-python$      i  i         g333333?g      >@aP  
#include <math.h>
#include <string.h>
#include <stdio.h>

typedef struct {
    float winding;
    float hyperfine;
    float entropy;
    float accuracy;
    int isEPR;
    int isViolation;
    float avgMotion;
} Metrics;

void process_grid(const float* gray, float* prev_luma, int w, int h, 
                  float cavityEnergy, Metrics* out, char* statusMsg) {
    float totalDX = 0.0f, totalDY = 0.0f;
    float totalMotion = 0.0f;
    float lumaSum = 0.0f;
    int totalPixels = w * h;

    float spinTheta[1008]; // Max size for 36*28
    float spinMag[1008];

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            int idx = y * w + x;
            float lum = gray[idx];
            lumaSum += lum;

            if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {
                float left  = gray[y * w + (x - 1)];
                float right = gray[y * w + (x + 1)];
                float up    = gray[(y - 1) * w + x];
                float down  = gray[(y + 1) * w + x];

                float dx = right - left;
                float dy = down - up;
                float theta = atan2f(dy, dx);
                float mag = sqrtf(dx*dx + dy*dy);

                float motion = fabsf(lum - prev_luma[idx]);
                totalMotion += motion;

                totalDX += cosf(theta) * mag;
                totalDY += sinf(theta) * mag;

                spinTheta[idx] = theta;
                spinMag[idx] = mag;
            }
            prev_luma[idx] = lum;
        }
    }

    float avgMotion = totalMotion / totalPixels;
    float meanLuma = lumaSum / totalPixels;

    // Winding number
    float circulation = 0.0f;
    for (int y = 2; y < h - 2; ++y) {
        for (int x = 2; x < w - 2; ++x) {
            int idx = y * w + x;
            float t = spinTheta[idx];
            circulation += (sinf(t) * totalDX - cosf(t) * totalDY);
        }
    }
    out->winding = fabsf(circulation) / (totalPixels * 2.0f);
    if (out->winding > 1.0f) out->winding = 1.0f;

    // Hyperfine
    out->hyperfine = avgMotion * cavityEnergy * 8.0f;
    out->avgMotion = avgMotion;

    // Entropy
    float totalMag = 0.0f;
    for (int i = 0; i < totalPixels; i++) totalMag += spinMag[i] + 0.001f;
    float entropyVal = 0.0f;
    for (int i = 0; i < totalPixels; i++) {
        float p = (spinMag[i] + 0.001f) / totalMag;
        if (p > 0.0f) entropyVal -= p * log2f(p);
    }
    float maxEnt = log2(totalPixels);
    out->entropy = entropyVal;
    float normEntropy = entropyVal / maxEnt;

    // Accuracy
    out->accuracy = (1.0f - normEntropy) * out->hyperfine * 4.0f;
    if (out->accuracy > 1.0f) out->accuracy = 1.0f;

    // EPR detection (Simplified)
    float leftMotion = 0.0f, rightMotion = 0.0f;
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            float delta = fabsf(prev_luma[y*w+x] - meanLuma);
            if (x < w/2) leftMotion += delta;
            else rightMotion += delta;
        }
    }
    float leftCorr = leftMotion / (totalPixels/2);
    float rightCorr = rightMotion / (totalPixels/2);
    
    out->isEPR = (fabsf(leftCorr - rightCorr) < 0.05f && cavityEnergy > 0.15f && avgMotion > 0.02f && out->hyperfine > 0.25f);
    
    out->isViolation = 0;
    if (avgMotion > 0.08f && cavityEnergy < 0.03f) out->isViolation = 1;
    else if (avgMotion < 0.02f && cavityEnergy > 0.25f) out->isViolation = 1;

    if (out->isEPR) strcpy(statusMsg, "EPR BRIDGE DETECTED");
    else if (out->isViolation) strcpy(statusMsg, "SKISS-VIOLATION");
    else if (normEntropy > 0.85f) strcpy(statusMsg, "SKISS-INCOMPLETE");
    else strcpy(statusMsg, "SKISS-COMPLETE (Bonded)");
}
c                       e Zd Zdej                  fdej                  fdej                  fdej                  fdej
                  fdej
                  fdej                  fgZy)	Metricswinding	hyperfineentropyaccuracyisEPRisViolation	avgMotionN)__name__
__module____qualname__ctypesc_floatc_int_fields_     ./home/per/Documents/Sensor linear acc/mapsh.pyr   r      s]    	FNN#	fnn%	FNN#	V^^$	&,,	%	fnn%Hr   r   c            	      x   d} d}t        | d      5 }|j                  t               d d d        	 t        j                  dddd|d| g       t        j                  |      }t        j                  t        j                        t        j                  t        j                        t        j                  t        j                  t        j                  t        j                  t              t        j                  g|j                  _        |S # 1 sw Y   xY w# t
        $ r}t        d	|        Y d }~y d }~ww xY w)
Nzmapsh_core.cz./mapsh_core.sowgccz-O3z-sharedz-oz-fPICzError compiling C core: )openwriteC_CODE
subprocess
check_call	Exceptionprintr   CDLLPOINTERr   r   r   c_char_pprocess_gridargtypes)c_fileso_filefelibs        r   	get_c_libr.      s    FG	fc	 a	ueYgwPVWX
 ++g
Cv~~&v~~&w!C J' 
  (,-s"   DD D	D9!D44D9c                   $    e Zd Zd Zd Zd Zd Zy)MAPHSc                 ~   t               | _        | j                  s t        d       t        j                  d       t        j                  t        t
        j                        | _	        d| _
        d| _        d| _        t        d       | _        t        j                  t        t
        j                        | _        y )NzFFalling back to (slower) Python implementation is not yet implemented.   )dtype        g      ?inf)r.   r-   r#   sysexitnpzerosTOTAL_PIXELSfloat32	prev_lumacavity_energygain_emacontrol_outputfloat	last_gainFFT_SIZEaudio_buffer)selfs    r   __init__zMAPHS.__init__   sy    ;xxZ[HHQK,bjjA !, HHXRZZ@r   c                 d   |rt        |       t        j                  | j                  |       | _        |d d df   | j                  | d  t        j                  t        j
                  j                  | j                              }|t        t        dz    }t        j                  |      | _
        y )Nr   r2   )r#   r8   rollrC   absfftrfftCAVITY_LO_BINCAVITY_HI_BINmeanr=   )rD   indataframestimestatusfft_databinss          r   audio_callbackzMAPHS.audio_callback   s    &MGGD$5$5w?&,QTl6'(# 66"&&++d&7&789mAo6WWT]r   c                    | j                   t        d       kD  r:|| j                   kD  r| xj                  dz  c_        n| xj                  dz  c_        t        dt	        d| j                              | _        || _         | j                  S )Nr5   g{Gz?r4         ?)rA   r@   r?   maxmin)rD   gain_dbs     r   compute_controlzMAPHS.compute_control   sq    >>U5\M)'##t+###t+#!#s30C0C'DE """r   c                    t        d       t        j                  d      }|j                         st        d       y t        r8t	        j
                  | j                  dt        d      }|j                          nt        d       	 	 |j                         \  }}|snt        j                  |t        t        ft        j                        }t        j                  |t        j                        j!                  t"        j$                        d	z  }|j'                         }t)               }t+        j,                  d
      }	| j.                  j1                  |j*                  j3                  t+        j4                  t*        j6                              | j8                  j*                  j3                  t+        j4                  t*        j6                              t        t        | j:                  t+        j<                  |      |	       |j>                  d|j@                  z   z  }
dtB        z
  | jD                  z  tB        |
z  z   | _"        | jD                  dkD  r"dt#        jF                  | jD                        z  nd}| jI                  |      }|	jJ                  jM                         }t        d|dd|dd|j@                  dd|dd       t        jN                  dt        j                  |d             t        jP                  d      dz  tS        d      k(  rntU        jV                  dtX        z         |j]                          t        j^                          t        rja                          t        d       y # tZ        $ r t        d       Y \w xY w# |j]                          t        j^                          t        rja                          t        d       w xY w)Nz+MAPHS Python - Black Hole Energy Extractionr   zError: Could not open camera.r2   i   )callbackchannels
samplerate	blocksizezRunning without audio input.)interpolationg     o@   rV   gư>g      $@g      Yz[CTRL] mirror=z.3fz | Gain=z6.1fz dB | Winding=z | z<25 )endzMAPHS Monitor)i  i     qz
Interrupted by user.z

Shutdown.)1r#   cv2VideoCaptureisOpenedsdInputStreamrT   SAMPLE_RATEstartreadresizeGRID_WGRID_H
INTER_AREAcvtColorCOLOR_BGR2GRAYastyper8   r;   flattenr   r   create_string_bufferr-   r'   data_asr%   r   r<   r=   byrefr
   r	   	EMA_ALPHAr>   log10rZ   valuedecodeimshowwaitKeyordrP   sleepCONTROL_UPDATE_HZKeyboardInterruptreleasedestroyAllWindowsstop)rD   capstreamretframesmallgray	gray_flatmetrics
status_msg
super_gainrY   controlmsgs                 r   runz	MAPHS.run   s   ;<q!||~12^^T-@-@1/:cKFLLN010	! XXZ
U 

566*:#..Y||E3+=+=>EEbjjQTYY LLN	!)#88=
%%$$,,V^^FNN-KLNN))11&..2PQF&&LL) %..#2GH
!$yDMM AIPZDZ Z<@MMD<P$$--!88V\..w7 !&&--/(Xgd^>ZaZiZijmYnnqruvyqz{  BD  E 

?CJJuj,IJ;;q>D(CH4

3!223M V KKM!!#-  ! 	,*+	, KKM!!#- s&   J2M? ?NN NN AO N)r   r   r   rE   rT   rZ   r   r   r   r   r0   r0      s    A
+#>!r   r0   __main__)osr6   rP   r    r   numpyr8   rf   sounddeviceri   ImportErrorr#   ro   rp   r:   rk   rB   rK   rL   ry   r   r   	Structurer   r.   r0   r   appr   r   r   r   <module>r      s    	 
     
 
		 
q
f	f 	8d! d!L z
'CGGI q  	
LM	
CD	Bs   A9 9BB