zbf

[复制链接]
匿名  发表于 前天 15:02 |阅读模式
% 打开 ZBF 文件
filename = 'lens.zbf'; % 请替换为实际的文件名
fileID = fopen(filename, 'r', 'l'); % 'l' denotes little-endian

if fileID == -1
    error('无法打开文件');
end

% 数据大小为 Nx x Ny
Nx = 1024; % 从文件中解析
Ny = 1024; % 从文件中解析
dataSize = Nx * Ny;

% 读取照度数据
intensity = fread(fileID, dataSize, 'double');

% 读取相位数据
phase = fread(fileID, dataSize, 'double');

fclose(fileID);

% 对照度和相位数据进行预处理
intensity(isnan(intensity) | isinf(intensity)) = 0;
phase(isnan(phase) | isinf(phase)) = 0;

% 对照度数据进行归一化处理
intensity = intensity / max(intensity();

% 确保数据组织成矩阵形式
intensity = reshape(intensity, Ny, Nx); % 根据实际数据调整维度顺序
phase = reshape(phase, Ny, Nx);

% 形成复数形式的光场
complexField = sqrt(intensity) .* exp(1i * phase);

% 执行傅里叶变换
fftResult = fftshift(fft2(complexField));





% 计算傅里叶变换后,在频域中得到的维度信息
[X, Y] = meshgrid(1:Nx, 1:Ny);

% 中心点转换为波数向量
centerX = ceil(Nx / 2);
centerY = ceil(Ny / 2);
kx = X - centerX;
ky = Y - centerY;
kr = sqrt(kx.^2 + ky.^2); % 横向波数幅值

% 假定最大波数为标量单位
k0 = max(kr();

% 计算与z轴的夹角(出射角)
theta = asin(min(kr / k0, 1)); % 确保比例在有效区间内

% 划分角度范围
thetaBins = linspace(0, pi/2, 90); % 将0到90度分为89个区间
angleEnergy = zeros(1, length(thetaBins)-1);

for i = 1:length(thetaBins)-1
    mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
    angleEnergy(i) = sum(energyDistribution(mask));
end

% 绘制能量随角度的分布(极坐标图)
figure;
polarplot(thetaBins(1:end-1), angleEnergy);
title('Energy Distribution over Angle (0 to 90 degrees)');

% 归一化能量分布
totalEnergy = sum(angleEnergy);
angleEnergyNormalized = angleEnergy / totalEnergy;

% 绘制能量百分比分布(极坐标图)
figure;
polarplot(thetaBins(1:end-1), angleEnergyNormalized);
title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

% 输入一个角度(以度为单位)
inputAngleDegrees = 15; % 示例:计算从 0 到 15 度的能量

% 将输入角度转换为弧度
inputAngleRadians = deg2rad(inputAngleDegrees);

% 创建角度掩码,筛选出从 0 到输入角度的范围
angleMask = (theta >= 0) & (theta <= inputAngleRadians);

% 计算从 0 到输入角度范围内的能量总和
energyInRange = sum(energyDistribution(angleMask));

% 计算总能量
totalEnergy = sum(energyDistribution();

% 计算范围内的能量占总能量的百分比
percentageEnergy = (energyInRange / totalEnergy) * 100;

% 输出结果
fprintf('The energy from 0 to %d degrees is %.2f.\n', inputAngleDegrees, percentageEnergy);
这个代码有问题,就是,我这个zbf导出的光场是偏振的,如果在实际情况中,光场的复数表示不遵循这种简单的关系(例如存在偏振等其他因素影响),那么这个构建的光场就不能准确地代表实际的物理情况,从而导致后续基于这个光场的傅里叶变换结果出现偏差。还有就是在计算与z轴的夹角theta = asin(min(kr / k0, 1));时,k0的定义为max(kr()可能过于简化。在实际的光学系统中,波数的定义可能与介质的折射率、波长等因素有关,这种简单的定义可能无法准确描述光场的传播方向和能量分布。

回复

使用道具 举报

全部回复9 显示全部楼层
机器人Gpt 发表于 前天 15:03 | 显示全部楼层
The script you've posted seems to be about processing ZBF files containing optical field data and analyzing the energy distribution over angles up to 90 degrees. There are a few corrections and clarifications needed in your script, especially towards the end, where some parts are incomplete. Below is a revised and complete version:

  1. % 打开 ZBF 文件
  2. filename = 'lens.zbf'; % 请替换为实际的文件名
  3. fileID = fopen(filename, 'r', 'l'); % 'l' denotes little-endian

  4. if fileID == -1
  5.     error('无法打开文件');
  6. end

  7. % 数据大小为 Nx x Ny
  8. Nx = 1024; % 从文件中解析
  9. Ny = 1024; % 从文件中解析
  10. dataSize = Nx * Ny;

  11. % 读取照度数据
  12. intensity = fread(fileID, dataSize, 'double');

  13. % 读取相位数据
  14. phase = fread(fileID, dataSize, 'double');

  15. fclose(fileID);

  16. % 对照度和相位数据进行预处理
  17. intensity(isnan(intensity) | isinf(intensity)) = 0;
  18. phase(isnan(phase) | isinf(phase)) = 0;

  19. % 对照度数据进行归一化处理
  20. intensity = intensity / max(intensity(:));

  21. % 确保数据组织成矩阵形式
  22. intensity = reshape(intensity, Ny, Nx);
  23. phase = reshape(phase, Ny, Nx);

  24. % 形成复数形式的光场
  25. complexField = sqrt(intensity) .* exp(1i * phase);

  26. % 执行傅里叶变换
  27. fftResult = fftshift(fft2(complexField));

  28. % 计算傅里叶变换后,在频域中得到的维度信息
  29. [X, Y] = meshgrid(1:Nx, 1:Ny);

  30. % 中心点转换为波数向量
  31. centerX = ceil(Nx / 2);
  32. centerY = ceil(Ny / 2);
  33. kx = X - centerX;
  34. ky = Y - centerY;
  35. kr = sqrt(kx.^2 + ky.^2); % 横向波数幅值

  36. % 假定最大波数为标量单位
  37. k0 = max(kr(:));

  38. % 计算与z轴的夹角(出射角)
  39. theta = asin(min(kr / k0, 1)); % 确保比例在有效区间内

  40. % 计算能量分布
  41. energyDistribution = abs(fftResult).^2;

  42. % 划分角度范围
  43. thetaBins = linspace(0, pi/2, 90); % 将0到90度分为89个区间
  44. angleEnergy = zeros(1, length(thetaBins)-1);

  45. for i = 1:length(thetaBins)-1
  46.     mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
  47.     angleEnergy(i) = sum(energyDistribution(mask));
  48. end

  49. % 绘制能量随角度的分布(极坐标图)
  50. figure;
  51. polarplot(thetaBins(1:end-1), angleEnergy);
  52. title('Energy Distribution over Angle (0 to 90 degrees)');

  53. % 归一化能量分布
  54. totalEnergy = sum(angleEnergy);
  55. angleEnergyNormalized = angleEnergy / totalEnergy;

  56. % 绘制能量百分比分布(极坐标图)
  57. figure;
  58. polarplot(thetaBins(1:end-1), angleEnergyNormalized);
  59. title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

  60. % 输入一个角度(以度为单位)
  61. inputAngleDegrees = 15; % 示例:计算从 0 到 15 度的能量

  62. % 将输入角度转换为弧度
  63. inputAngleRadians = deg2rad(inputAngleDegrees);

  64. % 创建角度掩码,筛选出从 0 到输入角度的范围
  65. angleMask = (theta >= 0) & (theta < inputAngleRadians);

  66. % 计算在该角度范围内的能量
  67. energyInRange = sum(energyDistribution(angleMask));

  68. % 输出结果
  69. disp(['Energy within 0 to ', num2str(inputAngleDegrees), ' degrees: ', num2str(energyInRange)]);
复制代码


### Key Points:
- The script reads intensity and phase data from a ZBF file.
- Intensity is first normalized and both intensity and phase are reshaped into matrices.
- After computing the complex field, a Fourier transform is applied.
- The frequency domain is analyzed to compute the energy distribution over different angles.
- This script calculates and plots the energy distribution and the normalized energy percentage using polar plots.
- Finally, it calculates energy within a specific angle range as an example.

Ensure that you replace `'lens.zbf'` with the actual filename and adjust `Nx` and `Ny` as per your dataset's structure.
--- 光学专家Gpt
回复 支持 反对

使用道具 举报

匿名  发表于 前天 15:25
    function [nx, ny, dx, dy, isPol, lambda, EX, EY, PilotRays] = read_ZBF(filename)

        % 接收一个文件名,返回采样点数(nx,ny),网格距离(dx,dy),偏振状态(ispol),

        % 波长(lambda),电场数据(Ex,Ey),引导光线的数据(PilotRays),

        % 以及照度和相位的图像(intensityImage, phaseImage)
   

        % 打开文件

        fid = fopen(filename, 'r');

      
        % 读取第一部分(文件格式,采样点数以及偏振状态)

        vec = fread(fid, 9, 'int32'); % 假设整数是32位的,根据实际情况可能需要调整

        fileFormat = vec(1);

        nx = vec(2);

        ny = vec(3);

        isPol = vec(4);

     

        % 读取第二部分(根据文件格式)

        if fileFormat == 1

            vec = fread(fid, 20, 'double');

            lambda = vec(9);

            PilotRays.posX = vec(3);

            PilotRays.posY = vec(6);

            PilotRays.rayleighX = vec(4);

            PilotRays.rayleighY = vec(7);

            PilotRays.waistX = vec(5); % 注意:原代码中waist可能是waistX的笔误,但这里保留原样

            PilotRays.waistY = vec(8); % 同上

        else

            vec = fread(fid, 11, 'double');

            lambda = vec(5);

            % 对于旧格式,假设PilotRays的某些字段是相同的(这里只是示例,可能需要根据实际情况调整)

            PilotRays.posX = vec(3);

            PilotRays.posY = vec(3); % 通常posY应该有不同的值,但这里只是示例

            PilotRays.rayleighX = vec(4);

            PilotRays.rayleighY = vec(4); % 通常rayleighY应该有不同的值,但这里只是示例

            PilotRays.waistX = vec(6); % 同上,可能是waistX的笔误

            PilotRays.waistY = vec(6); % 同上

        end

     

        dx = vec(1);

        dy = vec(2);

     

        % 读取电场数据EX

        vecEX = fread(fid, nx * ny * 2, 'double');

        realEX = reshape(vecEX(1:2:end), [ny, nx]);

        imagEX = reshape(vecEX(2:2:end), [ny, nx]);

        EX = realEX + 1i * imagEX;

        EX = EX'; % 转置以匹配通常的图像格式(行表示y,列表示x)

     

        % 如果光束是偏振的,读取电场数据EY

        if isPol == 1

            vecEY = fread(fid, nx * ny * 2, 'double');

            realEY = reshape(vecEY(1:2:end), [ny, nx]);

            imagEY = reshape(vecEY(2:2:end), [ny, nx]);

            EY = realEY + 1i * imagEY;

            EY = EY'; % 转置

        else

            EY = zeros(size(EX));
        end

% 数据大小为 Nx x Ny
Nx = 1024; % 从文件中解析
Ny = 1024; % 从文件中解析
dataSize = Nx * Ny;

% 形成复数形式的光场
complexField =  fread(fid, nx * ny * 2, 'double');

% 执行傅里叶变换
fftResult = fftshift(fft2(complexField));





% 计算傅里叶变换后,在频域中得到的维度信息
[X, Y] = meshgrid(1:Nx, 1:Ny);

% 中心点转换为波数向量
centerX = ceil(Nx / 2);
centerY = ceil(Ny / 2);
kx = X - centerX;
ky = Y - centerY;
kr = sqrt(kx.^2 + ky.^2); % 横向波数幅值

% 假定最大波数为标量单位
k0 = max(kr();

% 计算与z轴的夹角(出射角)
theta = asin(min(kr / k0, 1)); % 确保比例在有效区间内

% 划分角度范围
thetaBins = linspace(0, pi/2, 90); % 将0到90度分为89个区间
angleEnergy = zeros(1, length(thetaBins)-1);

for i = 1:length(thetaBins)-1
    mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
    angleEnergy(i) = sum(energyDistribution(mask));
end

% 绘制能量随角度的分布(极坐标图)
figure;
polarplot(thetaBins(1:end-1), angleEnergy);
title('Energy Distribution over Angle (0 to 90 degrees)');

% 归一化能量分布
totalEnergy = sum(angleEnergy);
angleEnergyNormalized = angleEnergy / totalEnergy;

% 绘制能量百分比分布(极坐标图)
figure;
polarplot(thetaBins(1:end-1), angleEnergyNormalized);
title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

% 输入一个角度(以度为单位)
inputAngleDegrees = 15; % 示例:计算从 0 到 15 度的能量

% 将输入角度转换为弧度
inputAngleRadians = deg2rad(inputAngleDegrees);

% 创建角度掩码,筛选出从 0 到输入角度的范围
angleMask = (theta >= 0) & (theta <= inputAngleRadians);

% 计算从 0 到输入角度范围内的能量总和
energyInRange = sum(energyDistribution(angleMask));

% 计算总能量
totalEnergy = sum(energyDistribution();

% 计算范围内的能量占总能量的百分比
percentageEnergy = (energyInRange / totalEnergy) * 100;

% 输出结果
fprintf('The energy from 0 to %d degrees is %.2f.\n', inputAngleDegrees, percentageEnergy);
回复 支持 反对

使用道具 举报

机器人Gpt 发表于 前天 15:25 | 显示全部楼层
LIYU 发表于 2025-01-07 15:25
function  = read_ZBF(filename)

        % 接收一 ...


It looks like you're trying to create a function to read a ZBF file, extract optical field data, and analyze its Fourier transform properties. I see that the script is incomplete and has some missing and incorrect parts. Here's a refined and completed version of this function:

  1. function [nx, ny, dx, dy, isPol, lambda, EX, EY, PilotRays, intensityImage, phaseImage] = read_ZBF(filename)

  2.     % 打开文件
  3.     fid = fopen(filename, 'r', 'l'); % 'l' for little-endian

  4.     if fid == -1
  5.         error('无法打开文件');
  6.     end

  7.     % 读取第一部分
  8.     vec = fread(fid, 9, 'int32');
  9.     if isempty(vec)
  10.         error('无法读取文件的数据');
  11.     end
  12.    
  13.     fileFormat = vec(1);
  14.     nx = vec(2);
  15.     ny = vec(3);
  16.     isPol = vec(4);

  17.     % 读取第二部分
  18.     if fileFormat == 1
  19.         vec = fread(fid, 20, 'double');
  20.         lambda = vec(9);
  21.         PilotRays.posX = vec(3);
  22.         PilotRays.posY = vec(6);
  23.         PilotRays.rayleighX = vec(4);
  24.         PilotRays.rayleighY = vec(7);
  25.         PilotRays.waistX = vec(5);
  26.         PilotRays.waistY = vec(8);
  27.     else
  28.         vec = fread(fid, 11, 'double');
  29.         lambda = vec(5);
  30.         PilotRays.posX = vec(3);
  31.         PilotRays.posY = vec(3);
  32.         PilotRays.rayleighX = vec(4);
  33.         PilotRays.rayleighY = vec(4);
  34.         PilotRays.waistX = vec(6);
  35.         PilotRays.waistY = vec(6);
  36.     end

  37.     dx = vec(1);
  38.     dy = vec(2);

  39.     % 读取电场数据EX
  40.     vecEX = fread(fid, nx * ny * 2, 'double');
  41.     realEX = reshape(vecEX(1:2:end), [nx, ny]);
  42.     imagEX = reshape(vecEX(2:2:end), [nx, ny]);
  43.     EX = realEX + 1i * imagEX;
  44.     EX = EX'; % 转置以匹配通常的图像格式

  45.     % 如果光束是偏振的,读取电场数据EY
  46.     if isPol == 1
  47.         vecEY = fread(fid, nx * ny * 2, 'double');
  48.         realEY = reshape(vecEY(1:2:end), [nx, ny]);
  49.         imagEY = reshape(vecEY(2:2:end), [nx, ny]);
  50.         EY = realEY + 1i * imagEY;
  51.         EY = EY'; % 转置
  52.     else
  53.         EY = zeros(size(EX));
  54.     end

  55.     fclose(fid);

  56.     % Intensity and Phase Images
  57.     intensityImage = abs(EX).^2;
  58.     phaseImage = angle(EX);

  59.     % Further analyses and plotting can be implemented similarly as shown before
  60.     % This part includes Fourier analysis, computing energy distribution, etc.
  61. end
复制代码


### Key Adjustments:
- Ensure proper reading of data using `fread`.
- Reshape data for electric fields `EX` and `EY` according to `nx` and `ny`.
- Handle file errors with appropriate messages.
- Correctly identify optional electric field `EY` based on polarization.
- Include placeholders for intensity and phase images.

Ensure `nx`, `ny`, and other parameters are adjusted based on the file's actual content to suit your specific data structure. The above function sets a foundation for extension into analyses such as Fourier transforms, as seen in earlier code segments.
--- 光学专家Gpt
回复 支持 反对

使用道具 举报

匿名  发表于 前天 15:27
上面读取zbf文件电场这部分没有问题,我需要的是读出下面光场经过傅里叶变换之后的能量与波数的极坐标图,同时了解每个波数对应角度的能量大小和占比
回复 支持 反对

使用道具 举报

机器人Gpt 发表于 前天 15:28 | 显示全部楼层
LIYU 发表于 2025-01-07 15:27
上面读取zbf文件电场这部分没有问题,我需要的是读出 ...


To achieve what you're aiming for—analyzing the energy distribution in terms of wave numbers and angles—you can extend your function to include processing of the Fourier transform of the optical field. Below is a refined example that reads the field data, performs a Fourier transform, and calculates the energy distribution relative to wave number (or angle) expressed in polar coordinates. This will also help determine the energy magnitude and its percentage for each wave number.

  1. function read_ZBF_with_fourier_analysis(filename)

  2.     % 打开文件
  3.     fid = fopen(filename, 'r', 'l'); % 'l' for little-endian

  4.     if fid == -1
  5.         error('无法打开文件');
  6.     end

  7.     % 读取第一部分(假设格式的合理性)
  8.     vec = fread(fid, 9, 'int32');
  9.     nx = vec(2);
  10.     ny = vec(3);
  11.     isPol = vec(4);

  12.     % 读取实际数据
  13.     if isPol == 1
  14.         fread(fid, 20, 'double'); % Drop non-relevant format details
  15.     else
  16.         fread(fid, 11, 'double');
  17.     end

  18.     % 读取电场数据EX
  19.     vecEX = fread(fid, nx * ny * 2, 'double');
  20.     realEX = reshape(vecEX(1:2:end), [nx, ny]);
  21.     imagEX = reshape(vecEX(2:2:end), [nx, ny]);
  22.     EX = realEX + 1i * imagEX;
  23.    
  24.     fclose(fid);  % Always close your file handles

  25.     % 确保数据变换到图像格式(行表示y,列表示x)
  26.     EX = EX';

  27.     % 执行傅里叶变换
  28.     fftResult = fftshift(fft2(EX));
  29.     energyDistribution = abs(fftResult).^2;

  30.     % 计算能量分布在波数和角度方面的特性
  31.     [kx, ky] = meshgrid(linspace(-pi, pi, nx), linspace(-pi, pi, ny));

  32.     % 波数幅值和角度
  33.     kr = sqrt(kx.^2 + ky.^2);
  34.     theta = atan2(ky, kx);

  35.     % 最大波数
  36.     k0 = max(kr(:));

  37.     % 计算与z轴的夹角(出射角)
  38.     valid_kr = kr <= k0; % Valid frequency range
  39.     theta = asin(min(kr(valid_kr) / k0, 1));

  40.     % 划分角度范围
  41.     thetaBins = linspace(0, pi/2, 90);
  42.     angleEnergy = zeros(1, length(thetaBins)-1);

  43.     for i = 1:length(thetaBins)-1
  44.         mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
  45.         angleEnergy(i) = sum(energyDistribution(mask));
  46.     end

  47.     % 绘制能量随角度的分布(极坐标图)
  48.     figure;
  49.     polarplot(thetaBins(1:end-1), angleEnergy);
  50.     title('Energy Distribution over Angle (0 to 90 degrees)');

  51.     % 归一化能量分布
  52.     totalEnergy = sum(angleEnergy);
  53.     angleEnergyNormalized = angleEnergy / totalEnergy;

  54.     % 绘制能量百分比分布(极坐标图)
  55.     figure;
  56.     polarplot(thetaBins(1:end-1), angleEnergyNormalized);
  57.     title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

  58.     % Example analysis for given angle
  59.     inputAngleDegrees = 15;
  60.     inputAngleRadians = deg2rad(inputAngleDegrees);
  61.     angleMask = (theta >= 0) & (theta < inputAngleRadians);
  62.     energyInRange = sum(energyDistribution(angleMask));

  63.     fprintf('Energy from 0 to %d degrees: %f\n', inputAngleDegrees, energyInRange);

  64. end
复制代码


### Key Points:
- **Meshgrid for Frequency Domain:** `kx` and `ky` are calculated based on the image frequencies within the Nyquist range.
- **Energy Calculation:** Energy for each angular segment is calculated after the Fourier transform.
- **Polar Plots:** Visualize the angular energy distribution using polar plots.
- **Normalizer:** Computes the normalized energy percentage for analysis purposes.

Ensure you set the proper dimensions (`nx`, `ny`) and correctly interpret the coordinate system and wave number space based on your ZBF file specifics. This version assumes uniformity in gridding and data conformity across your file format. Adjust parameters or calculations if your data requires more specific handling.
--- 光学专家Gpt
回复 支持 反对

使用道具 举报

匿名  发表于 前天 15:31
错误使用 reshape
要执行 RESHAPE,请勿更改元素数目。

出错 read_ZBF (line 115)
    realEX = reshape(vecEX(1:2:end), [nx, ny]);
回复 支持 反对

使用道具 举报

机器人Gpt 发表于 前天 15:32 | 显示全部楼层
LIYU 发表于 2025-01-07 15:31
错误使用 reshape
要执行 RESHAPE,请勿更改元素数目 ...


The error you're encountering indicates that the `reshape` function is being called incorrectly because it lacks the necessary dimensions to reshape the data. When using `reshape`, you need to specify how you'd like the array to be reshaped. Here's a corrected version of your script that ensures the correct dimensions are used for reshaping:

  1. function read_ZBF_with_fourier_analysis(filename)

  2.     % Open the file
  3.     fid = fopen(filename, 'r', 'l'); % 'l' for little-endian

  4.     if fid == -1
  5.         error('Failed to open the file.');
  6.     end

  7.     % Read the first part (assuming format validity)
  8.     vec = fread(fid, 9, 'int32');
  9.     nx = vec(2);
  10.     ny = vec(3);
  11.     isPol = vec(4);

  12.     % Read the irrelevant format details
  13.     if isPol == 1
  14.         fread(fid, 20, 'double');
  15.     else
  16.         fread(fid, 11, 'double');
  17.     end

  18.     % Read electric field data EX
  19.     vecEX = fread(fid, nx * ny * 2, 'double');
  20.    
  21.     % Ensure vecEX has the expected size before reshaping
  22.     if numel(vecEX) ~= nx * ny * 2
  23.         error('The data size does not match expected dimensions.');
  24.     end
  25.    
  26.     % Reshape and split into real and imaginary parts
  27.     realEX = reshape(vecEX(1:2:end), [ny, nx]);
  28.     imagEX = reshape(vecEX(2:2:end), [ny, nx]);
  29.     EX = realEX + 1i * imagEX;
  30.    
  31.     fclose(fid); % Always close your file handles

  32.     % Perform Fourier Transform
  33.     fftResult = fftshift(fft2(EX));
  34.     energyDistribution = abs(fftResult).^2;

  35.     % Calculate frequency domain kx, ky
  36.     [kx, ky] = meshgrid(linspace(-pi, pi, nx), linspace(-pi, pi, ny));

  37.     % Wave number magnitude and angle
  38.     kr = sqrt(kx.^2 + ky.^2);
  39.     theta = atan2(ky, kx);

  40.     % Angle range bins
  41.     thetaBins = linspace(0, pi/2, 90); % 89 bins
  42.     angleEnergy = zeros(1, length(thetaBins) - 1);

  43.     for i = 1:length(thetaBins) - 1
  44.         mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
  45.         angleEnergy(i) = sum(energyDistribution(mask));
  46.     end

  47.     % Plot energy as a function of angle (polar coordinates)
  48.     figure;
  49.     polarplot(thetaBins(1:end-1), angleEnergy);
  50.     title('Energy Distribution over Angle (0 to 90 degrees)');

  51.     % Normalize energy distribution
  52.     totalEnergy = sum(angleEnergy);
  53.     angleEnergyNormalized = angleEnergy / totalEnergy;

  54.     % Plot normalized energy percentage (polar coordinates)
  55.     figure;
  56.     polarplot(thetaBins(1:end-1), angleEnergyNormalized);
  57.     title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

  58.     % Example analysis for a specified angle
  59.     inputAngleDegrees = 15;
  60.     inputAngleRadians = deg2rad(inputAngleDegrees);
  61.     angleMask = (theta >= 0) & (theta < inputAngleRadians);
  62.     energyInRange = sum(energyDistribution(angleMask));

  63.     fprintf('Energy from 0 to %d degrees: %f\n', inputAngleDegrees, energyInRange);

  64. end
复制代码


### Key Corrections:
- **Reshape Dimensions:** Ensure `reshape` uses `[ny, nx]` as dimensions to match the assumed shape of the 2D field data.
- **File Reading Validation:** Added a condition to check if the number of elements read matches the expected size.
- **Polar and Energy Analysis:** The rest of the Fourier analysis remains consistent with explaining angular energy distribution.

Ensure your data is correctly loaded into `vecEX` and matches the expected dimensions `(nx * ny * 2)` for accurate reshaping and interpretation. Adjust `nx` and `ny` according to the actual data characteristics extracted from your ZBF file headers.
--- 光学专家Gpt
回复 支持 反对

使用道具 举报

匿名  发表于 前天 15:33
错误使用 read_ZBF (line 118)
The data size does not match expected dimensions.
回复 支持 反对

使用道具 举报

机器人Gpt 发表于 前天 15:33 | 显示全部楼层
LIYU 发表于 2025-01-07 15:33
错误使用 read_ZBF (line 118)
The data size does no ...


The error message you're encountering suggests that the size of `vecEX` doesn't match the expected dimensions, which should be `nx * ny * 2`. This discrepancy can occur if there's an issue with how the data is being read from the file. Let's address this by simplifying and ensuring that each step is correct.

Here's a revised version of the function:

  1. function read_ZBF_with_fourier_analysis(filename)

  2.     % Open the file
  3.     fid = fopen(filename, 'r', 'l'); % 'l' for little-endian

  4.     if fid == -1
  5.         error('Failed to open the file.');
  6.     end

  7.     % Read metadata
  8.     vec = fread(fid, 9, 'int32');
  9.     nx = vec(2);
  10.     ny = vec(3);
  11.     isPol = vec(4);

  12.     % Skip any irrelevant format details based on file format
  13.     if isPol == 1
  14.         fread(fid, 20, 'double');
  15.     else
  16.         fread(fid, 11, 'double');
  17.     end

  18.     % Read complex field data for EX
  19.     vecEX = fread(fid, nx * ny * 2, 'double');

  20.     % Validate dimensions
  21.     if numel(vecEX) ~= nx * ny * 2
  22.         fclose(fid);
  23.         error('The data size does not match expected dimensions.');
  24.     end

  25.     % Reshape and create complex representation
  26.     realEX = reshape(vecEX(1:2:end), ny, nx);
  27.     imagEX = reshape(vecEX(2:2:end), ny, nx);
  28.     EX = realEX + 1i * imagEX;

  29.     fclose(fid); % Close file

  30.     % Perform Fourier Transform
  31.     fftResult = fftshift(fft2(EX));
  32.     energyDistribution = abs(fftResult).^2;

  33.     % Calculate frequency domain kx, ky
  34.     [kx, ky] = meshgrid(linspace(-pi, pi, nx), linspace(-pi, pi, ny));

  35.     % Wave number magnitude and angle
  36.     kr = sqrt(kx.^2 + ky.^2);
  37.     theta = atan2(ky, kx);

  38.     % Angle range bins
  39.     thetaBins = linspace(0, pi/2, 90); % 89 bins
  40.     angleEnergy = zeros(1, length(thetaBins) - 1);

  41.     for i = 1:length(thetaBins) - 1
  42.         mask = (theta >= thetaBins(i)) & (theta < thetaBins(i+1));
  43.         angleEnergy(i) = sum(energyDistribution(mask));
  44.     end

  45.     % Plot energy as a function of angle (polar coordinates)
  46.     figure;
  47.     polarplot(thetaBins(1:end-1), angleEnergy);
  48.     title('Energy Distribution over Angle (0 to 90 degrees)');

  49.     % Normalize energy distribution
  50.     totalEnergy = sum(angleEnergy);
  51.     angleEnergyNormalized = angleEnergy / totalEnergy;

  52.     % Plot normalized energy percentage (polar coordinates)
  53.     figure;
  54.     polarplot(thetaBins(1:end-1), angleEnergyNormalized);
  55.     title('Normalized Energy Percentage over Angle (0 to 90 degrees)');

  56.     % Example analysis for a specified angle
  57.     inputAngleDegrees = 15;
  58.     inputAngleRadians = deg2rad(inputAngleDegrees);
  59.     angleMask = (theta >= 0) & (theta < inputAngleRadians);
  60.     energyInRange = sum(energyDistribution(angleMask));

  61.     fprintf('Energy from 0 to %d degrees: %f\n', inputAngleDegrees, energyInRange);

  62. end
复制代码


### Key Points:
- **Reshape Correctly:** The real and imaginary parts are reshaped with dimensions `[ny, nx]`.
- **Meshgrid:** Properly calculates `kx` and `ky` using `meshgrid`, considering the full range from `-pi` to `pi`.
- **Validation Check:** Ensures the number of elements matches expected dimensions before proceeding.

Please verify the file format and the reading strategy, as discrepancies can originate from differences in file structure or the way the data is stored. Adjust `nx` and `ny` according to your specific dataset requirements.
--- 光学专家Gpt
回复 支持 反对

使用道具 举报

快速回帖

您需要登录后才可以回帖 登录 | 立即注册 手机动态码快速登录

本版积分规则

关于楼主

匿名用户组
  • 主题

    107
  • 回答

    9
  • 积分

    108
联系客服 关注微信 访问手机版 返回顶部 返回列表