# FEMM 5, встроенный MicroPython. Сгущение постоянного тока у входящего угла.
# Собственная постановка курса по мотивам видео ComProgExpert № 4.
# При запуске из редактора выберите рабочей папкой папку этого файла.
import os
import sys
import json
import math

script = globals().get('__file__', '') or (sys.argv[0] if sys.argv else '')
if script and script not in ('', '-c', '-'):
    os.chdir(os.path.dirname(os.path.abspath(script)))
if not 'results' in os.listdir('.'):
    os.mkdir('results')

rows = []
for h in (0.6, 0.3, 0.15):
    newdocument(3)
    ci_probdef('millimeters', 'planar', 0, 1e-9, 1, 30)
    ci_addmaterial('Copper', 58000000, 58000000, 1, 1, 0, 0)
    points = [(0, 0), (40, 0), (40, 10), (10, 10), (10, 40), (0, 40)]
    for x, y in points:
        ci_addnode(x, y)
    for index in range(len(points)):
        x1, y1 = points[index]
        x2, y2 = points[(index + 1) % len(points)]
        ci_addsegment(x1, y1, x2, y2)
    ci_addconductorprop('Supply', 0.001, 0, 1)
    ci_addconductorprop('Return', 0, 0, 1)
    ci_selectsegment(40, 5)
    ci_setsegmentprop('<None>', h, 0, 0, 0, 'Supply')
    ci_clearselected()
    ci_selectsegment(5, 40)
    ci_setsegmentprop('<None>', h, 0, 0, 0, 'Return')
    ci_clearselected()
    ci_addblocklabel(5, 5)
    ci_selectlabel(5, 5)
    ci_setblockprop('Copper', 0, h, 1)
    ci_clearselected()
    name = 'results/current-h-' + str(h)
    ci_saveas(name + '.fec')
    ci_analyze(1)
    ci_loadsolution()
    co_smooth('off')
    va, ia = co_getconductorproperties('Supply')
    vb, ib = co_getconductorproperties('Return')
    co_groupselectblock(1)
    power = float(complex(co_blockintegral(0)).real)
    co_clearblock()
    current = abs(complex(ia))
    samples = []
    for radius in (0.5, 1, 2, 4):
        x = 10 - radius / math.sqrt(2)
        values = co_getpointvalues(x, x)
        j = math.sqrt(abs(complex(values[1])) ** 2 + abs(complex(values[2])) ** 2)
        samples.append({'r_mm': radius, 'J_A_m2': j})
    row = {'h_mm': h, 'I_A': current, 'R_ohm': 0.001 / current,
           'P_W': power, 'P_terminal_W': 0.001 * current,
           'current_balance_A': abs(complex(ia) + complex(ib)),
           'power_relative_error': abs(power - 0.001 * current) / power,
           'samples': samples}
    rows.append(row)
    co_close()
    ci_close()

result = {'runtime': 'FEMM 5.0, embedded MicroPython, Current Flow DC',
          'source': 'Own six-edge L conductor; no dimensions copied from video',
          'conductivity_S_m': 58000000, 'depth_mm': 1, 'voltage_V': 0.001, 'rows': rows}
result['passed'] = max(row['power_relative_error'] for row in rows) < 1e-6 and max(row['current_balance_A'] for row in rows) < 1e-6
with open('results/result.json', 'w') as output:
    json.dump(result, output)
print(json.dumps(result))
assert result['passed']
