Okay, this is a common and important task in RF/microwave engineering. Directly inverting S-parameters at each frequency point using methods like Nicolson-Ross-Weir (NRW) is indeed prone to issues at resonant thicknesses (nλ/2 in the material, which relates to λ/4 issues in some formulations).
The most robust way to avoid these issues is to use an optimization-based approach. You assume a model for your material properties (e.g., frequency-independent εr and μr, or a simple dispersion model like Debye), calculate the expected S-parameters based on these assumed properties and your sample thickness, and then optimize your assumed properties until the calculated S-parameters match the measured ones as closely as possible across the entire frequency band.
Here's a MATLAB script that implements this concept. It will:
Read a Touchstone file (S2P).
Ask for the sample thickness.
Use an optimization routine (lsqnonlin or fminsearch) to find the best-fit frequency-independent complex permittivity (εr* = εr' - jεr'') and permeability (μr* = μr' - jμr'').
Plot the results.
Assumptions for this script:
The material is homogeneous and isotropic.
The sample has flat, parallel faces and is of uniform thickness.
The measurement is a well-calibrated free-space measurement (plane wave incidence).
For simplicity, this initial script assumes εr and μr are constant over the measured frequency range. This is often a reasonable approximation for non-resonant materials over moderate bandwidths. For highly dispersive materials, you'd need to fit parameters of a dispersion model (e.g., Debye, Lorentz).
The script uses the convention ε* = ε' - jε'' (so ε'' > 0 for loss).
matlab
% --- Main Script: extract_material_properties.m ---
clear; clc; close all;
% --- User Inputs ---
touchstoneFile = 'sample_data.s2p'; % Replace with your .s2p file name
thickness_m = 0.005; % Sample thickness in meters (e.g., 5 mm)
% --- Constants ---
c0 = 299792458; % Speed of light in vacuum (m/s)
eta0 = 376.730313668; % Impedance of free space (Ohms)
% --- 1. Read Touchstone File ---
try
s_params_obj = sparameters(touchstoneFile);
freq = s_params_obj.Frequencies;
S11_meas = squeeze(s_params_obj.Parameters(1,1,:));
S21_meas = squeeze(s_params_obj.Parameters(2,1,:));
% S12_meas = squeeze(s_params_obj.Parameters(1,2,:)); % S21 should be S12 for reciprocal passive
% S22_meas = squeeze(s_params_obj.Parameters(2,2,:)); % S11 should be S22 for symmetric
if isempty(freq) || isempty(S11_meas) || isempty(S21_meas)
error('Could not read S-parameters or data is empty.');
end
fprintf('Successfully read %s. %d frequency points.\n', touchstoneFile, length(freq));
catch ME
fprintf('Error reading Touchstone file: %s\n', ME.message);
fprintf('Please ensure the file exists and is a valid S2P file.\n');
fprintf('You might need to create a dummy .s2p file named "sample_data.s2p" for testing.\n');
% Create a dummy file for testing if it doesn't exist
if strcmp(touchstoneFile, 'sample_data.s2p') && ~exist(touchstoneFile, 'file')
disp('Creating a dummy sample_data.s2p for demonstration...');
create_dummy_s2p('sample_data.s2p', thickness_m); % Call helper to create one
s_params_obj = sparameters(touchstoneFile);
freq = s_params_obj.Frequencies;
S11_meas = squeeze(s_params_obj.Parameters(1,1,:));
S21_meas = squeeze(s_params_obj.Parameters(2,1,:));
fprintf('Dummy file created and loaded.\n');
else
return;
end
end
% --- 2. Optimization to Extract Material Properties ---
% We want to find: [eps_r_prime, eps_r_double_prime, mu_r_prime, mu_r_double_prime]
% Convention: eps_r* = eps_r_prime - j*eps_r_double_prime (eps_r_double_prime > 0 for loss)
% mu_r* = mu_r_prime - j*mu_r_double_prime (mu_r_double_prime > 0 for loss)
% Initial guess for [eps_r', eps_r'', mu_r', mu_r'']
% These are crucial! Try to make them somewhat realistic for your material.
% For non-magnetic materials, mu_r' is ~1, mu_r'' is ~0.
% For dielectrics, eps_r' > 1, eps_r'' >= 0.
initial_guess = [3.0, 0.1, 1.0, 0.01];
% Lower and Upper bounds for the parameters
% [eps_r_prime_min, eps_r_double_prime_min, mu_r_prime_min, mu_r_double_prime_min]
lb = [1.0, 0.0, 0.8, 0.0]; % eps_r' >=1, losses >=0, mu_r' can be <1 for some metamaterials
% [eps_r_prime_max, eps_r_double_prime_max, mu_r_prime_max, mu_r_double_prime_max]
ub = [100, 10, 50, 5]; % Adjust based on expected material
% Define the objective function for lsqnonlin
% It should return a vector of errors (measured - calculated)
objective_func = @(params) cost_function_lsqnonlin(params, freq, S11_meas, S21_meas, thickness_m, c0, eta0);
% Optimization options
options = optimoptions('lsqnonlin', ...
'Algorithm', 'trust-region-reflective', ... % or 'levenberg-marquardt'
'Display', 'iter', ...
'MaxIterations', 400, ...
'MaxFunctionEvaluations', 2000, ...
'StepTolerance', 1e-8, ...
'OptimalityTolerance', 1e-8);
% 'UseParallel', true); % If you have Parallel Computing Toolbox
fprintf('\nStarting optimization...\n');
try
[optimized_params, resnorm, residual, exitflag, output] = lsqnonlin(objective_func, initial_guess, lb, ub, options);
if exitflag <= 0
fprintf('Optimization did not converge or was terminated. Exit flag: %d\n', exitflag);
disp(output.message);
% Try with fminsearch if lsqnonlin fails badly, or adjust initial guesses/bounds
% For fminsearch, the cost function needs to return a scalar (sum of squares)
% scalar_objective_func = @(params) sum(abs(cost_function_lsqnonlin(params, freq, S11_meas, S21_meas, thickness_m, c0, eta0)).^2);
% options_fmin = optimset('Display','iter','MaxIter',1000, 'MaxFunEvals', 5000);
% [optimized_params, fval] = fminsearch(scalar_objective_func, initial_guess, options_fmin);
end
catch ME_optim
fprintf('Error during optimization: %s\n', ME_optim.message);
fprintf('Optimization failed. Check initial guesses, bounds, and Touchstone data.\n');
return;
end
% Extract results
eps_r_prime_fit = optimized_params(1);
eps_r_double_prime_fit = optimized_params(2);
mu_r_prime_fit = optimized_params(3);
mu_r_double_prime_fit = optimized_params(4);
epsilon_r_extracted = eps_r_prime_fit - 1j * eps_r_double_prime_fit;
mu_r_extracted = mu_r_prime_fit - 1j * mu_r_double_prime_fit;
fprintf('\n--- Optimization Finished ---\n');
fprintf('Extracted Epsilon_r: %.4f - j%.4f\n', real(epsilon_r_extracted), imag(epsilon_r_extracted)*-1);
fprintf('Extracted Mu_r: %.4f - j%.4f\n', real(mu_r_extracted), imag(mu_r_extracted)*-1);
fprintf('Residual norm (sum of squares of errors): %.4e\n', resnorm);
% --- 3. Calculate S-parameters using the extracted properties for comparison ---
[S11_fit, S21_fit] = calculate_S_params_slab(epsilon_r_extracted, mu_r_extracted, freq, thickness_m, c0, eta0);
% --- 4. Plotting Results ---
figure;
% Plot S11
subplot(2,2,1);
plot(freq/1e9, 20*log10(abs(S11_meas)), 'b-', 'LineWidth', 1.5);
hold on;
plot(freq/1e9, 20*log10(abs(S11_fit)), 'r--', 'LineWidth', 1.5);
hold off;
xlabel('Frequency (GHz)');
ylabel('|S_{11}| (dB)');
title('S_{11} Magnitude');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
subplot(2,2,2);
plot(freq/1e9, unwrap(angle(S11_meas))*180/pi, 'b-', 'LineWidth', 1.5);
hold on;
plot(freq/1e9, unwrap(angle(S11_fit))*180/pi, 'r--', 'LineWidth', 1.5);
hold off;
xlabel('Frequency (GHz)');
ylabel('Phase(S_{11}) (degrees)');
title('S_{11} Phase');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
% Plot S21
subplot(2,2,3);
plot(freq/1e9, 20*log10(abs(S21_meas)), 'b-', 'LineWidth', 1.5);
hold on;
plot(freq/1e9, 20*log10(abs(S21_fit)), 'r--', 'LineWidth', 1.5);
hold off;
xlabel('Frequency (GHz)');
ylabel('|S_{21}| (dB)');
title('S_{21} Magnitude');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
subplot(2,2,4);
plot(freq/1e9, unwrap(angle(S21_meas))*180/pi, 'b-', 'LineWidth', 1.5);
hold on;
plot(freq/1e9, unwrap(angle(S21_fit))*180/pi, 'r--', 'LineWidth', 1.5);
hold off;
xlabel('Frequency (GHz)');
ylabel('Phase(S_{21}) (degrees)');
title('S_{21} Phase');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
sgtitle(sprintf('Material Properties Fit: \\epsilon_r = %.2f - j%.2f, \\mu_r = %.2f - j%.2f', ...
real(epsilon_r_extracted), imag(epsilon_r_extracted)*-1, ...
real(mu_r_extracted), imag(mu_r_extracted)*-1));
% If you were fitting frequency-dependent properties, you'd plot them vs. frequency
% For this script, they are constant, so we just display them.
end % End of main script function (if you wrap it)
% --- Helper function to calculate S-parameters for a slab ---
function [S11, S21] = calculate_S_params_slab(epsilon_r_complex, mu_r_complex, freq_vec, d, c0, eta0)
omega_vec = 2 * pi * freq_vec;
% Material properties
eta_m_vec = eta0 * sqrt(mu_r_complex ./ epsilon_r_complex); % Intrinsic impedance of material
gamma_m_vec = 1j * omega_vec .* sqrt(epsilon_r_complex .* mu_r_complex) / c0; % Propagation constant in material
% Reflection coefficient at interface
Gamma_vec = (eta_m_vec - eta0) ./ (eta_m_vec + eta0);
% Transmission factor through material thickness d
T_vec = exp(-gamma_m_vec * d);
% Calculate S-parameters
% Using standard formulas for a single slab
S11_numerator = Gamma_vec .* (1 - T_vec.^2);
S11_denominator = 1 - (Gamma_vec.^2 .* T_vec.^2);
S11 = S11_numerator ./ S11_denominator;
S21_numerator = T_vec .* (1 - Gamma_vec.^2);
S21_denominator = 1 - (Gamma_vec.^2 .* T_vec.^2);
S21 = S21_numerator ./ S21_denominator;
end
% --- Helper function for lsqnonlin cost function ---
function error_vector = cost_function_lsqnonlin(params, freq_vec, S11_meas, S21_meas, d, c0, eta0)
eps_r_prime = params(1);
eps_r_double_prime = params(2); % This will be positive for loss
mu_r_prime = params(3);
mu_r_double_prime = params(4); % This will be positive for loss
epsilon_r_complex = eps_r_prime - 1j * eps_r_double_prime;
mu_r_complex = mu_r_prime - 1j * mu_r_double_prime;
[S11_calc, S21_calc] = calculate_S_params_slab(epsilon_r_complex, mu_r_complex, freq_vec, d, c0, eta0);
% Error for S11 (real and imaginary parts separately for lsqnonlin)
error_S11_real = real(S11_meas - S11_calc);
error_S11_imag = imag(S11_meas - S11_calc);
% Error for S21 (real and imaginary parts separately)
error_S21_real = real(S21_meas - S21_calc);
error_S21_imag = imag(S21_meas - S21_calc);
% Weighting (optional, can be useful if S11 or S21 fit is more critical or noisy)
% For example, if S21 is more reliable:
% weight_S11 = 1;
% weight_S21 = 1; % or 2 or more if S21 is more important/accurate
% Construct the error vector
% error_vector = [weight_S11 * error_S11_real;
% weight_S11 * error_S11_imag;
% weight_S21 * error_S21_real;
% weight_S21 * error_S21_imag];
% Normalize by magnitude to prevent very small S-parameters from having too little influence
% Or, normalize to dB errors (can be more complex to set up for lsqnonlin)
% Simple non-weighted version:
error_vector = [error_S11_real; error_S11_imag; error_S21_real; error_S21_imag];
% Penalize non-physical solutions (optional, better handled by bounds if possible)
% if eps_r_prime < 1.0 || eps_r_double_prime < 0 || mu_r_prime < 0.5 || mu_r_double_prime < 0
% error_vector = error_vector + 1e3; % Add large penalty
% end
end
% --- Helper function to create a DUMMY S2P file for testing ---
function create_dummy_s2p(filename, thickness_m_val)
% Create some plausible dummy S-parameter data based on known material
% For demonstration, let's assume some typical dielectric like FR4
% (eps_r ~ 4.4 - j0.08, mu_r ~ 1.0 - j0.001)
eps_r_true = 4.4 - 1j*0.08;
mu_r_true = 1.0 - 1j*0.001; % Slightly lossy non-magnetic
freq_dummy = linspace(1e9, 10e9, 101); % 1 to 10 GHz, 101 points
c0_dummy = 299792458;
eta0_dummy = 376.730313668;
[S11_dummy, S21_dummy] = calculate_S_params_slab(eps_r_true, mu_r_true, freq_dummy, thickness_m_val, c0_dummy, eta0_dummy);
% Add a tiny bit of noise
noise_level_abs = 0.005;
noise_level_phase_rad = 0.01;
S11_dummy = S11_dummy + noise_level_abs * (randn(size(S11_dummy)) + 1j*randn(size(S11_dummy)));
S21_dummy = S21_dummy + noise_level_abs * (randn(size(S21_dummy)) + 1j*randn(size(S21_dummy)));
% Assume reciprocal and symmetric for simplicity (S12=S21, S22=S11)
S12_dummy = S21_dummy;
S22_dummy = S11_dummy;
fid = fopen(filename, 'w');
if fid == -1
error('Cannot create dummy file %s', filename);
end
fprintf(fid, '! Dummy S2P file generated by MATLAB script\n');
fprintf(fid, '# HZ S RI R 50\n'); % Header: Frequency in Hz, S-params, Real/Imaginary, impedance 50 Ohm
fprintf(fid, '! FREQ S11R S11I S21R S21I S12R S12I S22R S22I\n');
for i = 1:length(freq_dummy)
fprintf(fid, '%.6e %.6e %.6e %.6e %.6e %.6e %.6e %.6e %.6e\n', ...
freq_dummy(i), ...
real(S11_dummy(i)), imag(S11_dummy(i)), ...
real(S21_dummy(i)), imag(S21_dummy(i)), ...
real(S12_dummy(i)), imag(S12_dummy(i)), ...
real(S22_dummy(i)), imag(S22_dummy(i)));
end
fclose(fid);
fprintf('Dummy file %s created with plausible data for eps_r~%.1f, mu_r~%.1f, d=%.1fmm.\n', ...
filename, real(eps_r_true), real(mu_r_true), thickness_m_val*1000);
end
How to Use:
Save: Save the code above as extract_material_properties.m. The helper functions calculate_S_params_slab, cost_function_lsqnonlin, and create_dummy_s2p should be in the same file or on MATLAB's path.
Touchstone File:
Place your S2P Touchstone file (e.g., my_sample.s2p) in the same directory as the script.
Modify the touchstoneFile variable in the script to match your filename.
If you don't have one, the script will attempt to create a sample_data.s2p with plausible synthetic data for testing.
Thickness:
Modify the thickness_m variable to your sample's thickness in meters.
Run: Execute the script from the MATLAB command window:
matlab
extract_material_properties
Review Output:
The script will print iteration information from the optimizer.
It will then print the extracted εr* and μr*.
Finally, it will show plots comparing the measured S-parameters with those calculated using the fitted material properties. A good fit indicates reliable extracted parameters.
Important Considerations and Potential Improvements:
Initial Guesses & Bounds: The success of optimization heavily depends on good initial guesses (initial_guess) and reasonable bounds (lb, ub). If the optimization fails or gives non-physical results, these are the first things to adjust.
Frequency Dependence: This script assumes εr and μr are constant. For many materials, especially at higher frequencies or over wide bandwidths, this isn't true. You would then need to:
Assume a dispersion model (e.g., Debye: eps_r(f) = eps_inf + (eps_s - eps_inf) / (1 + j*f/f_relax)).
Optimize the parameters of that model (e.g., eps_s, eps_inf, f_relax). This increases the number of parameters to fit.
Local Minima: Optimization algorithms can get stuck in local minima. Try different initial guesses or use a global optimization algorithm (e.g., globalsearch, particleswarm - requires Global Optimization Toolbox) if you suspect this.
Measurement Quality: The accuracy of the extracted properties is only as good as your S-parameter measurements. Ensure proper VNA calibration (TRL is best for free-space), minimal air gaps, and correct sample geometry.
Uniqueness: For thin, low-loss materials, it can sometimes be hard to uniquely determine both εr and μr. S11 is more sensitive to impedance mismatch (related to sqrt(μr/εr)), while S21 is more sensitive to electrical thickness (related to sqrt(μr*εr)*d). If μr is known to be 1 (common for non-magnetic dielectrics), you can simplify the problem by fixing mu_r_prime = 1 and mu_r_double_prime = 0 in the optimization.
Multi-Thickness: Measuring samples of different thicknesses and fitting a single set of material properties to all datasets simultaneously significantly improves robustness and uniqueness. The cost function would sum errors from all datasets.
Error Analysis/Weighting: In cost_function_lsqnonlin, you might want to weight the errors. For example, if S21 is measured more accurately than S11, or if you want to fit dB magnitude and phase rather than complex values directly.
Kramers-Kronig: For frequency-dependent properties, ensuring the extracted εr(f) and μr(f) are Kramers-Kronig consistent is a good check of physicality, though enforcing it during optimization is complex.
This script provides a solid foundation. The optimization approach is generally much more robust than direct inversion techniques, especially around problematic λ/4 or λ/2 thicknesses.