# Execute with FEMM5 native embeddedMicroPython from this extracted folder.
import os
def _exists(p):
    try:os.stat(p);return True
    except OSError:return False
if _exists('files/reproduce.py'):os.chdir('files')
elif '__file__' in globals() and '/' in __file__.replace('\\','/'):os.chdir(__file__.replace('\\','/').rsplit('/',1)[0])

import os
_inputs=['gap-refined-source-model.fem', 'practice-ii05-1-source-model.fem', 'ring-effective-source-model.fem', 'uniformT10.0-source-model.fem', 'uniformT100.0-source-model.fem', 'uniformT110.0-source-model.fem', 'uniformT20.0-source-model.fem', 'uniformT30.0-source-model.fem', 'uniformT90.0-source-model.fem']
os.mkdir('rebuild-frequency-matrix-output')
for _name in _inputs:
 with open(_name,'rb') as _f:_bytes=_f.read()
 with open('rebuild-frequency-matrix-output/'+_name,'wb') as _f:_f.write(_bytes)
os.chdir('rebuild-frequency-matrix-output')
import json,os,sys,time,math,cmath
import numpy as np
CONFIG={'output': 'rebuild-frequency-matrix-native-result.json', 'directories': {'practice-ii05-1': '.'}, 'models': {'./practice-ii05-1-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './gap-refined-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './ring-effective-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT10.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT100.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT110.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT20.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT30.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}, './uniformT90.0-source-model.fem': {'problem': 'planar', 'depth': 100.0, 'angle': 20.0, 'circuits': ['Фаза А', 'Фаза В', 'Фаза С']}}}
DATA={'runtime':sys.version,'implementation':str(sys.implementation),'experiments':{},'field_solutions':0}
assert sys.implementation.name=='micropython'
def save():
    with open(CONFIG['output'],'w') as f:json.dump(DATA,f)
def serial(v):
    if isinstance(v,complex):return [v.real,v.imag]
    if isinstance(v,(tuple,list)):return [serial(x) for x in v]
    if isinstance(v,dict):return {k:serial(x) for k,x in v.items()}
    return v
def close():
    for n in ('mo_close','mi_close'):
        try:globals()[n]()
        except Exception:pass
def start(name):
    close();d=CONFIG['directories'][name];os.chdir(d);return d
def model(name):return './'+name+'-source-model.fem'
def solve(path,tag,currents=None,frequency=None,rotate=0,group=2,mesh=None,material=None):
    close();opendocument(path);mi_saveas(os.getcwd()+'/'+tag+'.fem')
    if frequency is not None:
        info=CONFIG['models'][path]
        mi_probdef(frequency,'millimeters',info['problem'],1e-8,info['depth'],info['angle'])
    if rotate:
        mi_selectgroup(group);mi_moverotate(0,0,rotate);mi_clearselected()
    if material:
        x,y,material_name=material;mi_selectlabel(x,y);mi_setblockprop(material_name,0,1,'',0,0,0);mi_clearselected()
    if mesh:
        for x,y,mat,sz,circ,mag,g,turns in mesh:
            mi_selectlabel(x,y);mi_setblockprop(mat,0,sz,circ,mag,g,turns);mi_clearselected()
    if currents:
        for name,value in currents:mi_modifycircprop(name,1,value)
    mi_analyze(1);mi_loadsolution();DATA['field_solutions']+=1
    info={'file':os.getcwd()+'/'+tag+'.fem','nodes':mo_numnodes(),'elements':mo_numelements(),'circuits':{}}
    for name in CONFIG['models'][path]['circuits']:
        info['circuits'][name]=list(mo_getcircuitproperties(name))
    mo_clearblock();mo_groupselectblock();info['energy_J']=mo_blockintegral(2);info['coenergy_J']=mo_blockintegral(17)
    info['loss_magnetic_W']=mo_blockintegral(3);info['loss_resistive_W']=mo_blockintegral(4);info['loss_total_W']=mo_blockintegral(6)
    mo_clearblock()
    try:
        mo_groupselectblock(group);info['torque_Nm']=mo_blockintegral(22);info['force_x_N']=mo_blockintegral(18);info['force_y_N']=mo_blockintegral(19);mo_clearblock()
    except Exception as error:info['force_error']=str(error)
    return info
def real(x):return complex(x).real
def add(name,value):DATA['experiments'][name]=serial(value);save()
def z_matrix(path,prefix,names):
    columns=[];evidence=[]
    for j in range(len(names)):
        row=solve(path,prefix+'-basis-'+str(j),[(n,1 if j==k else 0) for k,n in enumerate(names)])
        columns.append([complex(row['circuits'][n][1]) for n in names]);evidence.append(row)
    return [[columns[j][i] for j in range(len(names))] for i in range(len(names))],evidence
def linear_load(path,prefix,names,Z,rloads,rprimary,source,neutral=False):
    n=len(names);m=n+1 if neutral else n
    matrix=[[0j for j in range(m)] for i in range(m)]
    rhs=[0j]*m
    for i in range(n):
        for j in range(n):matrix[i][j]=Z[i][j]
        if i<n//2:matrix[i][i]+=rprimary;rhs[i]=source[i]
        else:
            matrix[i][i]+=rloads[i-n//2]
            if neutral:matrix[i][n]=1
    if neutral:
        for j in range(n//2,n):matrix[n][j]=1
    answer=np.linalg.solve(np.array(matrix),np.array(rhs));currents=[complex(answer[j]) for j in range(n)]
    row=solve(path,prefix,[(n,currents[j]) for j,n in enumerate(names)])
    voltages=[complex(row['circuits'][n][1]) for n in names]
    residual=[]
    for i in range(n):
        r=voltages[i]+(rprimary if i<n//2 else rloads[i-n//2])*currents[i]-(source[i] if i<n//2 else 0)
        if neutral and i>=n//2:r+=complex(answer[n])
        residual.append(r)
    row['current_A']=currents;row['voltage_V']=voltages;row['residual_V']=residual
    row['source_power_W']=sum(real(source[i]*currents[i].conjugate())/2 for i in range(n//2))
    row['external_primary_copper_W']=sum(rprimary*abs(currents[i])**2/2 for i in range(n//2))
    row['load_power_W']=sum(rloads[i-n//2]*abs(currents[i])**2/2 for i in range(n//2,n))
    row['neutral_current_A']=-sum(currents[n//2:]);row['neutral_potential_V']=complex(answer[n]) if neutral else 0
    row['power_balance_W']=row['source_power_W']-row['external_primary_copper_W']-row['load_power_W']-real(row['loss_total_W'])
    return row

def count_conductors():
    n=0
    for j in range(1,int(mo_numelements())+1):
        e=mo_getelement(j)
        if int(e[6])==4 and complex(mo_getpointvalues(e[3],e[4])[3]).real>0:n+=1
    return n

def restore(z):return complex(z[0],z[1]) if isinstance(z,list) else complex(z)
def tensor_torque(N):
    radius=.040375;depth=.1;delta=(math.pi/2)/N;total=0.
    for k in range(N):
        a=(k+.5)*delta;c=math.cos(a);s=math.sin(a);p=mo_getpointvalues(radius*1000*c,radius*1000*s);bx=complex(p[1]);by=complex(p[2]);br=bx*c+by*s;bt=-bx*s+by*c;total+=real(br*bt.conjugate())*.5
    return 4*depth*radius*radius/(4*math.pi*1e-7)*total*delta
try:
    name='practice-ii05-1';start(name);path=model(name);names=CONFIG['models'][path]['circuits'];matrix_rows=[]
    DATA['experiments']['induction_matrix_series']={'rows':matrix_rows,'status':'running','sector_count':4,'source_sector_deg':90,'phase_convention':'source B +120deg, C -120deg','amplitude_convention':True}
    for frequency in (.5,1.,2.,3.,4.,5.,7.5):
        cols=[];raw=[]
        for j in range(3):
            r=solve(path,'matrix-current',[(n,1 if k==j else 0) for k,n in enumerate(names)],frequency)
            r.pop('file');r['input_frequency_Hz']=frequency;r['input_basis_port']=j;cols.append([complex(r['circuits'][n][1]) for n in names]);raw.append(r)
        Z=[[cols[j][i] for j in range(3)] for i in range(3)];matrix_rows.append(serial({'frequency_Hz':frequency,'Z_sector_ohm':Z,'basis':raw,'conductor_elements':count_conductors()}));save()
    # Original balanced-current rotor-bar extraction; 8 bars in a 90-degree sector.
    balanced=[cmath.exp(2j*math.pi*k/3) for k in range(3)];r=solve(path,'rotor-ring-control',list(zip(names,balanced)),1.)
    bar_points=[(.9,33.5),(7.3,32),(15,29.6),(20.2,25.8),(25.8,20.6),(29,14),(31.2,6.7),(31.6,.3)];bar=[]
    for x,y in bar_points:
        mo_clearblock();mo_selectblock(x,y);bar.append(complex(mo_blockintegral(7)))
    mo_clearblock();r['bar_currents_sector_A']=bar;r['airgap_torque_full_Nm_128']=tensor_torque(128);r['airgap_torque_full_Nm_256']=tensor_torque(256)
    full_bars=[]
    # Antiperiodic continuation reverses the axial current every quarter-turn.
    for quadrant in range(4):full_bars.extend([z*((-1)**quadrant) for z in bar])
    cumulative=[];running=0j
    for z in full_bars:running+=z;cumulative.append(running)
    mean=sum(cumulative)/len(cumulative);ring=[z-mean for z in cumulative]
    ring_radius=.036;ring_area=50e-6;rho_al=1/(34.45e6);Rseg=rho_al*2*math.pi*ring_radius/32/ring_area;ring_loss=sum(Rseg*abs(z)**2 for z in ring)
    r['ring_assumptions']={'radius_m':ring_radius,'section_m2':ring_area,'conductivity_S_m':34.45e6,'bars_full':32,'rings':2,'origin':'Explicit illustrative end-ring geometry chosen for this course model; not a measured motor passport.'};r['ring_segment_R_20_ohm']=Rseg;r['ring_branch_currents_A']=ring;r['bar_KCL_sum_A']=sum(full_bars);r['ring_loss_full_W']=ring_loss;r['bar_loss_full_W']=4*real(r['loss_resistive_W']);r['ring_to_bar_loss_ratio']=ring_loss/max(r['bar_loss_full_W'],1e-30)
    add('induction_ring',r)
    DATA['experiments']['induction_matrix_series']['status']='complete';save()
except Exception as error:
    DATA['fatal_error']=str(error);save()
finally:close()
save()

assert 'fatal_error' not in DATA,DATA.get('fatal_error')
