clc; clear;

%% ============================================================
%  GOAL
%  ============================================================
% Design a finned-tube oil cooler that fits inside:
% 50 in x 50 in x 15 in
%
% Required:
% oil flow rate = 100 gal/min
% heat rejection = 440 kW
% target outlet oil temperature = 100 C
%
% This script estimates:
% required inlet temperature
% required UA
% fin efficiency
% number of fins needed
% whether the geometry fits
% predicted outlet temperature
%
% Notes:
% This is a first-pass heat transfer model.
% It does NOT model air pressure drop, fan curve, nonuniform flow,
% oil-side pressure drop, or air temperature rise through the core.
%% ============================================================


%% ============================================================
%  UNIT CONVERSIONS
%  ============================================================

inch_to_m = 0.0254;
gal_to_m3 = 0.00378541;


%% ============================================================
%  PACKAGE SIZE LIMITS
%  ============================================================

box_width  = 50*inch_to_m;   % [m]
box_height = 50*inch_to_m;   % [m]
box_depth  = 15*inch_to_m;   % [m]

fprintf("\n================ PACKAGE SIZE ================\n");
fprintf("Box width  = %.4f m\n", box_width);
fprintf("Box height = %.4f m\n", box_height);
fprintf("Box depth  = %.4f m\n", box_depth);


%% ============================================================
%  REQUIRED OIL-SIDE CONDITIONS
%  ============================================================

q_load = 440000;             % required heat rejection [W]
Vdot_gpm = 100;              % oil flow rate [gal/min]
Vdot = Vdot_gpm*gal_to_m3/60; % oil flow rate [m^3/s]

rho_oil = 860;               % oil density [kg/m^3]
cp_oil = 2000;               % oil specific heat [J/kg-K]

mdot = rho_oil*Vdot;         % oil mass flow rate [kg/s]
C_oil = mdot*cp_oil;         % oil heat capacity rate [W/K]

T_out_target = 100;          % desired oil outlet temperature [C]
T_air = 25;                  % ambient air temperature [C]

% Required inlet temperature from oil energy balance:
% q = mdot*cp*(T_in - T_out)
T_in_required = T_out_target + q_load/C_oil;

fprintf("\n================ REQUIRED OIL CONDITIONS ================\n");
fprintf("Oil flow rate = %.3f gal/min\n", Vdot_gpm);
fprintf("Oil flow rate = %.6f m^3/s\n", Vdot);
fprintf("Oil mass flow rate = %.4f kg/s\n", mdot);
fprintf("Oil heat capacity rate = %.2f W/K\n", C_oil);
fprintf("Required heat rejection = %.0f W\n", q_load);
fprintf("Target outlet temperature = %.2f C\n", T_out_target);
fprintf("Required inlet temperature = %.2f C\n", T_in_required);
fprintf("Required oil temperature drop = %.2f C\n", T_in_required - T_out_target);


%% ============================================================
%  REQUIRED UA USING LMTD
%  ============================================================
% Air is approximated as constant-temperature ambient air.
% This is optimistic if air heats up significantly through the cooler.

DeltaT_in = T_in_required - T_air;
DeltaT_out = T_out_target - T_air;

LMTD = (DeltaT_in - DeltaT_out)/log(DeltaT_in/DeltaT_out);

UA_required = q_load/LMTD;

fprintf("\n================ REQUIRED UA ================\n");
fprintf("DeltaT at oil inlet = %.2f K\n", DeltaT_in);
fprintf("DeltaT at oil outlet = %.2f K\n", DeltaT_out);
fprintf("LMTD = %.2f K\n", LMTD);
fprintf("Required UA = %.2f W/K\n", UA_required);


%% ============================================================
%  DESIGN CHOICES
%  ============================================================

% Pipe/tube geometry
OD_pipe = 1.315*inch_to_m;     % 1 in nominal pipe OD [m]
r1 = OD_pipe/2;                % pipe outer radius / fin base radius [m]

ID_pipe = 1.049*inch_to_m;     % approximate Sch 40 1 in pipe ID [m]
IR = ID_pipe/2;                % pipe inner radius [m]

L_tube = box_width;            % tube length [m], tubes run across width

% Fin geometry
t_fin = 0.125*inch_to_m;       % fin thickness [m], 1/8 in
fin_OD = 7.0*inch_to_m;        % annular fin outer diameter [m]
r2 = fin_OD/2;                 % annular fin outer radius [m]

% Material properties
k_fin = 205;                   % aluminum fin conductivity [W/m-K]
k_pipe = 200;                  % pipe conductivity [W/m-K]

% Convection assumptions
h_air = 150;                   % air-side convection coefficient [W/m^2-K]
h_oil = 500;                   % oil-side convection coefficient [W/m^2-K]

% Tube layout inside 50 in x 50 in x 15 in box
num_tubes_height = floor(box_height/fin_OD);
num_tubes_depth  = floor(box_depth/fin_OD);
num_tubes = num_tubes_height*num_tubes_depth;

% Choose fin spacing along each tube
fin_pitch = 0.3125*inch_to_m;   % center-to-center fin pitch [m], 5/16 in
num_fins_per_tube = floor(L_tube/fin_pitch);

% Actual used length by fins
used_length_per_tube = num_fins_per_tube*fin_pitch;

% Total number of fins
N_fins_total = num_tubes*num_fins_per_tube;

fprintf("\n================ DESIGN CHOICES ================\n");
fprintf("Pipe OD = %.4f m = %.3f in\n", OD_pipe, OD_pipe/inch_to_m);
fprintf("Pipe ID = %.4f m = %.3f in\n", ID_pipe, ID_pipe/inch_to_m);
fprintf("Tube length = %.4f m = %.2f in\n", L_tube, L_tube/inch_to_m);
fprintf("Fin OD = %.4f m = %.2f in\n", fin_OD, fin_OD/inch_to_m);
fprintf("Fin thickness = %.5f m = %.3f in\n", t_fin, t_fin/inch_to_m);
fprintf("Fin pitch = %.5f m = %.3f in\n", fin_pitch, fin_pitch/inch_to_m);
fprintf("Fins per tube = %d\n", num_fins_per_tube);
fprintf("Tubes in height direction = %d\n", num_tubes_height);
fprintf("Tubes in depth direction = %d\n", num_tubes_depth);
fprintf("Total tubes = %d\n", num_tubes);
fprintf("Total fins = %d\n", N_fins_total);


%% ============================================================
%  GEOMETRY FIT CHECKS
%  ============================================================

if num_tubes < 1
    error("No tubes fit. Reduce fin OD or increase box size.")
end

if fin_OD > box_height
    error("Fin OD is too large for box height.")
end

if fin_OD > box_depth
    error("Fin OD is too large for box depth.")
end

if t_fin >= fin_pitch
    error("Fin thickness is greater than or equal to fin pitch. No air gap between fins.")
end

air_gap = fin_pitch - t_fin;

fprintf("\n================ FIT CHECK ================\n");
fprintf("Air gap between fins = %.5f m = %.3f in\n", air_gap, air_gap/inch_to_m);
fprintf("Used tube length = %.4f m = %.2f in\n", used_length_per_tube, used_length_per_tube/inch_to_m);

if used_length_per_tube <= L_tube
    fprintf("Fin stack fits along tube length.\n");
else
    fprintf("Fin stack does NOT fit along tube length.\n");
end


%% ============================================================
%  ANNULAR FIN EFFICIENCY
%  ============================================================

m = sqrt(2*h_air/(k_fin*t_fin));

% Corrected outer radius for convective tip approximation
r2c = r2 + t_fin/2;

% Efficiency coefficient
C2 = (2*r1/m)/(r2c^2 - r1^2);

% Modified Bessel terms
K1_r1  = besselk(1, m*r1);
I1_r2c = besseli(1, m*r2c);

I1_r1  = besseli(1, m*r1);
K1_r2c = besselk(1, m*r2c);

I0_r1  = besseli(0, m*r1);
K0_r1  = besselk(0, m*r1);

eta_f = C2 * (K1_r1*I1_r2c - I1_r1*K1_r2c) / ...
             (I0_r1*K1_r2c + K0_r1*I1_r2c);

Af_single = 2*pi*(r2c^2 - r1^2);

fprintf("\n================ FIN RESULTS ================\n");
fprintf("m = %.4f 1/m\n", m);
fprintf("Corrected fin radius r2c = %.5f m\n", r2c);
fprintf("Single fin area = %.6f m^2\n", Af_single);
fprintf("Fin efficiency eta_f = %.4f\n", eta_f);
fprintf("Effective area per fin eta*A = %.6f m^2\n", eta_f*Af_single);


%% ============================================================
%  BARE PIPE AREA
%  ============================================================

% Bare exposed tube length per tube
bare_length_per_tube = L_tube - num_fins_per_tube*t_fin;

if bare_length_per_tube < 0
    error("Bare length is negative. Too many fins or fins too thick.")
end

Abare_per_tube = 2*pi*r1*bare_length_per_tube;
Abare_total = num_tubes*Abare_per_tube;

fprintf("\n================ BARE PIPE AREA ================\n");
fprintf("Bare length per tube = %.4f m\n", bare_length_per_tube);
fprintf("Bare pipe area total = %.6f m^2\n", Abare_total);


%% ============================================================
%  AIR-SIDE EFFECTIVE AREA AND RESISTANCE
%  ============================================================

A_fin_effective_total = N_fins_total*eta_f*Af_single;

A_effective_air = A_fin_effective_total + Abare_total;

R_air = 1/(h_air*A_effective_air);

fprintf("\n================ AIR-SIDE RESULTS ================\n");
fprintf("Effective fin area total = %.3f m^2\n", A_fin_effective_total);
fprintf("Effective total air-side area = %.3f m^2\n", A_effective_air);
fprintf("Air-side resistance = %.6f K/W\n", R_air);
fprintf("Air-side UA only = %.2f W/K\n", 1/R_air);


%% ============================================================
%  OIL-SIDE CONVECTION AND PIPE CONDUCTION
%  ============================================================

% Oil flows through all tubes in parallel.
% Total inside area:
A_oil_total = num_tubes*2*pi*IR*L_tube;

R_oil = 1/(h_oil*A_oil_total);

% Pipe conduction through all tubes in parallel:
R_pipe_single = log(r1/IR)/(2*pi*k_pipe*L_tube);
R_pipe_total = R_pipe_single/num_tubes;

fprintf("\n================ OIL AND PIPE RESULTS ================\n");
fprintf("Total inner oil area = %.6f m^2\n", A_oil_total);
fprintf("Oil-side resistance = %.6f K/W\n", R_oil);
fprintf("Pipe conduction resistance = %.6f K/W\n", R_pipe_total);


%% ============================================================
%  TOTAL UA
%  ============================================================

R_total = R_oil + R_pipe_total + R_air;
UA_design = 1/R_total;

fprintf("\n================ TOTAL UA ================\n");
fprintf("Total thermal resistance = %.6f K/W\n", R_total);
fprintf("Design UA = %.2f W/K\n", UA_design);
fprintf("Required UA = %.2f W/K\n", UA_required);
fprintf("UA ratio design/required = %.3f\n", UA_design/UA_required);


%% ============================================================
%  HEAT REJECTION AT TARGET TEMPERATURES
%  ============================================================

q_possible_at_target = UA_design*LMTD;

fprintf("\n================ TARGET CHECK ================\n");
fprintf("Heat rejection possible at target temps = %.0f W\n", q_possible_at_target);
fprintf("Required heat rejection = %.0f W\n", q_load);
fprintf("Percent of required heat rejected = %.2f %%\n", q_possible_at_target/q_load*100);

if q_possible_at_target >= q_load
    fprintf("Result: This design may be able to reject the required heat load.\n");
else
    fprintf("Result: This design is undersized for the required heat load.\n");
end


%% ============================================================
%  PREDICT OUTLET TEMP FROM REQUIRED INLET TEMP
%  ============================================================
% Uses NTU model with air treated as constant temperature reservoir.

T_out_predicted = T_air + ...
    (T_in_required - T_air)*exp(-UA_design/C_oil);

q_removed_predicted = C_oil*(T_in_required - T_out_predicted);

fprintf("\n================ OUTLET PREDICTION ================\n");
fprintf("Required inlet oil temperature = %.2f C\n", T_in_required);
fprintf("Predicted outlet oil temperature = %.2f C\n", T_out_predicted);
fprintf("Target outlet oil temperature = %.2f C\n", T_out_target);
fprintf("Predicted heat removed = %.0f W\n", q_removed_predicted);

if T_out_predicted <= T_out_target
    fprintf("The design cools to the target outlet temperature or below.\n");
    fprintf("If exact 100 C outlet is required, reduce fan speed, bypass some oil, or reduce active area.\n");
else
    fprintf("The design does not cool enough to reach the target outlet temperature.\n");
end


%% ============================================================
%  TEMPERATURES IN FAHRENHEIT
%  ============================================================

T_in_required_F = T_in_required*9/5 + 32;
T_out_target_F = T_out_target*9/5 + 32;
T_out_predicted_F = T_out_predicted*9/5 + 32;
T_air_F = T_air*9/5 + 32;

fprintf("\n================ TEMPERATURES IN F ================\n");
fprintf("Ambient air temperature = %.2f F\n", T_air_F);
fprintf("Required inlet oil temperature = %.2f F\n", T_in_required_F);
fprintf("Target outlet oil temperature = %.2f F\n", T_out_target_F);
fprintf("Predicted outlet oil temperature = %.2f F\n", T_out_predicted_F);