%% MATCHED COPY — original pasted attachment unchanged
% Default: X-only 175 uT, 100 turns each, 16 AWG, exact ZotField geometry.
% Outer envelope enlarged to 1538 mm to preserve a 1524 mm MEAN X side.
% If 1524 mm is a hard OUTER envelope, revise BOTH calculators' geometry.
% Native MATLAB execution unavailable here. Translated numerical tests passed.
% The 3-D box metric is retained and is NOT ZotField's axial metric.
% Legacy equivalent_square_LM helper is retained but NOT USED.
clear; clc;
%% THREE-AXIS SQUARE HELMHOLTZ CAGE DESIGN CALCULATOR

% Modified from the user's original Calculator.pdf design workflow.

% MATLAB R2017b or newer (vecnorm is used). All coil pairs comprise two SQUARE coils.

% Each axis is a separate DC series circuit; currents can be signed.

% Calculates: turns, design current, actual field/uniformity, wire length,

% DC resistance, voltage, power, approximate self+mutual pair inductance.

% IMPORTANT: Inductance is a lumped thin-filament approximation, NOT a

% validated winding-resolved model. Magnetic core, heat, leads, driver,

% inter-axis mutual coupling and switching transients are not modeled.



%% 1. USER INPUTS (millimeters, amperes, millitesla)

cage_outer_side_mm = 1538;        % cubic outer envelope (5 ft)

% Square OUTER winding-frame sides, one size per axis; nested geometry.

loop_outer_side_mm = [1538 1512.6 1487.2]; % X, Y, Z

pair_spacing_mm = [829.8275130092816 815.9970799825431 802.1666520746139];            % [] = 0.5445*MEAN loop side per axis

                                    % or set [dx dy dz] explicitly

uniform_region_size_mm = [100 100 200]; % 2U CubeSat test box (NOT magnetic)

uniform_region_center_mm = [0 0 0];

target_field_mT = 0.175;             % magnitude of specified field vector

requested_direction = [1 0 0];  % e.g. Z field; normalized below

uniformity_tolerance_percent = 1;

operating_current_A = 1.7;         % DESIRED design current for sizing turns

max_axis_current_A = 2.5;          % safety/design constraint, NOT the drive

% Winding parameters: 16 AWG copper example

turns_per_layer = 10;            % turns in each axial pack layer

wire_pitch_mm = 1.4;            % INCLUDING insulation, must exceed bare

bare_copper_diameter_mm = .127*92^((36-16)/39);

resistance_per_m_20C = 1.724e-8/(pi*(bare_copper_diameter_mm/2000)^2);  % ohm/m, 16 AWG copper at 20 deg C

lead_length_per_coil_m = 0;

min_region_clearance_mm = 10;

min_frame_clearance_mm = 1;      % approximate nest-side clearance

max_design_iterations = 12;

% numerical accuracy/performance

check_points_per_axis = 7;       % 7^3 samples across the 2U region

inductance_segments_per_side = 32; % more segments -> better L estimate

% Manual evaluation DOES NOT re-design turns.

% Each row is [Ix Iy Iz] (A); [] includes only designed target case.

manual_currents_A = [1 0 0; 0 1 0; 0 0 1];

show_plots = true;



%% 2. INPUT CHECKS

assert(isscalar(cage_outer_side_mm) && cage_outer_side_mm>0);

assert(numel(loop_outer_side_mm)==3 && all(loop_outer_side_mm>0));

assert(all(loop_outer_side_mm<=cage_outer_side_mm), ...

    'Square coil outer sides must fit inside cage_outer_side_mm.');

assert(numel(uniform_region_size_mm)==3 && all(uniform_region_size_mm>0));

assert(numel(uniform_region_center_mm)==3);

assert(target_field_mT>0 && operating_current_A>0 && max_axis_current_A>0);

assert(operating_current_A<=max_axis_current_A, ...

    'Operating current exceeds the maximum allowable axis current.');

assert(norm(requested_direction)>0);

assert(turns_per_layer>=1 && turns_per_layer==round(turns_per_layer));

assert(wire_pitch_mm>=bare_copper_diameter_mm && bare_copper_diameter_mm>0);

assert(check_points_per_axis>=3 && inductance_segments_per_side>=8);

assert(isempty(pair_spacing_mm) || (numel(pair_spacing_mm)==3 && all(pair_spacing_mm>0)));

assert(isempty(manual_currents_A) || size(manual_currents_A,2)==3);

requested_direction = requested_direction(:).'/norm(requested_direction);

S = loop_outer_side_mm(:)'/1000;

pitch = wire_pitch_mm/1000;

mu0 = 4*pi*1e-7;

% Winding packs modeled as successive square filament loops, stacked inward.

% Pair windings have identical geometry, driven in aiding series connection.

% Use complete layers and choose minimum turns meeting target at or BELOW

% desired operating current. Current can be reduced after integer rounding.



%% 3. FIXED GEOMETRY FOR ZOTFIELD PARITY (no automatic turn redesign)
turns=[100 100 100];
pack_depth=(turns/turns_per_layer)*pitch;
mean_side=S-pack_depth;
separation=pair_spacing_mm/1000;
gain=zeros(1,3);
for a=1:3
 gain(a)=norm(square_pair_wound([0 0 0],a,S(a),separation(a),turns(a),turns_per_layer,pitch));
end
actual_required_A=target_field_mT*1e-3./gain;

%% 4. GEOMETRY CONSTRAINT CHECKS

pack_depth=(turns/turns_per_layer)*pitch;

mean_side=S-pack_depth;

% Pair center positions must fit winding pack axial width inside cube.

pack_width=turns_per_layer*pitch;

envelope_ok=all(S<=cage_outer_side_mm/1000+1e-12) && ...

    all(separation+pack_width<=cage_outer_side_mm/1000+1e-12);

% Conservative 2U bounding test: check test-box projection into all 3

% coil plane openings, based on innermost square winding sides.

region_extent=(abs(uniform_region_center_mm)+uniform_region_size_mm/2)/1000;

opening_gap=zeros(1,3);

for a=1:3

    inplane=setdiff(1:3,a);

    opening_gap(a)=1000*(S(a)-2*pack_depth(a))/2-1000*max(region_extent(inplane));

end

region_ok=all(opening_gap>=min_region_clearance_mm);

% Approximate frame nesting check (NOT complete 3D winding interference CAD).

frame_gap=1000*(S(1:2)-S(2:3))/2;

frame_ok=all(frame_gap>=min_frame_clearance_mm);

geometry_ok=envelope_ok && region_ok && frame_ok;

if ~geometry_ok

    warning('GEOMETRY CHECK FAILED: adjust sides, winding layers, or clearances.');

end



%% 5. FIELD RESPONSE / 3-D UNIFORMITY VERIFICATION

% Measure spatial variation for arbitrary directions with 3-axis basis.

ng=check_points_per_axis;

q=linspace(-0.5,0.5,ng);

[xg,yg,zg]=ndgrid(q,q,q);

points=[xg(:) yg(:) zg(:)].*(uniform_region_size_mm/1000) ...

       +uniform_region_center_mm/1000;

points=[points; uniform_region_center_mm/1000];

nb=size(points,1);

G=zeros(3*nb,3); % field per A, rows = [Bx(all);By(all);Bz(all)]

for a=1:3

    Baxis=square_pair_wound(points,a,S(a),separation(a),turns(a),turns_per_layer,pitch);

    G(:,a)=Baxis(:);

end

centerG=zeros(3,3);

for a=1:3

    centerG(:,a)=square_pair_wound(uniform_region_center_mm/1000,a, ...

        S(a),separation(a),turns(a),turns_per_layer,pitch).';

end

% Current vector to match requested target field at center:

target_B=target_field_mT*1e-3*requested_direction.';

I_design=centerG\target_B;

% The actual target case and any manual currents use fixed turns.

case_currents=[I_design.';manual_currents_A];

case_labels=[{'Target field'}; arrayfun(@(k) sprintf('Manual %d',k), ...

    (1:size(manual_currents_A,1)).','UniformOutput',false)];

% Worst relative FIELD-SHAPE error for any desired orientation at magnitude

% target_field_mT, using the center current-response calibration matrix.

response=G/centerG; % one basis per Cartesian target-field component

worst_error=0;

for p=1:nb

    rows=p+[0 nb 2*nb];

    worst_error=max(worst_error,100*norm(response(rows,:)-eye(3),2));

end

uniform_ok=worst_error<=uniformity_tolerance_percent;

I_basis=centerG\(target_field_mT*1e-3*eye(3));

worst_axis_current=sqrt(sum(I_basis.^2,2));

current_ok=all(worst_axis_current<=max_axis_current_A+1e-8) && ...

           all(abs(I_design)<=max_axis_current_A+1e-8);



%% 6. ELECTRICAL OUTPUTS

wire_length=zeros(1,3);

for a=1:3

    radii_side=S(a)-2*((0:(turns(a)/turns_per_layer-1))+0.5)*pitch;

    wire_length(a)=2*turns_per_layer*sum(4*radii_side)+2*lead_length_per_coil_m;

end

R=wire_length*resistance_per_m_20C;

V_cases=case_currents.*R;

P_cases=(case_currents.^2).*R;

current_density=abs(case_currents)/(pi*(bare_copper_diameter_mm/2)^2);

% Inductance: equivalent one-turn square at mean side, replace N turns

% with N coincident turns per coil. Series-aiding inductance:

% Matched model uses actual per-turn self and mutual inductance.

% Self integral uses regularization at copper radius to avoid divergence;

% this is approximate for discrete-layer coils, especially many turns.

Lpair=zeros(1,3);

for a=1:3

    c.inner_mm=1000*(S(a)/2-(turns(a)/turns_per_layer)*pitch);
    c.radial=turns(a)/turns_per_layer; c.axial=turns_per_layer;
    c.pitch_mm=wire_pitch_mm; c.bare_mm=bare_copper_diameter_mm;
    c.d=separation(a);
    [~,~,Lpair(a)]=finiteInductance(c);

end



%% 7. REPORT

fprintf('\n=========== THREE-AXIS SQUARE HELMHOLTZ CAGE ===========\n');

fprintf('Outer cubic envelope: %.1f mm; target B: %.3f mT\n', ...

    cage_outer_side_mm,target_field_mT);

fprintf('Design current: %.3f A; maximum allowed: %.3f A\n', ...

    operating_current_A,max_axis_current_A);

fprintf('Sampled worst-direction uniformity error: %.4f%% (limit %.3f%%)\n', ...

    worst_error,uniformity_tolerance_percent);

status={'FAIL','PASS'};

fprintf('Uniformity %s | Electrical limit %s | Approx geometry %s\n', ...

    status{1+uniform_ok},status{1+current_ok},status{1+geometry_ok});

axis_names={'X';'Y';'Z'};

result=table(axis_names,1000*S(:),1000*separation(:),turns(:), ...

    (turns(:)/turns_per_layer),pack_depth(:)*1000, ...

    R(:),Lpair(:)*1000,wire_length(:),I_design, ...

    R(:).*I_design,R(:).*I_design.^2,worst_axis_current, ...

    'VariableNames',{'Axis','SquareOuterSide_mm','PairSpacing_mm', ...

    'TurnsPerCoil','RadialLayers','PackDepth_mm','PairResistance_ohm', ...

    'PairInductanceApprox_mH','PairCopperLength_m', ...

    'TargetCurrent_A','TargetDCVoltage_V','TargetPower_W', ...

    'WorstAxisCurrentAnyDirection_A'});

disp(result);

case_data=zeros(size(case_currents,1),3);

max_case_error=zeros(size(case_currents,1),1);

for k=1:size(case_currents,1)

    case_data(k,:)=(centerG*case_currents(k,:).').'*1000;

    btest=reshape(G*case_currents(k,:).',nb,3);

    cref=case_data(k,:)/1000;

    max_case_error(k)=100*max(vecnorm(btest-cref,2,2))/max(norm(cref),eps);

end

case_results=table(case_labels,case_currents(:,1),case_currents(:,2),case_currents(:,3), ...

    case_data(:,1),case_data(:,2),case_data(:,3), ...

    V_cases(:,1),V_cases(:,2),V_cases(:,3),sum(P_cases,2),max_case_error, ...

    'VariableNames',{'Case','Ix_A','Iy_A','Iz_A','BxCenter_mT', ...

    'ByCenter_mT','BzCenter_mT','Vx_DC_V','Vy_DC_V','Vz_DC_V', ...

    'TotalPower_W','MaxRelativeVectorVariation_pct'});

disp(case_results);

fprintf('Copper length all pairs: %.1f m; copper mass approx %.1f kg\n', ...

    sum(wire_length),sum(wire_length)*pi*(bare_copper_diameter_mm/2000)^2*8960);

if any(any(abs(case_currents)>max_axis_current_A)), warning('One or more evaluated cases exceed current limit.'); end

fprintf('Region-to-winding gaps per axis (mm): [%g %g %g]\n',opening_gap);

fprintf(['NOTE: inductance uses actual-turn thin-wire self/mutual estimates; ' ...

    'it excludes inter-axis coupling.\n']);

fprintf(['NOTE: DC voltage = I*R. Switching requires additional L*dI/dt ' ...

    'and suitable driver margin.\n']);

fprintf('NOTE: Geometry validation is approximate; perform 3D CAD collision checks.\n');



%% 8. OPTIONAL PLOTS

if show_plots

    figure('Color','w','Name','Field variation in CubeSat region');

    Bz=reshape(G(:,3),nb,3);

    scatter3(points(1:end-1,1)*1000,points(1:end-1,2)*1000, ...

        points(1:end-1,3)*1000,28,vecnorm(Bz(1:end-1,:),2,2)*1000,'filled');

    colorbar; axis equal; grid on;

    xlabel('X (mm)');ylabel('Y (mm)');zlabel('Z (mm)');

    title('Field magnitude (mT), Z-axis pair at 1 A');

end



%% LOCAL FUNCTIONS (MATLAB R2016b+)

function B = square_pair_wound(P,axisID,outerSide,d,N,nAxial,pitch)
 if isvector(P),P=reshape(P,1,3);end
 B=zeros(size(P));
 assert(mod(N,nAxial)==0,'Turns must form complete layers.');
 for j=1:N/nAxial
  side=outerSide-2*(j-.5)*pitch;
  for k=0:nAxial-1
   shifted=P; shifted(:,axisID)=shifted(:,axisID)-(k-(nAxial-1)/2)*pitch;
   B=B+square_pair_field(shifted,axisID,side,d,1);
  end
 end
end

function B=square_pair_field(P,axisID,side,d,I)

    if isvector(P),P=reshape(P,1,3);end

    % Local [v1 v2 normal] frame, cyclic axis permutations preserve sign.

    switch axisID

        case 1, Q=P(:,[2 3 1]);

        case 2, Q=P(:,[3 1 2]);

        case 3, Q=P;

    end

    Bl=single_square_field(Q,side,d/2,I)+single_square_field(Q,side,-d/2,I);

    switch axisID

        case 1, B=Bl(:,[3 1 2]);

        case 2, B=Bl(:,[2 3 1]);

        case 3, B=Bl;

    end

end



function B=single_square_field(Q,side,z0,I)

    a=side/2;

    C=[a -a z0;a a z0;-a a z0;-a -a z0];

    B=zeros(size(Q));

    for k=1:4

        A=C(k,:);D=C(mod(k,4)+1,:);

        v=D-A; len=norm(v);eh=v/len;

        r=Q-A;t=r*eh.';

        cr=cross(repmat(eh,size(Q,1),1),r,2);

        h2=sum(cr.^2,2);h2=max(h2,1e-24);

        factor=(len-t)./sqrt((len-t).^2+h2)+t./sqrt(t.^2+h2);

        B=B+(1e-7*I)*(cr./h2).*factor;

    end

end



function [Lself,M12]=equivalent_square_LM(side,d,wireRadius,nPerSide)

    % Regularized midpoint Neumann quadrature for two ideal square loops.

    [r,dl]=square_segments(side,0,nPerSide);

    [r2,dl2]=square_segments(side,d,nPerSide);

    % Conductor-radius regularization gives an indicative effective Lself.

    dr=reshape(r,[],1,3)-reshape(r,1,[],3);

    rr=sqrt(sum(dr.^2,3)+wireRadius^2);

    dd=dl*dl.';

    Lself=1e-7*sum(dd(:)./rr(:));

    dr12=reshape(r,[],1,3)-reshape(r2,1,[],3);

    rr12=sqrt(sum(dr12.^2,3));

    rr12=max(rr12,1e-12);

    M12=1e-7*sum(dd(:)./rr12(:));

end



function [centers,dl]=square_segments(side,z,n)

    a=side/2;

    vertices=[-a -a z;a -a z;a a z;-a a z;-a -a z];

    centers=zeros(4*n,3);dl=zeros(4*n,3);

    for edge=1:4

        delta=(vertices(edge+1,:)-vertices(edge,:))/n;

        rows=(edge-1)*n+(1:n);

        centers(rows,:)=vertices(edge,:)+((1:n)'-0.5)*delta;

        dl(rows,:)=repmat(delta,n,1);

    end

end

function ts=turnList(c)
ts=zeros(c.radial*c.axial,2); n=0;
for j=0:c.radial-1
 for k=0:c.axial-1
  n=n+1; ts(n,:)=[(c.inner_mm+(j+.5)*c.pitch_mm)/1000, (k-(c.axial-1)/2)*c.pitch_mm/1000];
 end
end
end

function [single,M,total]=finiteInductance(c)
ts=turnList(c); n=size(ts,1); single=0; M=0;
for i=1:n
 r=ts(i,1); z=ts(i,2); g=c.bare_mm/2000*exp(-.25);
 single=single+4*segmentMutual(2*r,2*r,g)-4*segmentMutual(2*r,2*r,2*r);
 for j=1:i-1
  single=single+2*squareMutual(r,ts(j,1),z-ts(j,2));
 end
 for j=1:n
  M=M+squareMutual(r,ts(j,1),c.d+ts(j,2)-z);
 end
end
total=2*(single+M);
end
function v=squareMutual(r1,r2,z)
v=4*(segmentMutual(2*r1,2*r2,hypot(r1-r2,z))-segmentMutual(2*r1,2*r2,hypot(r1+r2,z)));
end
function v=segmentMutual(l1,l2,D)
f=@(x) x.*asinh(x/D)-hypot(x,D);
v=2e-7*(f((l1+l2)/2)-f((l1-l2)/2));
end

