"""Потокосцепление пробной обмотки при вращении поля кольцевой модели."""
import math,json
opendocument('Обмотка-сосредоточенная.fem');mi_loadsolution();mo_smooth('off')
N=512;r=.095;length=.1;p=2;omega_m=2*math.pi*1500/60
A=[];Br=[]
for k in range(N):
    t=2*math.pi*k/N;c=math.cos(t);s=math.sin(t);v=mo_getpointvalues(r*1000*c,r*1000*s)
    A.append(complex(v[0]).real);Br.append(complex(v[1]).real*c+complex(v[2]).real*s)
mo_close();mi_close()
def amp(v,h):
    aa=sum(z*math.cos(2*math.pi*h*k/len(v)) for k,z in enumerate(v))*2/len(v)
    bb=sum(z*math.sin(2*math.pi*h*k/len(v)) for k,z in enumerate(v))*2/len(v)
    return math.sqrt(aa*aa+bb*bb)
def value(theta):
    x=(theta/(2*math.pi)*N)%N;j=int(x);f=x-j
    return A[j]*(1-f)+A[(j+1)%N]*f
upper=[1 if (j//3)%6==0 else -1 if (j//3)%6==3 else 0 for j in range(36)]
result={'speed_rpm':1500,'frequency_Hz':50,'receiver_radius_mm':95,'depth_mm':100,'source_model':'Обмотка-сосредоточенная.fem','source_solution':'Обмотка-сосредоточенная.ans','native_A_Wbpm':A,'native_Br_T':Br,'windings':[]}
for title,pitch in [('Полный шаг',9),('Укороченный шаг',8)]:
    weights=[upper[j]-upper[(j-pitch)%36] for j in range(36)]
    n=sum(abs(w) for w in weights)/2
    cw=sum(weights[j]*math.cos(p*2*math.pi*j/36) for j in range(36));sw=sum(weights[j]*math.sin(p*2*math.pi*j/36) for j in range(36))
    kw=math.sqrt(cw*cw+sw*sw)/(2*n)
    psi=[]
    for k in range(192):
        rotation=2*math.pi*k/192
        psi.append(length*sum(weights[j]*value(2*math.pi*j/36-rotation) for j in range(36)))
    harmonics=[omega_m*h*amp(psi,h)/math.sqrt(2) for h in range(1,49)]
    e1=harmonics[p-1];etotal=math.sqrt(sum(e*e for e in harmonics));theory=omega_m*p*n*kw*(2*r*length*amp(Br,p)/p)/math.sqrt(2)
    result['windings'].append({'title':title,'pitch_slots':pitch,'turns':n,'kw1':kw,'flux_Wbturn':psi,'E_harmonics_RMS_V':harmonics,'E1_from_flux_RMS_V':e1,'E1_from_B1_RMS_V':theory,'E_RMS_band1to48_V':etotal,'THD_band_Vratio':math.sqrt(max(0,etotal*etotal-e1*e1))/e1,'relative_error_E1':e1/theory-1})
with open('flux-result.json','w') as f:json.dump(result,f)
print('WINDING_FLUX_COMPLETE')
