initial commit

This commit is contained in:
2026-08-07 15:56:42 +09:00
commit 91ad25aca9
1012 changed files with 159314 additions and 0 deletions
+116
View File
@@ -0,0 +1,116 @@
import io.image_read
import io.load_prepared_data
import io.spec_read
clear
addpath ptycho/utils/
scans=[11745:11763];
range=[];
marksaxis_start = 1; % First markMarks used for scan
marksaxis_step = 0.1; % Step of marks, change of marks from one scan to the next
usemarksaxis = false;
use_fluorescence = false;
use_pilatus = true;
int=zeros(1,length(scans));
norm=zeros(1,length(scans));
xaxis=zeros(1,length(scans));
marksaxis = [0:numel(xaxis)-1]*marksaxis_step + marksaxis_start;
S=spec_read('~/Data10/specES1/dat-files/','ScanNr',scans);
spectra_sum = [];
for hh=1:length(scans)
if use_fluorescence
filename = sprintf('~/Data10/fx123/gccDppConsoleLinux/data/x123_%05d.dat',scans(hh));
data = image_read(filename);
if ~isempty(spectra_sum)
spectra_sum = spectra_sum + sum(data.data,2);
else
spectra_sum = sum(data.data,2);
end
if ~isempty(range)
int(hh)=sum(sum(data.data(range,:),1),2);
else
int(hh)=sum(sum(data.data(:,:),1),2);
end
end
if use_pilatus
prepdata_filename = sprintf('~/Data10/analysis/S%05d/S%05d_data_400x400.h5',scans(hh),scans(hh));
display(sprintf('loading %s',prepdata_filename))
[I, fmask, ~] = load_prepared_data(prepdata_filename, true);
this = sum(I, 3).*any(fmask,3);
trans(hh) = sum(this(:));
end
eaxis(hh)=S{hh}.mokev;
norm(hh)=S{hh}.bpm4i;
%data_spectrum = sum(data.data,2);
end
%
if usemarksaxis
axisplot = marksaxis;
xlabeltext = 'Marks';
else
axisplot = eaxis;
xlabeltext = 'E [keV]';
end
if use_fluorescence
figure(1)
subplot(2,1,1)
semilogy(spectra_sum)
title('Sum of all spectra')
subplot(2,1,2)
plot(axisplot,int./norm)
title('Integrated fluorescence')
xlabel(xlabeltext)
% figure(3)
% subplot(2,1,2)
% line(eaxis,int./norm)
% %title('Integrated fluorescence')
% %xlabel(xlabeltext)
% xlim([eaxis(1) eaxis(end)])
% ax1 = gca;
% ax1_pos = ax1.Position; % position of first axes
% ax2 = axes('Position',ax1_pos,...
% 'XAxisLocation','top',...
% 'YAxisLocation','right',...
% 'Color','none');
% line(marksaxis,int./norm,'Parent',ax2,'Color','k')
% xlim([marksaxis(1) marksaxis(end)])
end
if use_pilatus
xanes=log(norm./trans);
figure(2)
title(sprintf('S%05d to S%05d',scans(1),scans(end)))
subplot(3,1,1)
plot(axisplot,xanes,'-bo')
grid on
subplot(3,1,2)
% plot(axisplot(1:end-1),diff(xanes),'-bo')
plot(axisplot,1./xanes,'-bo')
grid on
subplot(3,1,3)
plot(axisplot, xanes,'-bo')
xlabel(xlabeltext)
ylabel('log(bpm4i/pilatus\_transmission)')
grid on
end
+194
View File
@@ -0,0 +1,194 @@
%% Loading data
addpath ..
addpath ../ptycho/utils/
addpath ../ptycho/
clear
% close all;
scans = [3917:3997]; % scan numbers
for ii=1:numel(scans)
ptycho_filename = find_ptycho_filename('../../',scans(ii),[],'recons');
if ~iscell(ptycho_filename)
filename_list{ii}=utils.abspath(ptycho_filename);
else
filename_list{ii}=utils.abspath(ptycho_filename{end});
end
end
p0=io.HDF.hdf5_load(filename_list{1},'/reconstruction/p');
Nthreads = 6;
dims_ob=p0.object_size;
pixsize=p0.dx_spec(1);
size_crop=round((p0.object_size-p0.asize)/2)*2;
proj_file_names = reshape(filename_list, 1,[]);
object_block = io.ptycho_read(Nthreads, 'single', dims_ob, '/reconstruction/object', proj_file_names);
object_block=permute(object_block,[2 1 3]);
size_now=size(object_block);
pixsize=zeros(numel(scans),1);
for ii=1:numel(scans)
energies(ii)=io.HDF.hdf5_load(filename_list{ii},'/reconstruction/p/energy');
pixsize(ii,:)=io.HDF.hdf5_load(filename_list{ii},'/reconstruction/p/dx_spec');
end
pixsize = pixsize(:,1);
ROI = {round(size_now(1)/2) + (-size_crop(1)/2:size_crop(1)/2),round(size_now(2)/2)+(-size_crop(2)/2:size_crop(2)/2)};
object_crop=utils.imrescale_fft(object_block(ROI{:},:),pixsize(ii)/max(pixsize));
amp=abs(object_crop);
phase=math.unwrap2D_fft2(object_crop,10,0,[],-1);
%% Selecting the nonair part
roi_chosen = {1:379,70:600};
% If the sample is in the middle of FOV, include the entire object so only
% air is outside this ROI.
% If air region is in the middle of FOV, include only air.
obj_or_air=1; % =1 if object is in middle, =0 if air is in middle.
figure(5); clf;
plotting.imagesc3D(phase);
colormap bone; axis xy equal tight;
caxis([-2*pi 0.2]);
hold on;
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
drawnow;
figure(6); clf;
plotting.imagesc3D(amp);
colormap bone; axis xy equal tight;
caxis(math.sp_quantile(amp,[0.01 0.99],10));
hold on;
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
size_t=size(amp);
if obj_or_air==1
mask=ones(size_t(1),size_t(2));
mask(roi_chosen{:})=0;
else
mask=zeros(size_t(1),size_t(2));
mask(roi_chosen{:})=1;
end
for ii=1:numel(scans)
trans = abs(object_crop(:,:,ii));
reg(ii)=mean(mean(trans(mask==1)));
trans = trans/reg(ii);
transmission (:,:,ii) = trans;
end
%% Alignment of projections
margin = min(roi_chosen{2}(1),size(phase,2)-roi_chosen{2}(2));
phase_unwrap=math.unwrap2D_fft2(object_crop,margin,0,[],-1);
shift = utils.find_shift_fast_2D(phase_unwrap, ref, 0.1);
phase_unwrap_aligned = utils.imshift_fft(phase_unwrap, -shift);
transmission_aligned = utils.imshift_fft(transmission, -shift);
%ref=mean(phase_unwrap,3);
%for ii=1:numel(scans)
% curr=phase_unwrap(:,:,ii);
% [s1,s2,delta]= utils.registersubimages_2(curr,ref,[],[],[],[],100,0,1);
% translate(:,ii)=delta(:);
% phase_unwrap(:,:,ii)=utils.shiftwrapbilinear(curr,-delta(1),-delta(2));
% transmission_aligned(:,:,ii)=utils.shiftwrapbilinear(transmission(:,:,ii),-delta(1),-delta(2));
%end
figure(5); clf;
plotting.imagesc3D(phase_unwrap_aligned);
colormap bone; axis xy equal tight;
caxis([-2*pi 0.2]);
hold on;
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
drawnow;
figure(6); clf;
plotting.imagesc3D(transmission_aligned);
colormap bone; axis xy equal tight;
caxis(math.sp_quantile(transmission_aligned,[0.01 0.99],10));
hold on;
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
%% XANES analysis
roi = {50:250;200:400}; %{15:28;22:35}
figure(5); clf;
plotting.imagesc3D(phase_unwrap_aligned);
colormap bone; axis xy equal tight;
caxis([-2*pi 0.2]);
hold on;
plotting.vline(roi{2}(1),'-r');
plotting.vline(roi{2}(end),'-r');
plotting.hline(roi{1}(1),'-r');
plotting.hline(roi{1}(end),'-r');
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
figure(6); clf;
plotting.imagesc3D(transmission_aligned);
colormap bone; axis xy equal tight;
caxis(math.sp_quantile(transmission_aligned,[0.01 0.99],10));
hold on;
plotting.vline(roi{2}(1),'-r');
plotting.vline(roi{2}(end),'-r');
plotting.hline(roi{1}(1),'-r');
plotting.hline(roi{1}(end),'-r');
plotting.vline(roi_chosen{2}(1),'-b');
plotting.vline(roi_chosen{2}(end),'-b');
plotting.hline(roi_chosen{1}(1),'-b');
plotting.hline(roi_chosen{1}(end),'-b');
if ~isempty(roi)
xanes_phase = squeeze(mean(mean(phase_unwrap_aligned(roi{:},:))));
xanes_amp = squeeze(mean(mean(transmission_aligned(roi{:},:))));
else
xanes_phase = squeeze(mean(mean(phase_unwrap_aligned)));
xanes_amp = squeeze(mean(mean(transmission_aligned)));
end
figure(7); plot(energies,-xanes_phase(:),'ro-'); %.*energies(:).^2);
title('phase')
figure(8); plot(energies,xanes_amp(:),'ro-');
title('amp')
figure(9); plot(energies(1:end-1),diff(xanes_amp(:)));
title('amp\_diff')
%%
% estep=[3:15];
% figure(7); hold off;
% plot(energies,xanes_phase(:)); hold on;
% plot(energies(estep),xanes_phase(estep),'ro');
% figure(8); hold off;
% plot(energies,xanes_amp(:)); hold on;
% plot(energies(estep),xanes_amp(estep),'ro');
+77
View File
@@ -0,0 +1,77 @@
% function [varargout] = banana_scan(basepath, scan, Nx, Ny)
%
% This function only works for mesh scans done to see the undulator banana
% with spec. This is an example pf such scans:
% dmesh idgap -0.05 0.05 50 sl1cv -0.4 0.4 8 0.2
% 50 steps (51 points) along the fast axis
% 8 steps (9 points) along the slow axis
%
%
% Input parameters:
%
% basepath: main path where you are working
% scan: scan number of spec mesh scan
% Nx: number of points in fast axis
% Ny: number of steps in slow axis
%
% please reports bugs, problems, suggestions for improvements to:
% CXS group
%
% the case of duplicate scannumbers in the spec file, and how to
% address them remains to be implemented
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [varargout] = banana_plot(basepath, scan, Nx, Ny)
addpath([basepath 'matlab/'])
import io.*
S=io.spec_read(basepath,'ScanNr',scan);
m=reshape(S.bpm4i,Nx,Ny);
idgap=S.idgap(1:Nx);
m_sl1cv=reshape(S.sl1cv,Nx,Ny);
sl1cv=m_sl1cv(1,:);
imagesc(idgap,sl1cv,m')
title(sprintf('scan %05d',scan));
xlabel('idgap')
ylabel('sl1cv')
end
+58
View File
@@ -0,0 +1,58 @@
%BLUE_RED_MAP Colormap between saturated blue and red
%
% cmap = plotting.blue_red_map
%
% *optional*
% ** N Size of output colormap, default is 64
%
% returns
% ++ cmap Nx3 array with the colormap
%
%
% see also: plotting.imagesc3D, plotting.create_colormap
%
% EXAMPLES:
% colormap(plotting.blue_red_map)
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2018 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function cmap = blue_red_map(N)
if ~exist('N','var')
N = 64;
end
cmap = plotting.create_colormap([0 0.5 1],[0 0 1; 1 1 1; 1 0 0],N);
end
+125
View File
@@ -0,0 +1,125 @@
% FUNCTION IM = C2IMAGE(A)
%
% Returns a RGB image of complex array A where
% the phase is mapped to hue, and the amplitude
% is mapped to brightness.
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function im = c2image(a, varargin)
if ismatrix(a)
absa = abs(a);
phasea = angle(a);
% (optional second argument can switch between various plotting modes)
abs_range = [];
if nargin==2
m = varargin{1};
elseif nargin==3
m = varargin{1};
abs_range = varargin{2};
else
m = 1;
end
if isempty(abs_range)
nabsa = absa/max(max(absa));
else
nabsa = (absa - abs_range(1))/(abs_range(2) - abs_range(1));
nabsa(nabsa < 0) = 0;
nabsa(nabsa > 1) = 1;
end
switch m
case 1
im_hsv = zeros([size(a) 3]);
im_hsv(:,:,1) = mod(phasea,2*pi)/(2*pi);
im_hsv(:,:,2) = 1;
im_hsv(:,:,3) = nabsa;
im = hsv2rgb(im_hsv);
case 2
im_hsv = ones([size(a) 3]);
im_hsv(:,:,1) = mod(phasea,2*pi)/(2*pi);
im_hsv(:,:,2) = nabsa;
im = hsv2rgb(im_hsv);
end
elseif ndims(a)==3
sz = size(a);
im_hsv = zeros([sz 3]);
im = zeros([sz 3]);
for ii=1:sz(3)
absa = abs(a(:,:,ii));
phasea = angle(a(:,:,ii));
% (optional second argument can switch between various plotting modes)
abs_range = [];
if nargin==2
m = varargin{1};
elseif nargin==3
m = varargin{1};
abs_range = varargin{2};
else
m = 1;
end
if isempty(abs_range)
nabsa = absa/max(max(absa));
else
nabsa = (absa - abs_range(1))/(abs_range(2) - abs_range(1));
nabsa(nabsa < 0) = 0;
nabsa(nabsa > 1) = 1;
end
switch m
case 1
im_hsv(:,:,ii,1) = mod(phasea,2*pi)/(2*pi);
im_hsv(:,:,ii,2) = 1;
im_hsv(:,:,ii,3) = nabsa;
case 2
im_hsv(:,:,ii,1) = mod(phasea,2*pi)/(2*pi);
im_hsv(:,:,ii,2) = nabsa;
end
im(:,:,ii,:) = hsv2rgb(squeeze(im_hsv(:,:,ii,:)));
end
end
end
+66
View File
@@ -0,0 +1,66 @@
%CREATE_COLORMAP Create a colormap based on interpolation between anchor
%values and colors
%
% cmap = plotting.create_colormap(values,colors,N)
%
% ** values Array with numbers between 0 and 1
% ** colors Array with [r g b] for each number in values
%
% *optional*
% ** N Size of output colormap, default is 64
%
% returns
% ++ cmap Nx3 array with the colormap
%
%
% see also: plotting.imagesc3D
%
% EXAMPLES:
% A red colormap with 2 anchor colors, black and red
% colormap(plotting.create_colormap([0 1],[0 0 0; 1 0 0]));
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2018 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function cmap = create_colormap(values,colors,N)
if ~exist('N','var')
N = 64;
end
v = linspace(0,1,N);
cmap = zeros(N,3);
[X V] = meshgrid([1 2 3],v);
cmap = interp2(repmat([1 2 3],[numel(values) 1]),repmat(values(:),[1 3]),colors,X,V);
end
+157
View File
@@ -0,0 +1,157 @@
% Call function without arguments for a detailed explanation of its use
% Filename: $RCSfile: display_integ_masks.m,v $
%
% $Revision: 1.3 $ $Date: 2010/04/28 18:00:16 $
% $Author: bunk $
% $Tag: $
%
% Description:
% display azimuthal integration masks
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% none
%
% history:
%
% October 2nd 2009: 1st version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [ valid_mask ] = display_integ_masks(filename_frame,varargin)
import beamline.prep_integ_masks
import io.image_read
import plotting.franzmap
% set default values for the variable input arguments:
% valid pixel mask
filename_integ_masks = '~/Data10/analysis/data/pilatus_integration_masks.mat';
% figure number
fig_no = 220;
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin > 1)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 1)
display_help(filename_integ_masks,fig_no);
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
case 'FilenameIntegMasks'
filename_integ_masks = value;
otherwise
error('unknown argument %s',name);
end
end
% load the integration masks integ_masks
load(filename_integ_masks);
% load the example frame
frame = image_read(filename_frame);
frame_plot = frame.data;
frame_plot( frame_plot < 1 ) = 1;
plot_step = round(length(integ_masks.indices)/50);
if (plot_step < 2)
plot_step = 2;
end
ind_r_max = size(integ_masks.indices,1);
for (ind_r = 1:plot_step:ind_r_max)
for (ind_seg = 1:no_of_segments)
if (rem(ind_seg,2) == 1)
pixel_value = 2;
else
pixel_value = 10^(6*ind_seg/no_of_segments);
end
frame_plot(integ_masks.indices{ind_r,ind_seg}) = pixel_value;
if ((plot_step > 8) && (ind_r +2 < ind_r_max))
frame_plot(integ_masks.indices{ind_r+1,ind_seg}) = pixel_value;
frame_plot(integ_masks.indices{ind_r+2,ind_seg}) = pixel_value;
end
end
end
% plot the result
figure(fig_no);
imagesc(log10(frame_plot));
colormap(franzmap);
axis xy;
axis equal;
axis tight;
colorbar;
title('integration masks');
set(gcf,'Name','valid pixels');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [] = display_help(filename_valid_mask,fig_no)
fprintf('Usage:\n');
fprintf('%s(filename, [[<name>,<value>],...]);\n',mfilename)
fprintf('The optional <name>,<value> pairs are:\n');
fprintf('''FilenameIntegMasks'',<path and filename> Matlab file with the integration masks,\n');
fprintf(' default is %s\n',filename_valid_mask);
fprintf('''FigNo'',<integer> number of the figure in which the result is displayed, default is %d\n',...
fig_no);
fprintf('\n');
fprintf('Integration masks can be created using the macro prep_integ_masks.\n')
fprintf('\n');
+151
View File
@@ -0,0 +1,151 @@
% Call function without arguments for a detailed explanation of its use
% Filename: $RCSfile: display_valid_mask.m,v $
%
% $Revision: 1.2 $ $Date: 2011/08/09 10:03:48 $
% $Author: $
% $Tag: $
%
% Description:
% display a valid pixel mask
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% none
%
% history:
%
% May 9th 2008: 1st version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [ valid_mask ] = display_valid_mask(varargin)
import beamline.prep_valid_mask
% set default values for the variable input arguments:
% valid pixel mask
filename_valid_mask = '~/Data10/analysis/data/pilatus_valid_mask.mat';
% figure number
fig_no = 210;
% display help upon startup
no_help = 0;
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 1)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 0)
display_help(filename_valid_mask,fig_no);
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
case 'FilenameValidMask'
filename_valid_mask = value;
case 'NoHelp'
no_help = value;
otherwise
error('unknown argument %s',name);
end
end
% display help
if (~no_help)
display_help(filename_valid_mask,fig_no);
end
% load the valid pixel mask ind_valid
load(filename_valid_mask);
if (~exist('valid_mask','var'))
fprintf('Warning: this seems to be an old format of the valid pixel mask. Trying to use it anyway.\n');
valid_mask.framesize = [framesize1 framesize2];
fprintf('!!! Mirroring about the vertical axis !!!\n');
frame = zeros(valid_mask.framesize);
frame(ind_valid) = 1;
frame = fliplr(frame);
valid_mask.indices = find(frame ~= 0);
end
% mark the valid pixels as 1, leave the invalid at 0
frame = zeros(valid_mask.framesize);
frame(valid_mask.indices) = 1;
% plot the result
figure(fig_no);
imagesc(frame);
axis xy;
axis equal;
axis tight;
colorbar;
title('valid pixels');
set(gcf,'Name','valid pixels');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [] = display_help(filename_valid_mask,fig_no)
fprintf('Usage:\n');
fprintf('%s([[<name>,<value>],...]);\n',mfilename)
fprintf('The optional <name>,<value> pairs are:\n');
fprintf('''FilenameValidMask'',<path and filename> Matlab file with the valid pixel indices ind_valid,\n');
fprintf(' default is %s\n',filename_valid_mask);
fprintf('''FigNo'',<integer> number of the figure in which the result is displayed, default is %d\n',...
fig_no);
fprintf('\n');
fprintf('A valid pixel mask can be created using the macro prep_valid_mask.\n')
fprintf('\n');
+58
View File
@@ -0,0 +1,58 @@
%FIRE_MAP Hot blue-purlple-yellow colormap
%
% cmap = plotting.fire_map
%
% *optional*
% ** N Size of output colormap, default is 64
%
% returns
% ++ cmap Nx3 array with the colormap
%
%
% see also: plotting.imagesc3D, plotting.create_colormap
%
% EXAMPLES:
% colormap(plotting.fire_map)
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2018 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function cmap = fire_map(N)
if ~exist('N','var')
N = 64;
end
cmap = plotting.create_colormap([0 0.0625 0.25 0.38 0.5 0.8 1],[0 0 0; 0 0 0.3765; 0.5 0 1; 0.78 0 0.35; 1 0.25 0; 1 1 0; 1 1 1],N);
end
+78
View File
@@ -0,0 +1,78 @@
% Function FM = FRANZMAP(M)
% Franz's modified jet color map
% This function returns the colormap and should
% be used like any other colormaps, e.g.
% colormap(franzmap(128));
% or
% imwrite(uint8(255*myarray/max(max(myarray))),franzmap(256),'myarray.jpg');
% Filename: $RCSfile: franzmap.m,v $
%
% $Revision: 1.1 $ $Date: 2008/06/10 17:05:14 $
% $Author: $
% $Tag: $
%
% Description:
% Function FM = FRANZMAP(M)
% Franz's modified jet color map
% This function returns the colormap and should
% be used like any other colormaps, e.g.
% colormap(franzmap(128));
% or
% imwrite(uint8(255*myarray/max(max(myarray))),franzmap(256),'myarray.jpg');
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% none
%
% history:
%
% May 9th 2008: add CVS header
%
% Franz Pfeiffer: 1st version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function fm = franzmap(m)
if (nargin < 1)
m = size(get(gcf,'colormap'),1);
end
maxval = ceil(m/8);
fm = jet(m);
fm(1:maxval,3) = [1:maxval]/maxval;
+94
View File
@@ -0,0 +1,94 @@
function varargout = ginput_ax_mod2(ha,n)
if nargin<2
n=1;
end
k = 0;
button = 0;
%%// Tolerance so that in the inifnity case, this could act as
%%// the thresholding distance below which the
%%// input extracting operation must be terminated
TOL = 0.01;
%%// Placeholders for X-Y and button type could be stored
button1 = [];
xy = [];
hf = get(ha,'parent');
figure(hf);
set(hf,'WindowButtonMotionFcn',@changepointer)
set(ha,'ButtonDownFcn',@getpoints)
hp = get(ha,'children');
ht = get(hp,'hittest');
set(hp,'hittest','off')
axlim = get(ha,'Position');
fglim = get(hf,'Position');
x1 = axlim(1)*fglim(3) + fglim(1);
x2 = (axlim(1)+axlim(3))*fglim(3) + fglim(1);
y1 = axlim(2)*fglim(4) + fglim(2);
y2 = (axlim(2)+axlim(4))*fglim(4) + fglim(2);
waitfor(hf,'WindowButtonMotionFcn',[])
if iscell(ht)
for jj=1:length(ht)
set(hp(jj),'hittest',ht{jj})
end
else
set(hp,'hittest',ht)
end
selType = get(hf,'SelectionType');
% Mouse-Button recognition...
if(strcmp(button, 'normal'))
button = 1; % left
elseif(strcmp(button, 'extend'))
button = 2; % right
elseif(strcmp(button, 'alt'))
button = 3; % middle
else
button = 4; % double click any mousebutton
end
if nargout==3
varargout{1} = xy(:,1);
varargout{2} = xy(:,2);
varargout{3} = button1(:,1);
elseif nargout==2
varargout{1} = xy(:,1);
varargout{2} = xy(:,2);
else
varargout{1} = xy;
end
function changepointer(~,~)
pntr = get(0,'PointerLocation');
if pntr(1)>x1 && pntr(1)<x2 && pntr(2)>y1 && pntr(2)<y2
set(hf,'Pointer','crosshair')
else
set(hf,'Pointer','arrow')
end
end
function getpoints(src,evnt)
cp = get(src,'CurrentPoint');
button = get(hf, 'SelectionType');
k = k+1;
if k==1
xy = [xy ;cp(1,1:2)];
button1 = [button1; {button}];
end
if k>=2
if pdist2(cp(1,1:2),xy(k-1,:))<TOL && isinf(n)
k = n;
else
xy = [xy ;cp(1,1:2)];
button1 = [button1; {button}];
end
end
if k==n
set(hf,'Pointer','arrow')
set(hf,'WindowButtonMotionFcn',[])
set(ha,'ButtonDownFcn',[])
return;
end
end
end
+134
View File
@@ -0,0 +1,134 @@
% function h=hline(y, linetype, label)
%
% Draws a horizontal line on the current axes at the location specified by 'y'. Optional arguments are
% 'linetype' (default is 'r:') and 'label', which applies a text label to the graph near the line. The
% label appears in the same color as the line.
%
% The line is held on the current axes, and after plotting the line, the function returns the axes to
% its prior hold state.
%
% The HandleVisibility property of the line object is set to "off", so not only does it not appear on
% legends, but it is not findable by using findobj. Specifying an output argument causes the function to
% return a handle to the line, so it can be manipulated or deleted. Also, the HandleVisibility can be
% overridden by setting the root's ShowHiddenHandles property to on.
%
% h = hline(42,'g','The Answer')
%
% returns a handle to a green horizontal line on the current axes at y=42, and creates a text object on
% the current axes, close to the line, which reads "The Answer".
%
% hline also supports vector inputs to draw multiple lines at once. For example,
%
% hline([4 8 12],{'g','r','b'},{'l1','lab2','LABELC'})
%
% draws three lines with the appropriate labels and colors.
%
% By Brandon Kuczenski for Kensington Labs.
% brandon_kuczenski@kensingtonlabs.com
% 8 November 2001
% Copyright (c) 2001, Brandon Kuczenski
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function hhh=hline(y,in1,in2)
if length(y)>1 % vector input
for I=1:length(y)
switch nargin
case 1
linetype='r:';
label='';
case 2
if ~iscell(in1)
in1={in1};
end
if I>length(in1)
linetype=in1{end};
else
linetype=in1{I};
end
label='';
case 3
if ~iscell(in1)
in1={in1};
end
if ~iscell(in2)
in2={in2};
end
if I>length(in1)
linetype=in1{end};
else
linetype=in1{I};
end
if I>length(in2)
label=in2{end};
else
label=in2{I};
end
end
h(I)=hline(y(I),linetype,label);
end
else
switch nargin
case 1
linetype='r:';
label='';
case 2
linetype=in1;
label='';
case 3
linetype=in1;
label=in2;
end
g=ishold(gca);
hold on
x=get(gca,'xlim');
h=plot(x,[y y],linetype);
if ~isempty(label)
yy=get(gca,'ylim');
yrange=yy(2)-yy(1);
yunit=(y-yy(1))/yrange;
if yunit<0.2
text(x(1)+0.02*(x(2)-x(1)),y+0.02*yrange,label,'color',get(h,'color'))
else
text(x(1)+0.02*(x(2)-x(1)),y-0.02*yrange,label,'color',get(h,'color'))
end
end
if g==0
hold off
end
set(h,'tag','hline','handlevisibility','off') % this last part is so that it doesn't show up on legends
end % else
if nargout
hhh=h;
end
+526
View File
@@ -0,0 +1,526 @@
% Call function without arguments for instructions on how to use it
% Filename: $RCSfile: image_show.m,v $
%
% $Revision: 1.18 $ $Date: 2011/05/29 13:52:28 $
% $Author: $
% $Tag: $
%
% Description:
% read and display a 2D data frame
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% - image_read
%
%
% history:
%
% April 16th 2009:
% bug-fix in histogram scaling, the intensity base level was not properly
% taken into account,
% auto-scaling is activated by a separate parameter to allow for arbitrary
% scales
%
% February 23rd 2009:
% add histogram scaling
%
% September 4th 2009:
% add DisplayFtime and DisplayExptime parameters,
% use new rowcol_from field of th eframe structure rather than handling the
% region of interest specification here,
% remove leading home directory and beamline specific path from displayed
% filename
%
% February 23rd 2009:
% add ImageHandle parameter for updating existing plots,
% earlier the XScange and YScange parameters have been added
%
% August 28th 2008:
% plot 1D data using plot
%
% May 9th 2008:
% use image_read and named parameters, other changes since the last
% history entry, rename from pilatus_show to image_show
%
% November 2006: 1st version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [frame,image_handle] = image_show(filename,varargin)
import io.*
import plotting.image_show
import utils.default_parameter_value
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = 1 + length(varargin);
end
end
end
% set default values
fig_no = default_parameter_value(mfilename,'FigNo');
fig_clear = default_parameter_value(mfilename,'FigClear');
auto_scale = default_parameter_value(mfilename,'AutoScale');
axis_min = default_parameter_value(mfilename,'AxisMin');
axis_max = default_parameter_value(mfilename,'AxisMax');
hist_scale = default_parameter_value(mfilename,'HistScale');
log_scale = default_parameter_value(mfilename,'LogScale');
x_scale =default_parameter_value(mfilename,'XScale');
y_scale =default_parameter_value(mfilename,'YScale');
x_offs =default_parameter_value(mfilename,'XOffs');
display_colorbar = default_parameter_value(mfilename,'ColorBar');
display_axes = default_parameter_value(mfilename,'Axes');
display_time = default_parameter_value(mfilename,'DisplayTime');
display_ftime = default_parameter_value(mfilename,'DisplayFtime');
display_exptime = default_parameter_value(mfilename,'DisplayExptime');
color_map = default_parameter_value(mfilename,'ColorMap');
bgr_data = default_parameter_value(mfilename,'BgrData');
image_handle = default_parameter_value(mfilename,'ImageHandle');
frame_number = default_parameter_value(mfilename,'FrameNumber');
frame = [];
% check minimum number of input arguments and
% check number of input arguments
if ((nargin < 1) || (rem(no_of_in_arg,2) ~= 1))
image_read_help('ext',mfilename,'Examples',0,'ExtensionReturned',1);
fprintf('''BgrData'',<data array> subtract this background from the data read\n');
fprintf('''FrameNumber'',<integer> in case of multiple frames per file select one or 0 for the average of all frames, default is %d\n',frame_number);
fprintf('''FigNo'',<figure number> display figure in this window, default is %d\n',fig_no);
fprintf('''FigClear'',<0-no, 1-yes> clear figure before plotting, default is %d (only used if no image handle is specified)\n',fig_clear);
fprintf('''ImageHandle'',<handle number> update the specified image which may be faster and can be used to keep constant zoom level\n');
fprintf('''AutoScale'',<[0-no/1-yes 0-no/1-yes]> intensity auto scaling of lower/upper limit, default is [%d %d]\n',auto_scale(1),auto_scale(2));
fprintf('''AxisMin'',<value> intensity scaling if not in auto-scale mode, default is %.3e\n',axis_min);
fprintf('''AxisMax'',<value> intensity scaling if not in auto-scale mode, default is %.3e\n',axis_max);
fprintf('''AxisMinMax'',<[ min max]> specify both min and max value\n');
fprintf('''HistScale'',<[low high]> in case of auto scaling scale the data to see the portion of the intensity values from low to high, default is [ %.2f %.2f]\n',hist_scale(1),hist_scale(2));
fprintf('''LogScale'',<0-no,1-yes> default is %d\n',log_scale);
fprintf('''XScale'',<scaling factor> default is %.3e\n',x_scale);
fprintf('''YScale'',<scaling factor> default is %.3e\n',y_scale);
fprintf('''XOffs'',<scaling factor> default is %.3e\n',x_offs);
fprintf('''ColorBar'',<0-no,1-yes> display colorbar, default is %d\n',display_colorbar);
fprintf('''ColorMap'',<''map-name''> choose colormap, default is ''%s''\n',color_map);
fprintf('''Axes'',<0-no,1-yes> display axes, default is %d\n',display_axes);
fprintf('''TitleString'',<''text''> fixed part of the title\n');
fprintf('''DisplayTime'',<0-no,1-yes> default is yes\n');
fprintf('\n');
fprintf('\n');
fprintf('Examples:\n');
fprintf('[frame,image_handle]=%s(''~/Data10/pilatus/image_1_ct.cbf'');\n',mfilename);
fprintf('[frame,image_handle]=%s(''~/Data10/pilatus/image_1_ct.cbf'');\n',mfilename);
fprintf('[frame,image_handle]=%s(''~/Data10/pilatus/image_1_ct.cbf'',''RowFrom'',100,''RowTo'',800,''ColumnFrom'',200,''ColumnTo'',1200,''AxisMin'',1,''AxisMax'',1e6);\n',mfilename);
fprintf('[frame,image_handle]=%s(''~/Data10/pilatus/image_1_ct.cbf'',''AxisMax'',1e4);\n',mfilename);
fprintf('\n');
fprintf('The returned structure has the fields data, header and extension.\n');
if (nargin < 1)
error('At least the filename has to be specified as input parameter.');
else
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
end
% parse the variable input arguments not handled by or on purpose not
% passed to the image_read routine
vararg = cell(0,0);
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
case 'FigClear'
fig_clear = value;
case 'ImageHandle'
image_handle = value;
case 'AxisMin'
axis_min = value;
case 'AxisMax'
axis_max = value;
case 'AxisMinMax'
axis_min = value(1);
axis_max = value(2);
case 'AutoScale'
auto_scale = value;
case 'HistScale'
hist_scale = value;
case 'LogScale'
log_scale = value;
case 'XScale'
x_scale = value;
case 'YScale'
y_scale = value;
case 'XOffs'
x_offs = value;
case 'ColorBar'
display_colorbar = value;
case 'ColorMap'
color_map = value;
case 'Axes'
display_axes = value;
case 'DisplayTime'
display_time = value;
case 'DisplayFtime'
display_ftime = value;
case 'DisplayExptime'
display_exptime = value;
case 'BgrData'
bgr_data = value;
case 'FrameNumber'
frame_number = value;
case 'Frame'
frame = value;
otherwise
vararg{end+1} = name; %#ok<AGROW>
vararg{end+1} = value; %#ok<AGROW>
end
end
% get the home directory path
[stat,homedir] = system('echo ~');
if (stat ~= 0)
homedir = '';
else
if (~isempty(homedir))
homedir = homedir(1:end-1);
end
end
% remove a beamline specific part
[stat,username] = system('echo $USER');
if (stat == 0)
if (~isempty(username))
username = username(1:end-1);
end
std_path = [ '/sls/X12SA/Data10/' username ];
if ((length(filename) > length(std_path)) && ...
(strcmp(filename(1:length(std_path)),std_path)))
filename = [ '~/Data10' filename(length(std_path)+1:end) ];
end
end
% read the frame
if (isempty(frame))
[frame] = image_read(filename,vararg);
end
if (isempty(frame.data))
fprintf('%s: frame empty (file %s)\n',mfilename,filename);
return;
end
if (axis_max <= axis_min)
error('AxisMax must be greater than AxisMin');
end
% subtract background
if (~isempty(bgr_data))
if (size(bgr_data) ~= size(frame.data))
error('Background data dimension does not match data dimension.');
end
frame.data = frame.data - bgr_data;
end
% define axes range
x = x_scale * ...
frame.rowcol_from{1}(2):(frame.rowcol_from{1}(2)+size(frame.data,2)-1) + ...
x_offs;
y = y_scale * ...
frame.rowcol_from{1}(1):(frame.rowcol_from{1}(1)+size(frame.data,1)-1);
% select the plot window
if ((isempty(image_handle)) || (image_handle <= 0))
if (gcf ~= fig_no)
figure(fig_no);
end
if (fig_clear)
hold off;
clf;
end
end
% for dat files (like MCS data) display the last data set as a 1D plot
if ((strcmp(frame.extension{1},'dat')) && (ndims(frame.data) > 1))
x = x_scale * (1:size(frame.data,1)) + x_offs;
y = y_scale;
end_ind = floor(frame.no_of_el_read{1} / length(x)) * length(x);
begin_ind = end_ind - length(x) +1;
if (begin_ind < 1)
begin_ind = 1;
end
frame_plot = frame.data(begin_ind:end_ind);
else
if (ndims(frame.data) > 2)
if (frame_number == 0)
frame_plot = squeeze(mean(frame.data,3));
else
frame_plot = squeeze(frame.data(:,:,frame_number));
end
else
frame_plot = frame.data;
end
end
% display the frame
if (log_scale)
frame_plot(frame_plot < 1e-15) = 1e-15;
end
ax_min = axis_min;
ax_max = axis_max;
if ((length(x) == 1) || (length(y) ==1))
if (length(y) == 1)
if (log_scale)
semilogy(x,frame_plot);
else
plot(x,frame_plot);
end
xlabel('x [ pixel ]','FontSize',12);
x_range = [ x(1) x(end) ];
else
if (log_scale)
semilogy(y,frame_plot);
else
plot(y,frame_plot);
end
xlabel('y [ pixel ]','FontSize',12);
x_range = [ y(1) y(end) ];
end
% axis scaling etc.
ylabel('intensity','FontSize',12);
as = axis;
as(1:2) = x_range;
% auto scale lower/upper limit if specified
if (auto_scale(1))
ax_min = min(min(frame_plot));
end
if (auto_scale(2))
ax_max = max(max(frame_plot));
end
as(3) = ax_min;
as(4) = ax_max;
if (as(4) <= as(3))
as(4) = as(3) +1;
end
axis(as);
else
if (log_scale)
ax_min = log10( axis_min );
ax_max = log10( axis_max );
frame_plot = log10( double(frame_plot) );
end
if ((isempty(image_handle)) || (image_handle <= 0))
% initialize a new plot
image_handle = imagesc(x,y,frame_plot);
axis xy;
axis equal;
axis tight;
if (~display_axes)
axis off;
end
jet_mod = jet;
for (i = 1:8)
jet_mod(i,3) = i/8;
end
if (isempty(color_map))
colormap(jet_mod);
else
colormap(color_map);
end
if (display_colorbar)
colorbar;
end
xlabel('x [ pixel ]','FontSize',12);
ylabel('y [ pixel ]','FontSize',12);
zlabel('intensity');
else
% update an existing plot
set(image_handle,'CData', frame_plot );
end
% auto scale, if specified
if (nnz(auto_scale))
% use one million intensity bins over the intensity range
int_min = min(min(frame_plot));
int_max = max(max(frame_plot));
int_step = (int_max-int_min) / 2^20;
% calculate the bin indices from the intensities
hist_ind = round((frame_plot(:)-int_min) / int_step) +1;
% increase each bin an index is pointing to by one
hist_bins = zeros(1,max(hist_ind)-min(hist_ind)+1);
for (ind_hist = 1:numel(hist_ind))
hist_bins(hist_ind(ind_hist)) = hist_bins(hist_ind(ind_hist)) +1;
end
% calculate the cumulative sum
hist_bins = cumsum(hist_bins);
% find the indices to the bins with more pixels than the threshold
n_low = find(hist_bins > hist_scale(1) * numel(frame_plot),1,'first');
if (n_low >= length(hist_bins))
n_low = length(hist_bins) -1;
end
n_high = find(hist_bins > hist_scale(2) * numel(frame_plot),1,'first');
if (n_high <= n_low)
n_high = n_low +1;
end
if (n_high > length(hist_bins))
n_high = length(hist_bins);
end
% use the corresponding intensities to scale the image
if (auto_scale(1))
ax_min = (n_low-1) * int_step + int_min;
end
if (auto_scale(2))
ax_max = (n_high-1) * int_step + int_min;
end
% for (hist_iter = 1:4)
% hist_bins = int_min:((int_max-int_min)/1e3):int_max;
% [no_of_int_values] = hist(frame.data(:),hist_bins);
% % calculate the cumulative sum and find the position above the
% % lower and upper number of pixels threshold
% cumsum_no_of_int_values = cumsum(no_of_int_values);
% n_low = find(cumsum_no_of_int_values > hist_scale(1) * numel(frame_plot),1,'first') -1;
% if (n_low >= length(hist_bins))
% n_low = length(hist_bins) -1;
% end
% if (n_low < 1)
% n_low = 1;
% end
% n_high = find(cumsum_no_of_int_values > hist_scale(2) * numel(frame_plot),1,'first');
% if (n_high <= n_low)
% n_high = n_low +1;
% end
% if (n_high > length(hist_bins))
% n_high = length(hist_bins);
% end
%
% % sufficiently fine resolution is reached
% if ((n_high > 5) && (n_high < length(hist_bins)))
% % fprintf('%d: %d %d',hist_iter,n_low,n_high);
% break;
% end
%
% % change to a finer histogram spacing
% int_min = hist_bins(n_low);
% int_max = hist_bins(n_high);
% end
% % use the corresponding intensities to scale the image
% if (ax_min <= 0)
% ax_min = hist_bins(n_low);
% end
% if (ax_max <= 0)
% ax_max = hist_bins(n_high);
% end
% frame_med = medfilt2(frame_plot,[ 3 3 ]);
% if (ax_min <= 0)
% ax_min = 0.1 * mean(mean(frame_med));
% end
% if (ax_max <= 0)
% ax_max = max(max(frame_med));
% end
end
caxis( [ ax_min ax_max ] );
end
% compile title string:
% replace home directory by tilde
if ((length(filename) > length(homedir)) && ...
(strcmp(filename(1:length(homedir)),homedir)))
title_str = [ '~' filename(length(homedir)+1:end) ];
else
title_str = filename;
end
% escape underscore characters from LaTeX-like use
title_str = strrep(title_str,'_','\_');
if (log_scale)
title_str = [ title_str ' (log.)' ];
end
% add current time
if (display_time)
clock_now = clock();
title_str = [ title_str ' ' ...
num2str(clock_now(4)) ':' num2str(clock_now(5),'%02.0f') ...
':' num2str(clock_now(6),'%02.0f') ];
end
% get and display date string from file
if (display_ftime)
title_str = [ title_str '\newlinefile date: ' ...
common_header_value(frame.header{1},frame.extension{1},'Date') ];
end
% get and display exposure time
if (display_exptime)
title_str = [ title_str ', exposure time = ' ...
num2str(common_header_value(frame.header{1},frame.extension{1},...
'ExposureTime'),'%.3f') ' sec' ];
end
% add the frame number to the title string
if (frame_number == 0)
title_str = [ title_str ', frame average' ];
else
title_str = [ title_str sprintf(', frame %d',frame_number) ];
end
% display the compiled title string
title(title_str,'FontSize',14);
return;
+408
View File
@@ -0,0 +1,408 @@
% Call function without arguments for instructions on how to use it
% Filename: $RCSfile: image_spec.m,v $
%
% $Revision: 1.19 $ $Date: 2012/08/23 15:14:57 $
% $Author: $
% $Tag: $
%
% Description:
% display the current image data file
% (kind of online viewer)
%
% Note:
% information is passed on to this macro via a text file at a hard-wired
% location
%
% Dependencies:
% - image_show
% - common_header_value
%
%
% history:
%
% August 21th 2012
% Add a pause and retry for h5 files, the filename exists before the file
% is ready to read
%
% July 7th 2009:
% redraw figure if image size changes
%
% February 4th 2009:
% use valid-pixel mask for intensity sum calculation
%
% September 4th 2008:
% use new image_show functionality rather than displaying file date and
% exposure time from this macro
%
% August 28th 2008:
% pause one second in case of errors upon reading the filename from the
% spec exchange file
%
% June 24th 2008:
% update examples and include PCO CCD
%
% June 16th 2008:
% 1st version based on pilatus_spec
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [] = image_spec(det_no,varargin)
import beamline.pilatus_valid_pixel_roi
import io.common_header_value
import plotting.image_show
import plotting.image_spec
import utils.fopen_until_exists
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = 1 + length(varargin);
end
end
end
% set default parameters
matlab_spec_filename = '~/Data10/specES1/internal/spec_matlab_print.dat';
% valid pixel mask
filename_valid_mask = '~/Data10/analysis/data/pilatus_valid_mask.mat';
% check number of input arguments
if ((nargin < 1) || (rem(no_of_in_arg,2) ~= 1))
fprintf('Usage:\n')
fprintf('%s(detector_number,[[<name>,<value>], ...]);\n',mfilename);
fprintf('The optional name value pairs are:\n');
fprintf('''MatlabSpecFilename'',<''dir and filename''>\n');
fprintf(' default is %s\n',matlab_spec_filename);
fprintf('''FilenameValidMask'',<''dir and filename ''>\n');
fprintf(' default is %s\n',filename_valid_mask);
fprintf('Additionally parameters of image_show are supported like:\n')
fprintf('''RowFrom'',<0-max> region of interest definition, 0 for full frame\n');
fprintf('''RowTo'',<0-max> region of interest definition, 0 for full frame\n');
fprintf('''ColumnFrom'',<0-max> region of interest definition, 0 for full frame\n');
fprintf('''ColumnTo'',<0-max> region of interest definition, 0 for full frame\n');
fprintf('''AxisMin'',<value greater than 0> intensity scaling\n');
fprintf('''AxisMax'',<value greater than 0> intensity scaling\n');
fprintf('''ROI'',[ <ColumnFrom> <RowFrom> <ColumnTo> <RowTo> ]\n');
fprintf(' region of interest definition of all four coordinates together\n');
fprintf('Please call image_show without parameters for a complete list.\n')
fprintf('The integral intensity is calculated for the specified region of interest and masks out\n');
fprintf('invalid pixels via the valid pixel mask.\n');
fprintf('\n');
fprintf('\n');
fprintf('Examples:\n');
fprintf('%s;\n',mfilename);
fprintf('%s(2);\n',mfilename);
fprintf('%s(2,''RowFrom'',100,''RowTo'',800,''ColumnFrom'',200,''ColumnTo'',1200,''AxisMin'',1,''AxisMax'',1e6);\n',mfilename);
fprintf('%s(2,''AxisMax'',1e4);\n',mfilename);
fprintf('\n');
fprintf('Recognized detector numbers are:\n');
fprintf(' 1 - Pilatus 2M\n');
fprintf(' 2 - Pilatus 300k\n');
fprintf(' 3 - Pilatus 100k\n');
fprintf(' 4 - Eiger single chip (256x256 pixels)\n');
fprintf(' 5 - PX4 unit (Amptek)\n');
fprintf(' 6 - MCS (SIS VME module)\n');
fprintf(' 7 - FLI CCD\n');
fprintf(' 8 - Mythen\n');
fprintf(' 9 - Roper CCD\n');
fprintf('10 - Andor CCD\n');
fprintf('11 - PCO CCD\n');
error('The optional parameters have to be specified as ''name'',''value'' pairs');
return;
end
% for other than PILATUS detectors there is no default valid pixel mask
if (det_no > 2)
filename_valid_mask = [];
end
% parse the variable input arguments not handled by image_show
vararg = cell(0,0);
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'MatlabSpecFilename'
matlab_spec_filename = value;
case 'DetNo'
det_no = value;
case 'FilenameValidMask'
filename_valid_mask = value;
otherwise
vararg{end+1} = name;
vararg{end+1} = value;
end
end
% add some parameters for image_show
vararg(13:(end+12)) = vararg;
vararg{ 1} = 'RetryReadSleep';
vararg{ 2} = 0.1;
vararg{ 3} = 'RetryReadMax';
vararg{ 4} = 10;
vararg{ 5} = 'MessageIfNotFound';
vararg{ 6} = 0;
vararg{ 7} = 'ErrorIfNotFound';
vararg{ 8} = 0;
vararg{ 9} = 'DisplayFilename';
vararg{10} = 0;
vararg{11} = 'ImageHandle';
image_handle_pos = 12;
vararg{image_handle_pos} = 0;
% set some default values for the plot window
% set(0, 'DefaultAxesfontsize', 12);
% set(0, 'DefaultAxeslinewidth', 1, 'DefaultAxesfontsize', 12);
% set(0, 'DefaultLinelinewidth', 1);
last_time_stamp = 0;
last_filename = ' ';
last_no_of_el_read = 0;
disp_ct = -1;
idle_ct = 0;
date_old = ' ';
date_new = ' ';
image_handle = 0;
plot_ind_in = 1;
plot_ind_out = 1;
plot_ind_max = 5;
plot_filename = cell(plot_ind_max,1);
for (ind = 1:plot_ind_max)
plot_filename{ind} = '';
end
retry_read = 0;
last_date_ct = ' ';
last_frame_size = [];
% load the valid pixel mask ind_valid
if ((~isempty(filename_valid_mask)) && (exist(filename_valid_mask,'file')))
fprintf('loading the valid pixel mask %s\n',filename_valid_mask);
load(filename_valid_mask);
else
fprintf('valid pixel mask not found, integral intensity includes hot pixels\n');
valid_mask = [];
end
% periodically check the spec communication file
pause on;
while (true)
err = 0;
% open the plot-information file for read-only access
[fid] = fopen_until_exists(matlab_spec_filename,'RetryReadSleep',10.0);
% read up to including the line with the needed information
for (ind=1:det_no)
line = fgetl(fid);
if (~ischar(line))
fprintf('Could not read filename information for detector %d\n',det_no);
err = 1;
break;
end
end
if (err == 0)
if (isempty(line))
fprintf('Filename information for detector %d is empty\n',det_no);
err = 1;
end
end
% close the plot-information file
if (fid > 0)
if (fclose(fid) ~= 0)
fprintf('Error upon closing %s\n',matlab_spec_filename);
err = 1;
end
end
% parse the line
if (err == 0)
det_name = [];
time_stamp = [];
filename = [];
[det_name] = char(sscanf(line,'%[^:] %*f ''%*s'''));
[time_stamp] = sscanf(line,'%*s %f ''%*s''');
[filename] = char(sscanf(line,'%*s %*f ''%[^'']')');
if ((isempty(det_name)) || (isempty(time_stamp)) || (isempty(filename)))
fprintf('Could not parse filename information line for detector %d\n',det_no);
err = 1;
end
else
pause(1);
end
% store the filename, if it is new
if ((err == 0) && (time_stamp ~= last_time_stamp))
last_time_stamp = time_stamp;
plot_filename{plot_ind_in} = filename;
% suppress double names like multiple image_ct files
if ((plot_ind_in == plot_ind_out) || (~strcmp(filename,last_filename)))
plot_ind_in = plot_ind_in +1;
if (plot_ind_in > plot_ind_max)
plot_ind_in = 1;
end
end
last_filename = filename;
end
% handle pending plots
if (plot_ind_in ~= plot_ind_out)
err = 0;
if (retry_read == 0)
fprintf('plotting %s ',plot_filename{plot_ind_out});
end
% reuse the previous image handle for updating the figure
vararg{image_handle_pos} = image_handle;
if det_no == 4 % Add a default H5 data group for the Eiger
auxno = numel(vararg);
vararg{auxno+1} = 'H5Location';
vararg{auxno+2} = '/eh5/images';
end
try
[frame,image_handle] = image_show(plot_filename{plot_ind_out},vararg);
catch
fprintf('\nFailed reading, pausing 0.5 second and trying again\n')
pause(0.5)
[frame,image_handle] = image_show(plot_filename{plot_ind_out},vararg);
end
% redraw figure, if the figure size changed
if ((~isempty(last_frame_size)) && ...
(~isempty(frame)) && (~isempty(frame.data)) && ...
(any(size(frame.data) ~= last_frame_size)))
fprintf('image size changed, redrawing ')
set(gca, 'XLimMode','auto', 'YLimMode','auto');
hold off;
clf;
image_handle = 0;
vararg{image_handle_pos} = image_handle;
[frame,image_handle] = image_show(plot_filename{plot_ind_out},vararg);
end
% do not change the zoom level upon updates
set(gca, 'XLimMode','manual', 'YLimMode','manual');
if (~isempty(frame.data))
% set window title
set(gcf,'Name','image_spec');
% get and display date string from file
date_new = common_header_value(frame.header{1},...
frame.extension{1},'Date');
% check, if an old file has been displayed
is_ct = length(strfind(plot_filename{plot_ind_out},'_ct.'));
if (((strcmp(date_new,date_old)) && ...
(last_no_of_el_read == frame.no_of_el_read{1})) || ...
((is_ct ~= 0) && (strcmp(date_new,last_date_ct))))
% this is still the same image, retry
retry_read = retry_read +1;
pause(0.1);
else
% this is a new image, reset flags, increase counter
date_old = date_new;
last_no_of_el_read = frame.no_of_el_read{1};
if (is_ct ~= 0)
last_date_ct = date_new;
end
retry_read = 0;
plot_ind_out = plot_ind_out +1;
if (plot_ind_out > plot_ind_max)
plot_ind_out = 1;
end
ind_valid = 1:numel(frame.data);
if (isstruct(valid_mask))
% cut out the region of interest from the valid pixel mask
if ((isempty(last_frame_size)) || (sum(size(frame.data) ~= last_frame_size)) ~= 0)
last_frame_size = size(frame.data);
% cut out the valid mask for the currently active
% detector modules
valid_mask_cut = pilatus_valid_pixel_roi(valid_mask,...
'RoiSize',frame.img_full_size{1});
% from this cut out the region of interest,
% if specified
valid_mask_cut = pilatus_valid_pixel_roi(valid_mask_cut,vararg);
end
ind_valid = valid_mask_cut.indices;
end
fprintf('integral %.3e counts\n',sum(frame.data(ind_valid)));
end
else
% the image is not available, retry
retry_read = retry_read +1;
err = 1;
pause(0.1);
end
if (retry_read > 10)
fprintf(' could not load file\n');
date_old = date_new;
retry_read = 0;
plot_ind_out = plot_ind_out +1;
if (plot_ind_out > plot_ind_max)
plot_ind_out = 1;
end
end
drawnow;
idle_ct = 0;
else
idle_ct = idle_ct +1;
if (idle_ct > 20)
drawnow;
idle_ct = 0;
end
end
pause(0.2);
end
+523
View File
@@ -0,0 +1,523 @@
%IMAGESC3D 3D wrapper for imagesc
% imagesc3D supports the same parameters as Matlab's imagesc. In addition, the following
% parameters can be set
%
% init_frame... starting frame number (default 1)
% slider_axis... axis along which you want to use imagesc (default 3)
% fps... frames per second (default 25); will be adjusted by a factor of 1.2 to account for internal overhead
% title_list... individual title for each frame (default {})
% loop... run in a loop (default false)
% reset_frame... stop resets frame to init_frame (default false)
% autoplay... stark movie automatically (default false)
% slider_position... slider position [left bottom width height] (default center of axis)
% play_position... play button position [left bottom width height]
% edit_position... edit box position [left bottom width height]
% show_play_button... show/hide button; needs to be visible if loop=true; (default true)
% show_edit_box... show/hide box
% fnct... data processing function
% order... change slice order in stack
% save_movie... specify filename if a movie shall be written
% movie_quality... image quality of the saved movie
%
% Complex images will be converted to RGB using c2image.
%
% If you are not using 'autplay', you can also set a global title instead
% of a title list (similar to imagesc) and use '%d' to get the slice number
% title('Random block - slice %d')
%
%
% EXAMPLES:
% imagesc3D(rand(256, 256, 100), 'fps', 10, 'loop', true)
% imagesc3D(rand(256, 256)*1j)
% imagesc3D(rand(20, 256, 256), 'slider_axis', 1);
%
%
% Additionally, you can use imagesc/imagesc3D routines and trigger the movie by
% calling the play method of a specified axis:
%
% figure(1);
% imagesc3D(rand(256, 256, 100), 'fps', 20);
% title('Random block - slice %d');
% colorbar();
% ax = gca;
% ax.play();
%
%*-----------------------------------------------------------------------*
%| |
%| Except where otherwise noted, this work is licensed under a |
%| Creative Commons Attribution-NonCommercial-ShareAlike 4.0 |
%| International (CC BY-NC-SA 4.0) license. |
%| |
%| Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch) |
%| |
%| Author: CXS group, PSI |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function imagesc3D(varargin)
import math.isint
import plotting.c2image
ax_img = {};
if nargin == 1
img = varargin{1};
vararg = {};
elseif nargin == 3 && isnumeric(varargin{1}) && isnumeric(varargin{2}) && (islogical(varargin{3}) || isnumeric(varargin{3}))
img = varargin{3};
ax_img = varargin(1:2);
vararg = {};
elseif (islogical(varargin{1}) || isnumeric(varargin{1})) && ischar(varargin{2})
% assume that first argument is images, and next are
% string+arguments
img = varargin{1};
vararg = varargin(2:end);
elseif isnumeric(varargin{1}) && isnumeric(varargin{2}) && (islogical(varargin{3}) || isnumeric(varargin{3}))
% assume that first two arguments are axis,and third is images, and next are
% string+arguments
ax_img = varargin(1:2);
img = varargin{3};
vararg = varargin(4:end);
else
error('Unknown combination of parameters')
end
ax = gca;
pos = ax.Position;
slider_default = [pos(1)+pos(3)/2-0.06 pos(2)-0.1 0.14 0.05];
play_default = [slider_default(1)-0.1 pos(2)-0.1 0.08 0.05];
edit_default = [slider_default(1)+slider_default(3)+0.01 slider_default(2) 0.08 0.05];
par = inputParser;
par.addParameter('fps', 25, @isnumeric) % maximal frame rate
par.addParameter('init_frame', 1, @isnumeric) % starting frame number
par.addParameter('title_list', {}, @iscell) % list of titles for each frame
par.addParameter('slider_axis',3, @isnumeric) % array axis
par.addParameter('loop', false, @islogical) % loop
par.addParameter('reset_frame', false, @islogical) % stop resets frame to init_frame
par.addParameter('autoplay', false, @islogical) % start loop automatically
par.addParameter('slider_position',slider_default, @isnumeric) % slider position; [left bottom width height]
par.addParameter('play_position',play_default, @isnumeric) % slider position; [left bottom width height]
par.addParameter('edit_position', edit_default, @isnumeric) % edit position; [left bottom width height]
par.addParameter('show_play_button',true, @islogical) % array axis
par.addParameter('show_edit_box', true, @islogical) % edit box
par.addParameter('fnct', @(x)x) % data processing function
par.addParameter('order', 1:size(img,3), @isnumeric) % change slice order in stack
par.addParameter('plot_residua', false, @islogical) % plot residua in the image
par.addParameter('save_movie', '', @ischar) % specify filename if a movie shall be written
par.addParameter('movie_quality', 80, @isnumeric) % movie quality
par.parse(vararg{:})
vars = par.Results;
vars.fps = vars.fps *1.2; % correct for overhead
% permute the array to slide along diferent axis
switch vars.slider_axis
case 1
img = rot90(permute(img,[2,3,1]));
case 2
img = rot90(permute(img,[1,3,2]));
end
if any(cellfun(@(x)(strcmpi(x, 'order')), par.UsingDefaults))
% redefine the order just in case that the axis were swapped, but only
% if there is not use preference
vars.order = 1:size(img,3);
end
if ~isempty(vars.title_list)
assert(length(vars.title_list) == size(img,3), 'Number of titles has to correspond to number of frames')
end
sz = size(img,3);
im = imhandles(gcf);
ax = gca;
if ~isprop(ax, 'index')
ax.addprop('index');
ax.index = length(im)+1;
else
if isprop(ax, 'play_handle')
delete(ax.play_handle);
end
if isprop(ax, 'slider_handle')
delete(ax.slider_handle);
end
if isprop(ax, 'edit_handle')
delete(ax.edit_handle);
end
if isprop(ax, 'vars')
ax.vars = [];
end
end
if sz>1
% checks
vars.init_frame = round(vars.init_frame);
if vars.init_frame > sz || vars.init_frame < 1
warning('Initial frame exceeds stack size.')
vars.init_frame = 1;
end
vars.vargin = ax_img;
if ~ax.isprop('img')
ax.addprop('img');
end
ax.img = img;
if ~ax.isprop('play')
ax.addprop('play');
end
ax.play = @(x)play(x);
if ~ax.isprop('stop')
ax.addprop('stop');
end
ax.stop = @(x)stop(x);
if ~ax.isprop('update_fig')
ax.addprop('update_fig');
end
ax.update_fig = @(x)update_fig(x);
%%% set handles
% slider
slider_handle=uicontrol(gcf,'Style','slider','Max',sz,'Min',1,...
'Value',vars.init_frame,'SliderStep',[1/(sz-1) 10/(sz-1)],...
'Units','normalized','Position',vars.slider_position);
if ~isprop(slider_handle, 'ax_index')
slider_handle.addprop('ax_index');
slider_handle.ax_index = ax.index;
end
if ~ax.isprop('slider_handle')
ax.addprop('slider_handle');
ax.slider_handle = slider_handle;
elseif ax.isprop('slider_handle') && ~ax.slider_handle.isvalid
ax.slider_handle = slider_handle;
end
% play button
if vars.show_play_button
visible_button = 'on';
else
visible_button = 'off';
if vars.loop
warning('Loop can not be aborted without buttons. Setting ''loop'' back to ''false''.');
vars.loop = false;
end
end
play_handle=uicontrol(gcf,'Style','pushbutton','string','Play',...
'Units','normalized','Position',vars.play_position, 'Visible', visible_button);
if ~isprop(play_handle, 'ax_index')
play_handle.addprop('ax_index');
play_handle.ax_index = ax.index;
end
if ~ax.isprop('play_handle')
ax.addprop('play_handle');
ax.play_handle = play_handle;
elseif ax.isprop('play_handle') && ~ax.play_handle.isvalid
ax.play_handle = play_handle;
end
if ~ax.isprop('vars')
ax.addprop('vars');
ax.vars = vars;
else
ax.vars = vars;
end
set(play_handle,'Callback',{@play_callback,ax});
% text edit
if vars.show_edit_box
visible_box = 'on';
else
visible_box = 'off';
end
edit_handle = uicontrol('style','edit','units','normalized', 'Position', vars.edit_position, 'Visible', visible_box);
set(edit_handle, 'Callback', {@edit_callback, ax});
if ~ax.isprop('edit_handle')
ax.addprop('edit_handle');
ax.edit_handle = edit_handle;
elseif ax.isprop('edit_handle') && ~ax.edit_handle.isvalid
ax.edit_handle = edit_handle;
end
if ~isprop(edit_handle, 'ax_index')
edit_handle.addprop('ax_index');
edit_handle.ax_index = ax.index;
end
% set callback functions
set(slider_handle,'Callback',{@slider_callback,ax});
set(edit_handle, 'String', num2str(get(ax.slider_handle,'Value')));
if vars.autoplay
play_callback(ax, ax, ax);
end
update_fig(ax)
else
% standard imagesc should be enough
if ax.isprop('update_title') || ax.isprop('play_handle') || ax.isprop('vars')
if ax.isprop('vars') && isfield(ax.vars, 'slider_handle')
ax.vars = rmfield(ax.vars, 'slider_handle');
end
if ax.isprop('play_handle')
delete(ax.play_handle);
end
cla(ax);
end
img = gather(vars.fnct(img));
if ~isreal(img)
img = c2image(img);
end
if ~isempty(ax_img)
imagesc(ax_img{:}, img);
else
imagesc(img);
end
if ~isempty(vars.title_list)
title(ax, vars.title_list{1}, 'Interpreter', 'none')
end
end
end
% plotting function
function update_fig(ax)
import math.isint
import plotting.c2image
% im = imhandles(gcf);
vars = ax.vars;
slice = round(get(ax.slider_handle,'Value'));
slice = max(1, min(length(vars.order), slice));
% FIXME: everything works better without following lines
% sl = gcbo();
% if ~isempty(sl)
% ax = findobj('index', sl.ax_index);
% end
img = gather(vars.fnct(squeeze(ax.img(:,:,vars.order(slice),:))));
if ~isreal(img)
img = c2image(img);
end
if vars.plot_residua
[residua{2},residua{1}] = find(abs(utils.findresidues(img))>0.1);
end
% if the current axis is empty, use imagesc with remaining arguments
if ~ax.isprop('update_title')
ax.addprop('update_title');
ax.addprop('user_title');
ax.update_title = true;
if ~isempty(vars.vargin)
imagesc(vars.vargin{:}, img);
else
imagesc(img);
end
hold all
if vars.plot_residua && ~isempty(residua{1})
plot(residua{:},'or')
elseif vars.plot_residua
plot(0,0,'or')
end
hold off
addlistener(ax.Title, 'String', 'PostSet', @(gt, event)callback_title_post(ax, ax));
else
% if we just need to update the figure, only update the data
ax_data = ax.findobj('Type', 'Image');
ax_data.CData = img;
if vars.plot_residua
ax_data = ax.findobj('Type', 'Line');
ax_data(1).XData = residua{1};
ax_data(1).YData = residua{2};
end
end
% write title
if isempty(vars.title_list)
ax.update_title = false;
if ~isempty(ax.user_title)
title_text = sprintf(ax.user_title, vars.order(slice));
title(ax, title_text, 'Interpreter', 'none');
end
ax.update_title = true;
else
if ~isempty(vars.title_list)
title(ax, vars.title_list{vars.order(slice)}, 'Interpreter', 'none')
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Callback subfunctions %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function slider_callback(~,~,ax)
% ob = gco;
% vars.ax_index = ob.ax_index;
if ax.isprop('edit_handle')
set(ax.edit_handle, 'string', num2str(round(get(ax.slider_handle,'Value'))));
end
update_fig(ax)
drawnow()
end
function callback_title_post(ax, ~, ~)
if ax.update_title
ax.user_title = ax.Title.String;
try
ax.Title.String = sprintf(ax.user_title, get(ax.slider_handle,'Value'));
end
end
end
function play_callback(~,~,ax)
% ax = findobj('index', ax.slider_handle.ax_index);
vars = ax.vars;
if ax.isprop('slider_handle') && ax.slider_handle.isvalid
update_slider = true;
else
update_slider = false;
end
if ax.isprop('edit_handle') && ax.edit_handle.isvalid
update_edit = true;
else
update_edit = false;
end
try
switch get(ax.play_handle,'string')
case 'Play'
if ~isempty(vars.save_movie)
disp(['Saving movie to ' vars.save_movie]);
writeobj = VideoWriter(vars.save_movie);
writeobj.Quality=vars.movie_quality;
writeobj.FrameRate=vars.fps;
open(writeobj);
vars.writeobj = writeobj;
end
set(ax.play_handle,'string','Stop')
sz = size(ax.img,3);
pos = round(get(ax.slider_handle,'Value'));
if pos == sz
set(ax.slider_handle,'Value',1);
pos = 1;
end
while pos <=sz
if strcmp(get(ax.play_handle,'string'), 'Play')
break
end
if update_slider
set(ax.slider_handle,'Value',pos)
end
if update_edit
set(ax.edit_handle, 'String', num2str(pos));
end
update_fig(ax)
pause(1/vars.fps)
if vars.loop && pos == sz
pos = 1;
else
pos = pos+1;
end
if vars.save_movie
currFrame = getframe;
writeVideo(vars.writeobj,currFrame);
end
end
set(ax.play_handle,'string','Play')
if vars.reset_frame
set(ax.slider_handle,'Value',vars.init_frame)
end
if vars.save_movie
close(vars.writeobj);
end
case 'Stop'
set(ax.play_handle,'string','Play')
if vars.save_movie
close(vars.writeobj);
end
end
catch
if ~ax.isprop('play_handle')
fprintf('Lost connection to figure instance.\n')
end
end
end
function edit_callback(~,~, ax)
str=get(ax.edit_handle,'String');
if isempty(str2num(str))
warndlg('Input must be numerical');
set(ax.edit_handle, 'string', num2str(round(get(ax.slider_handle,'Value'))));
else
set(ax.slider_handle,'Value',str2num(str))
update_fig(ax)
drawnow()
end
end
function play(ax)
play_callback(ax.vars, ax.vars, ax);
end
function stop(ax)
set(ax.play_handle,'string','Play')
set(ax.slider_handle,'Value',ax.vars.init_frame)
end
+98
View File
@@ -0,0 +1,98 @@
function [im_out,range]=imagesc_tomo( varargin )
% Function [im_out]=imagesc_tomo( varargin )
% Parameters:
% data - 3D array to be shown
% colormap - name of standard matlab colormap, default = bone
% clim - range of the colorbar, default is [] (auto range)
% axis - cell of strings with axis parameters, eg. {'image', 'off'}
import math.sp_quantile
import plotting.imagesc3D
par = inputParser;
par.addOptional('data', [])
par.addParameter('colormap', 'bone' )
par.addParameter('clim', [] , @isnumeric )
par.addParameter('axis', {'image', 'off'}, @iscell)
par.addParameter('colorbar',false, @islogical)
par.parse(varargin{:})
r = par.Results;
data = r.data;
if ismatrix(data)
imagesc3D(data);
return
end
Npix = size(data);
cntr = ceil(Npix/2);
if isa(data, 'gpuArray')
data = gather(data); % download data from GPU
end
if isempty(r.clim)
range = sp_quantile(data, [1e-3, 1-1e-3], max(1, ceil(sqrt(numel(data))/1e3)));
else
range = r.clim;
end
%disp('range:')
%disp(range)
colormap(r.colormap)
args = {'show_play_button', false, 'show_edit_box', false };
ax(1) = subplot(2,3,1);
imagesc3D(rot90(permute(data, [2,3,1]),1), 'init_frame', cntr(1), 'slider_position',slider_pos(ax(1)), args{:});
axis(r.axis{:});
if isreal(data) && range(1) < range(2); caxis(range); end
if r.colorbar; colorbar; end
title('Centralslice xz');
ax(2) = subplot(2,3,2);
imagesc3D(rot90(permute(data, [1,3,2]),1), 'init_frame', cntr(2),'slider_position',slider_pos(ax(2)), args{:});
axis(r.axis{:});
if isreal(data) && range(1) < range(2); caxis(range); end
if r.colorbar; colorbar; end
title('Centralslice yz');
ax(3) = subplot(2,3,3);
imagesc3D(data, 'init_frame', cntr(3),'slider_position',slider_pos(ax(3)), args{:});
axis(r.axis{:});
if isreal(data) && range(1) < range(2); caxis(range); end
if r.colorbar; colorbar; end
title('Centralslice xy');
ax(4) = subplot(2,3,4);
imagesc3D(rot90(squeeze(sum(data,1)),1));
axis(r.axis{:});
title('Projection xz');
if r.colorbar; colorbar; end
ax(5) = subplot(2,3,5);
imagesc3D(rot90(squeeze(sum(data,2)),1));
axis(r.axis{:});
title('Projection yz');
if r.colorbar; colorbar; end
ax(6) = subplot(2,3,6);
imagesc3D(squeeze(sum(data,3)));
axis(r.axis{:});
title('Projection xy');
if r.colorbar; colorbar; end
% link together axis from the projections and the slices
linkaxes(ax([1,4]), 'xy')
linkaxes(ax([2,5]), 'xy')
linkaxes(ax([3,6]), 'xy')
if nargout > 0
im_out = ax;
end
end
function slider_default = slider_pos(ax)
pos = ax.Position;
slider_default = [pos(1)+pos(3)/2-0.095 pos(2)-0.045 0.2 0.04];
end
+124
View File
@@ -0,0 +1,124 @@
% Integrates frames from a loopscan
%
% Syntax:
% [int] = integrate_frames(base_path,scan_num,plotfigure,det_num,savedata,maskfilename,masktype)
% Needed parameters: base_path (e.g. '~/Data10/')
% scan_num (scan number)
% Optional parameters: plotfigure (figure number for final plot, 0 for no plotting, by default is 0)
% det_num (detector number, default 1)
% savedata (=1 to save data in 'analysis/integrated_frames/', default 0)
% maskfilename (valid mask file name. If empty [], no mask used)
% masktype (type of valid mask file name: 'bin' for binary or 'Oliver')
% 14-11-2012
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [int] = integrate_frames(base_path,scan_num,plotfigure,det_num,savedata,maskfile,masktype)
import beamline.pilatus_valid_pixel_roi
import io.image_read
import io.spec_read
import utils.compile_x12sa_filename
if exist('det_num') == 0
det_num=1;
end
if exist('savedata') == 0
savedata=0;
end
if exist('maskfile') == 0
maskfile=[];
end
if exist('plotfigure') == 0
plotfigure = 0;
end
if exist('masktype') == 0
plotfigure ='Oliver';
end
%maskfile=[];
if savedata
savefolder=[base_path 'analysis/integrated_frames/'];
if savefolder ~= 7
mkdir(savefolder)
end
end
path=sprintf('%spilatus_%01d',base_path,det_num);
filename0=compile_x12sa_filename(scan_num,0);
data0=image_read(filename0);
img0=data0.data;
dims=size(img0);
S=spec_read(base_path,'ScanNr',scan_num);
num=size(S.bpm4i,1);
if ~isempty(maskfile)
switch lower(masktype)
case 'oliver'
load(maskfile)
valid_mask = pilatus_valid_pixel_roi(valid_mask,'RoiSize',size(img0));
mask = zeros(size(img0));
mask(valid_mask.indices) = 1;
case 'bin'
load(maskfile)
otherwise
disp('masktype unknown')
end
else
mask = ones(size(img0));
end
int=img0*0;
stack=zeros(dims(1),dims(2),num);
for jj=1:num
filename=compile_x12sa_filename(scan_num,jj-1);
data1=image_read(filename);
img=data1.data.*mask;
int=int+img;
stack(:,:,jj)=img;
end
if plotfigure ~= 0
figure(plotfigure)
figure_position=[187 295 817 650];
set(gcf,'Position',figure_position);
imagesc(log10(int)); axis xy equal tight; colorbar; colormap jet
title(sprintf('integrated frames S%05d',scan_num))
end
if savedata
savefilename=sprintf('%s/S%05d_%01d_integrated_frames',savefolder,scan_num,det_num);
save([savefilename '.mat'],'int')
print('-f2','-djpeg','-r300',[ savefilename '.jpg'] );
print('-f2','-depsc','-r1200',[savefilename '.eps'] );
end
+189
View File
@@ -0,0 +1,189 @@
% Call function without arguments for instructions on how to use it
% Filename: $RCSfile: integrated_intensity.m,v $
%
% $Revision: 1.1 $ $Date: 2009/04/08 16:46:40 $
% $Author: $
% $Tag: $
%
% Description:
% sum the intensity of frames
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% - image_read
%
% history:
%
% September 4th 2009:
% use find_files rather than dir to find the files
%
% May 9th 2008: 1st documented version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [int_int] = integrated_intensity(filename_mask, varargin)
import beamline.pilatus_valid_pixel_roi
import io.image_read
import utils.find_files
% initialize return arguments
valid_mask = struct('indices',[], 'framesize',[]);
% set default values for the variable input arguments:
% filename for loading and saving the valid pixel mask
filename_valid_mask = '~/Data10/analysis/data/pilatus_valid_mask.mat';
% display result in this figure
fig_no = 2;
% check minimum number of input arguments
if (nargin < 1)
fprintf('\nUsage:\n');
fprintf('[int_int]=%s(filename_mask [[,<name>,<value>]...]);\n',mfilename);
fprintf('''FigNo'',<integer> number of the figure in which the result is displayed, default is %d\n',...
fig_no);
fprintf('\n');
fprintf('Examples:\n');
fprintf('[int_int]=%s(''~/Data10/pilatus/air_scattering/*.cbf'');\n',...
mfilename);
error('At least the filename mask has to be specified as input parameter.');
end
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = no_of_in_arg -1 + length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 1)
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments:
% initialize the list of unhandled parameters
vararg_remain = cell(0,0);
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
otherwise
vararg_remain{end+1} = name; %#ok<AGROW>
vararg_remain{end+1} = value; %#ok<AGROW>
end
end
vararg_remain{end+1} = 'UnhandledParError';
vararg_remain{end+1} = 0;
% set some default values for the plot window
set(0, 'DefaultAxesfontsize', 12);
set(0, 'DefaultAxeslinewidth', 1, 'DefaultAxesfontsize', 12);
set(0, 'DefaultLinelinewidth', 1);
% get all matching filenames
[data_dir,fnames,vararg_remain] = ...
find_files( filename_mask, vararg_remain );
if (length(fnames) < 1)
error('No matching files found for %s.\n',search_mask);
end
fprintf('loading the valid pixel mask %s\n',filename_valid_mask);
load(filename_valid_mask);
% process the frames
int_int = zeros(1,length(fnames));
fprintf('data directory is %s\n',data_dir);
for (f_ind=1:length(fnames))
fprintf('%3d/%3d: reading %s%s\n',f_ind,length(fnames),...
data_dir,fnames(f_ind).name);
[frame] = image_read([data_dir fnames(f_ind).name ],vararg_remain);
if (f_ind == 1)
framesize1 = size(frame.data,1);
framesize2 = size(frame.data,2);
framesize = framesize1 * framesize2;
ind_valid = 1:numel(frame.data);
if (isstruct(valid_mask))
% cut out the region of interest from the valid pixel mask
valid_mask_cut = pilatus_valid_pixel_roi(valid_mask,...
'RoiSize',frame.img_full_size{1});
% from this cut out the region of interest,
% if specified
valid_mask_cut = pilatus_valid_pixel_roi(valid_mask_cut,vararg_remain);
ind_valid = valid_mask_cut.indices;
end
end
% check that the file have identical dimensions
if ((framesize1 ~= size(frame.data,1)) || ...
(framesize2 ~= size(frame.data,2)))
error('The previous file(s) had %d x %d pixels, this frame has %d x %d pixels',...
framesize1,framesize2,size(frame.data,1),size(frame.data,2));
end
% sum the valid pixels
int_int(f_ind) = sum(frame.data(ind_valid));
end
% plot the result
if (fig_no > 0)
figure(fig_no);
plot(int_int);
title_str = [ strrep(filename_mask,'_','\_') ': average int. int. = ' ...
num2str(mean(int_int),'%.4e') ];
title(title_str);
end
+179
View File
@@ -0,0 +1,179 @@
function h = mArrow3(p1,p2,varargin)
%mArrow3 - plot a 3D arrow as patch object (cylinder+cone)
%
% syntax: h = mArrow3(p1,p2)
% h = mArrow3(p1,p2,'propertyName',propertyValue,...)
%
% with: p1: starting point
% p2: end point
% properties: 'color': color according to MATLAB specification
% (see MATLAB help item 'ColorSpec')
% 'stemWidth': width of the line
% 'tipWidth': width of the cone
%
% Additionally, you can specify any patch object properties. (For
% example, you can make the arrow semitransparent by using
% 'facealpha'.)
%
% example1: h = mArrow3([0 0 0],[1 1 1])
% (Draws an arrow from [0 0 0] to [1 1 1] with default properties.)
%
% example2: h = mArrow3([0 0 0],[1 1 1],'color','red','stemWidth',0.02,'facealpha',0.5)
% (Draws a red semitransparent arrow with a stem width of 0.02 units.)
%
% hint: use light to achieve 3D impression
%
% Copyright (c) 2009, Georg Stillfried
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this
% list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution
% * Neither the name of DLR - german aerospace center nor the names of its
% contributors may be used to endorse or promote products derived from this
% software without specific prior written permission.
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
propertyNames = {'edgeColor'};
propertyValues = {'none'};
%% evaluate property specifications
for argno = 1:2:nargin-2
switch varargin{argno}
case 'color'
propertyNames = {propertyNames{:},'facecolor'};
propertyValues = {propertyValues{:},varargin{argno+1}};
case 'stemWidth'
if isreal(varargin{argno+1})
stemWidth = varargin{argno+1};
else
warning('mArrow3:stemWidth','stemWidth must be a real number');
end
case 'tipWidth'
if isreal(varargin{argno+1})
tipWidth = varargin{argno+1};
else
warning('mArrow3:tipWidth','tipWidth must be a real number');
end
otherwise
propertyNames = {propertyNames{:},varargin{argno}};
propertyValues = {propertyValues{:},varargin{argno+1}};
end
end
%% default parameters
if ~exist('stemWidth','var')
ax = axis;
if numel(ax)==4
stemWidth = norm(ax([2 4])-ax([1 3]))/300;
elseif numel(ax)==6
stemWidth = norm(ax([2 4 6])-ax([1 3 5]))/300;
end
end
if ~exist('tipWidth','var')
tipWidth = 3*stemWidth;
end
tipAngle = 22.5/180*pi;
tipLength = tipWidth/tan(tipAngle/2);
ppsc = 50; % (points per small circle)
ppbc = 250; % (points per big circle)
%% ensure column vectors
p1 = p1(:);
p2 = p2(:);
%% basic lengths and vectors
x = (p2-p1)/norm(p2-p1); % (unit vector in arrow direction)
y = cross(x,[0;0;1]); % (y and z are unit vectors orthogonal to arrow)
if norm(y)<0.1
y = cross(x,[0;1;0]);
end
y = y/norm(y);
z = cross(x,y);
z = z/norm(z);
%% basic angles
theta = 0:2*pi/ppsc:2*pi; % (list of angles from 0 to 2*pi for small circle)
sintheta = sin(theta);
costheta = cos(theta);
upsilon = 0:2*pi/ppbc:2*pi; % (list of angles from 0 to 2*pi for big circle)
sinupsilon = sin(upsilon);
cosupsilon = cos(upsilon);
%% initialize face matrix
f = NaN([ppsc+ppbc+2 ppbc+1]);
%% normal arrow
if norm(p2-p1)>tipLength
% vertices of the first stem circle
for idx = 1:ppsc+1
v(idx,:) = p1 + stemWidth*(sintheta(idx)*y + costheta(idx)*z);
end
% vertices of the second stem circle
p3 = p2-tipLength*x;
for idx = 1:ppsc+1
v(ppsc+1+idx,:) = p3 + stemWidth*(sintheta(idx)*y + costheta(idx)*z);
end
% vertices of the tip circle
for idx = 1:ppbc+1
v(2*ppsc+2+idx,:) = p3 + tipWidth*(sinupsilon(idx)*y + cosupsilon(idx)*z);
end
% vertex of the tiptip
v(2*ppsc+ppbc+4,:) = p2;
% face of the stem circle
f(1,1:ppsc+1) = 1:ppsc+1;
% faces of the stem cylinder
for idx = 1:ppsc
f(1+idx,1:4) = [idx idx+1 ppsc+1+idx+1 ppsc+1+idx];
end
% face of the tip circle
f(ppsc+2,:) = 2*ppsc+3:(2*ppsc+3)+ppbc;
% faces of the tip cone
for idx = 1:ppbc
f(ppsc+2+idx,1:3) = [2*ppsc+2+idx 2*ppsc+2+idx+1 2*ppsc+ppbc+4];
end
%% only cone v
else
tipWidth = 2*sin(tipAngle/2)*norm(p2-p1);
% vertices of the tip circle
for idx = 1:ppbc+1
v(idx,:) = p1 + tipWidth*(sinupsilon(idx)*y + cosupsilon(idx)*z);
end
% vertex of the tiptip
v(ppbc+2,:) = p2;
% face of the tip circle
f(1,:) = 1:ppbc+1;
% faces of the tip cone
for idx = 1:ppbc
f(1+idx,1:3) = [idx idx+1 ppbc+2];
end
end
%% draw
fv.faces = f;
fv.vertices = v;
h = patch(fv);
for propno = 1:numel(propertyNames)
try
set(h,propertyNames{propno},propertyValues{propno});
catch
disp(lasterr)
end
end
+786
View File
@@ -0,0 +1,786 @@
% Call function without arguments for instructions on how to use it
% Filename: $RCSfile: plot_radial_integ.m,v $
%
% $Revision: 1.15 $ $Date: 2016/01/21 14:50:38 $
% $Author: $
% $Tag: $
%
% Description:
% plot radially integrated intensities
%
% Note:
% Call without arguments for a brief help text.
% The integrated intensities should be calculated first using
% radial_integ.m.
%
% Dependencies:
% none
%
% history:
%
% November 25th 2011:
% bug-fix in the background subtraction, only subtract for available
% intensities, i.e., intensities not flagged as -1
%
% May 27th 2011:
% return all curves rather than just the last one plotted and allow to
% suppress plotting completely using FigNo 0 (to average data using this
% function)
%
% April 28th 2010:
% add plot as a function of angle option,
% use default_parameter_value
%
% February 19th 2009:
% average only positive intensities (i.e., valid pixels)
%
% September 4th 2009: add Axis parameter
%
% June 9th 2008: 1st documented version
%*-----------------------------------------------------------------------*
%| |
%| Except where otherwise noted, this work is licensed under a |
%| Creative Commons Attribution-NonCommercial-ShareAlike 4.0 |
%| International (CC BY-NC-SA 4.0) license. |
%| |
%| Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch) |
%| |
%| Author: CXS group, PSI |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [x_values_returned,y_values_returned] = plot_radial_integ(filename_masks, varargin)
import utils.default_parameter_value
import utils.find_files
import utils.pixel_to_q
% set default values
fig_no = default_parameter_value(mfilename,'FigNo');
new_fig = default_parameter_value(mfilename,'NewFig');
clear_fig = default_parameter_value(mfilename,'ClearFig');
axis_scale = default_parameter_value(mfilename,'Axis');
sleep_time = default_parameter_value(mfilename,'SleepTime');
xlog = default_parameter_value(mfilename,'XLog');
ylog = default_parameter_value(mfilename,'YLog');
plot_q = default_parameter_value(mfilename,'PlotQ');
plot_angle = default_parameter_value(mfilename,'PlotAngle');
radius_range = default_parameter_value(mfilename,'RadiusRange');
filename_integ_masks = default_parameter_value(mfilename,'FilenameIntegMasks');
pixel_size_mm = default_parameter_value(mfilename,'PixelSize_mm');
det_dist_mm = default_parameter_value(mfilename,'DetDist_mm');
E_keV = default_parameter_value(mfilename,'E_keV');
inverse_nm = default_parameter_value(mfilename,'Inverse_nm');
q_mul_pow = default_parameter_value(mfilename,'QMulPow');
seg_avg = default_parameter_value(mfilename,'SegAvg');
seg_range = default_parameter_value(mfilename,'SegRange');
legend_mul_seg = default_parameter_value(mfilename,'LegendMulSeg');
point_avg = default_parameter_value(mfilename,'PointAvg');
point_range = default_parameter_value(mfilename,'PointRange');
bgr_filename = default_parameter_value(mfilename,'BgrFilename');
bgr_scale = default_parameter_value(mfilename,'BgrScale');
bgr_point = default_parameter_value(mfilename,'BgrPoint');
show_fig = 1;
% check minimum number of input arguments
if (nargin < 1)
fprintf('\nUsage:\n');
fprintf('[x,y]=%s(filename_mask, [[,<name>,<value>] ...]);\n',mfilename);
fprintf('x and y are optional outputs to get the data which is plotted\n')
fprintf('filename_mask can be something like ''*_integ.mat'' or ''*_integ.txt'' or\n');
fprintf('a cell array of filenames or filename masks like {''dir1/*.mat'',''dir2/*.mat''}.\n');
fprintf('The optional <name>,<value> pairs are:\n');
fprintf('''FigNo'',<figure number> number of the figure for plotting the integrated intensities, default is %d\n',fig_no);
fprintf('''NewFig'',<0-no, 1-yes> open a new figure for each file, default is %d\n',new_fig);
fprintf('''ClearFig'',<0-no, 1-yes for the first point,2-yes, always>\n');
fprintf(' clear the figure before plotting, default is %d\n',clear_fig);
fprintf('''Axis,<[ x_from x_to y_from y_to ]> fixed scale for the plot\n')
fprintf('''SleepTime'',<seconds> wait time after each plot, default is %.3f\n',sleep_time);
fprintf('''XLog'',<0-no, 1-yes> logarithmic scaling of the x-axis, default is %d\n',xlog);
fprintf('''YLog'',<0-no, 1-yes> logarithmic scaling of the y-axis, default is %d\n',ylog);
fprintf('''PlotQ'',<0-no, 1-yes> plot as a function of momentum transfer q rather than pixel no., default is %d\n',plot_q);
fprintf('''PlotAngle'',<0-no, 1-yes> plot as a function of the azimuthal angle rather than q or the radius, default is %d\n',plot_angle);
fprintf('''RadiusRange'',<vector or []> for azimuthal plots the intensity over this radius range is averaged, default is [] for all radii\n');
fprintf('''FilenameIntegMasks'',<filename> Matlab file containing the integration masks, needed for normalization in case of averaging over radii, default is ''%s''\n',filename_integ_masks);
fprintf('''QMulPow'',<value,or []> multiply intensity with q to the power of this value, default is [ ] for no multiplication\n');
fprintf('''Inverse_nm'',<0-no, 1-yes> plot q in inverse nm rather than inverse Angstroem, default is %d\n',inverse_nm);
fprintf('''PixelSize_mm'',<value in mm> pixel size for q-calculation, default is %.3f mm. If the file contains a q-vector this parameter is ignored\n',pixel_size_mm);
fprintf('''DetDist_mm'',<value in mm> sample to detector distance for q-calculation, default is %.3f mm. If the file contains a q-vector this parameter is ignored\n',det_dist_mm);
fprintf('''E_keV'',<value in keV> x-ray energy for q-calculation, default is %.3f mm. If the file contains a q-vector this parameter is ignored\n',E_keV);
fprintf('''SegAvg'',<0-no, 1-yes> average over angular segments rather than plotting them with different line colours, default is %d\n',seg_avg);
fprintf('''SegRange'',<vector or []> segment range to plot, default is [] for all segments\n');
fprintf('''LegendMulSeg'',<0-no, 1-yes> show a legend in case of multiple segments being plotted, default is %d\n',legend_mul_seg);
fprintf('''PointAvg'',<0-no,1-yes> plot the average of all intensity curves in the file, which typically means the average of a scan line, default is %d\n',point_avg);
fprintf('''PointRange'',<vector or []> point range to plot, default is [] for all points in a file\n');
fprintf('''BgrFilename'',<''filename''> background to subtract from each intensity profile, must have the same dimensions the data have\n');
fprintf('''BgrScale'',<value> scaling factor to apply to the backgroubnd data, default is %.3e\n',bgr_scale);
fprintf('''BgrPoint'',<integer> point to use from the file BgrFilename, default is %d, use [] to subtract 1:1\n',bgr_point);
fprintf('''ShowFigure'',<0-no,1-yes> show the figure, default is %d\n',show_fig);
fprintf('Examples:\n');
fprintf('%s(''~/Data10/analysis/integ/data1_integ.mat'');\n',mfilename);
error('At least the filename mask has to be specified as input argument.');
end
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = 1 + length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 1)
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments
% vararg = cell(0,0);
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
case 'NewFig'
new_fig = value;
case 'ClearFig'
clear_fig = value;
case 'Axis'
if (isempty(value))
continue;
end
if (length(value) ~= 4)
error('Axis needs a vector with four components as argument.');
end
axis_scale = value;
case 'SleepTime'
sleep_time = value;
case 'XLog'
xlog = value;
case 'YLog'
ylog = value;
case 'PlotQ'
plot_q = value;
case 'PlotAngle'
plot_angle = value;
case 'RadiusRange'
radius_range = value;
case 'FilenameIntegMasks'
filename_integ_masks = value;
case 'QMulPow'
q_mul_pow = value;
case 'Inverse_nm'
inverse_nm = value;
case 'PixelSize_mm'
pixel_size_mm = value;
case 'DetDist_mm'
det_dist_mm = value;
case 'E_keV'
E_keV = value;
case 'SegRange'
seg_range = value;
case {'SegSum', 'SegAvg' }
seg_avg = value;
case 'LegendMulSeg'
legend_mul_seg = value;
case {'PointSum', 'PointAvg'}
point_avg = value;
case 'PointRange'
point_range = value;
case 'BgrFilename'
bgr_filename = value;
case 'BgrScale'
bgr_scale = value;
case 'BgrPoint'
bgr_point = value;
case 'ShowFigure'
show_fig = value;
otherwise
error('Do not know how to handle the parameter %s',name);
% vararg{end+1} = name;
% vararg{end+1} = value;
end
end
% automatically disable averaging over angles in case of angular plots
if (plot_angle)
if (seg_avg ~= 0)
seg_avg = 0;
fprintf('Disabling the averaging over azimuthal segments since a plot as the function of angle has been requested.\n');
end
end
% The integration masks are needed for normalization in case of averaging
% over radii.
if ((plot_angle) && (exist(filename_integ_masks,'file')))
fprintf('Loading the integration masks from %s\n',filename_integ_masks);
integ_data = load(filename_integ_masks);
else
integ_data = [];
end
% determine the 1D plot function to use
if ((~xlog) && (~ylog))
plot_function = @plot;
end
if ((~xlog) && (ylog))
plot_function = @semilogy;
end
if ((xlog) && (~ylog))
plot_function = @semilogx;
end
if ((xlog) && (ylog))
plot_function = @loglog;
end
% load the background data
if (~isempty(bgr_filename))
fprintf('reading background data from %s\n',bgr_filename);
[d_bgr] = load(bgr_filename);
end
% loop over all filename masks
if (isstruct(filename_masks))
% allow for other macros handing over directly the integrated data
% rather than a filename
data_provided = 1;
ind_mask_max = 1;
d = filename_masks;
else
% ease handling by ensuring that filename_masks is a cell array
if (~iscell(filename_masks))
filename_masks = { filename_masks };
end
ind_mask_max = length(filename_masks);
data_provided = 0;
end
y_values_returned = [];
x_values_returned = [];
for (ind_mask = 1:ind_mask_max) %#ok<*NO4LP>
if (data_provided)
file_ind_max = 1;
else
filename_mask = filename_masks{ind_mask};
% % get data directory
% [data_dir] = fileparts(filename_mask);
% if ((~isempty(data_dir)) && (data_dir(end) ~= '/'))
% data_dir = [ data_dir '/' ];
% end
% search matching filenames
[ data_dir, fnames, vararg_remain ] = find_files( filename_mask );
if (length(fnames) < 1)
fprintf('No matching files found for %s.\n',filename_mask);
continue;
end
% loop over all matching files
file_ind_max = length(fnames);
end
if (new_fig)
legend_str = zeros(file_ind_max,12);
end
first_plot = 1;
for (file_ind=1:file_ind_max)
if (show_fig)
if (((new_fig) || (first_plot)) && (fig_no > 0))
figure(fig_no);
if (clear_fig)
hold off;
clf;
else
if (((strcmp(get(gca,'XScale'),'linear')) && (xlog)) || ...
((strcmp(get(gca,'YScale'),'linear')) && (ylog)))
hold off;
else
hold all;
end
end
end
if (new_fig)
first_plot = 1;
end
end
if (~data_provided)
% skip sub directories
if (fnames(file_ind).isdir)
continue;
end
% read one data file
filename = [ data_dir fnames(file_ind).name ];
fprintf('reading %4d / %4d: %s\n',file_ind,file_ind_max,...
filename);
[d] = load(filename);
else
filename = 'online plot';
end
if (isa(d,'struct'))
% in Matlab files a structure with the data is stored
if (isfield(d,'radius'))
% current name
radius = d.radius;
elseif (isfield(d,'r'))
% old name
radius = d.r;
else
radius = d.q;
end
I_all = d.I_all;
if (~isempty(bgr_filename))
% subtract background
if (isempty(bgr_point))
% subtract for the available intensities (I >= 0) 1:1,
% e.g., a line from a line
ind_pos = intersect(find(I_all >= 0), find(d_bgr.I_all >= 0));
I_all = I_all(ind_pos) - bgr_scale * d_bgr.I_all(ind_pos);
else
% determine the over the specified point range
% averaged background intensity,
% keep unavailable intensities flagged as -1
I_all_bgr = calc_I_point_avg(d_bgr.I_all,bgr_point);
% subtract the average background from all intensity
% distributions
for (ind_point = 1:size(I_all,3))
% only subtract available intensities, not the with
% -1 flagged invalid ones
I_point = I_all(:,:,ind_point);
ind_pos = intersect(find(I_point >= 0), find(I_all_bgr >= 0));
I_point(ind_pos) = I_point(ind_pos) - bgr_scale * I_all_bgr(ind_pos);
I_all(:,:,ind_point) = I_point;
end
end
end
else
% in text files the first column contains the radius, the rest
% are intensities for the different segments
if ((isa(d,'double')) && (size(d,2) >= 2))
radius = d(:,1);
I_all = d(:,2:end);
if (~isempty(bgr_filename))
I_all = I_all - bgr_scale * d_bgr(:,2:end);
end
else
error('Unknown data format.');
end
end
% check if segments have been loaded and get the number of segments
% available or specified via a command line parameter
no_of_radii = size(I_all,1);
no_of_segments = size(I_all,2);
no_of_points = size(I_all,3);
if (no_of_segments < 1)
error('could not load %s',filename);
end
if ((plot_angle) && (no_of_segments < 2))
error('At least two segments need to be present for an angular plot.');
end
% average over segments if specified
if (seg_avg)
no_of_segments = 1;
if (isempty(seg_range))
seg_range_use = 1:size(I_all,2);
else
seg_range_use = seg_range;
end
% average over all pixels with positive intensities, i.e., skip
% negative intensities
I_all_prev = I_all;
I_all = zeros(no_of_radii,1,no_of_points);
for (ind1=1:no_of_radii)
for (ind3=1:no_of_points)
no_of_el = 0;
for (ind2=1:length(seg_range_use))
if (I_all_prev(ind1,seg_range_use(ind2),ind3) >= 0)
I_all(ind1,1,ind3) = I_all(ind1,1,ind3) + I_all_prev(ind1,seg_range_use(ind2),ind3);
no_of_el = no_of_el +1;
end
end
if (no_of_el > 1)
I_all(ind1,1,ind3) = I_all(ind1,1,ind3) / no_of_el;
end
end
end
% I_all_prev = I_all;
% I_all = zeros(no_of_radii,1,size(I_all,3));
% for (ind1=1:no_of_radii)
% for (ind3=1:size(I_all,3))
% I_now = I_all_prev(ind1,seg_range_use,ind3);
% I_all(ind1,1,ind3) = mean(I_now(I_now >= 0));
% end
% end
else
if (~isempty(seg_range))
% remove the not needed segments
no_of_segments = length(seg_range);
I_all_prev = I_all;
I_all = zeros(no_of_radii,no_of_segments,no_of_points);
for (ind2=1:no_of_segments)
I_all(:,ind2,:) = I_all_prev(:,seg_range(ind2),:);
end
end
end
% average over radii, if specified
if (plot_angle)
no_of_radii = 1;
if (isempty(radius_range))
radius_range_use = 1:size(I_all,1);
else
radius_range_use = radius_range;
end
% If averaging is performed, i.e., more than one intensity
% value is available, then the number of pixels in each
% integration area needs to be known from the integration masks
% data.
if (isempty(integ_data))
integ_data.integ_masks.norm_sum = ones(size(I_all,1),no_of_segments);
if (length(radius_range_use) > 1)
fprintf('Warning: The integration mask could not be loaded from the file %s.\n',...
filename_integ_masks);
fprintf('Therefore the averaging over radii is not normalized by the number of pixels, which strongly influences the result.\n');
end
end
% average over all pixels with positive intensities, i.e., skip
% negative intensities
I_all_prev = I_all;
I_all = zeros(1,no_of_segments,no_of_points);
for (ind2=1:no_of_segments)
for (ind3=1:no_of_points)
no_of_pixels = 0;
for (ind1=1:length(radius_range_use))
if (I_all_prev(radius_range_use(ind1),ind2,ind3) >= 0)
I_all(1,ind2,ind3) = I_all(1,ind2,ind3) + ...
integ_data.integ_masks.norm_sum(radius_range_use(ind1),ind2) * I_all_prev(radius_range_use(ind1),ind2,ind3);
no_of_pixels = no_of_pixels + integ_data.integ_masks.norm_sum(radius_range_use(ind1),ind2);
end
end
if (no_of_pixels > 0)
I_all(1,ind2,ind3) = I_all(1,ind2,ind3) / no_of_pixels;
end
end
end
end
% average over points, if specified
if (point_avg)
if (isempty(point_range))
point_range_use = 1:size(I_all,3);
else
point_range_use = point_range;
end
% average over all pixels with positive intensities, i.e., skip
% negative intensities
I_all_prev = I_all;
I_all = zeros(no_of_radii,size(I_all,2),1);
for (ind1=1:no_of_radii)
for (ind2=1:no_of_segments)
no_of_el = 0;
for (ind3=1:length(point_range_use))
if (I_all_prev(ind1,ind2,point_range_use(ind3)) >= 0)
I_all(ind1,ind2,1) = I_all(ind1,ind2,1) + I_all_prev(ind1,ind2,point_range_use(ind3));
no_of_el = no_of_el +1;
end
end
if (no_of_el > 1)
I_all(ind1,ind2,1) = I_all(ind1,ind2,1) / no_of_el;
end
end
end
no_of_points = 1;
else
if (~isempty(point_range))
no_of_points = length(point_range);
else
no_of_points = size(I_all,3);
end
end
if (~new_fig)
legend_str = cell(1,no_of_segments);
end
% calculate q:
if (isfield(d,'q')) && (~isempty(d.q))
% define q_A aalways, if available
q_A = d.q;
else
% calculate q, if it is not available in the (historic) data set,
% and if the necessary parameters are provided
if (plot_q || (~isempty(q_mul_pow)))
error_base_str1 = 'You requested PlotQ or QMulPow, but the q-vector does not exist in the file. Please provide ';
error_base_str2 = ' in order to calculate the q-vector.';
if isempty(E_keV)
error('%s''E_keV''%s',error_base_str1,error_base_str2)
end
if isempty(det_dist_mm)
error('%s''DetDist_mm''%s',error_base_str1,error_base_str2)
end
if isempty(pixel_size_mm)
error('%s''PixelSize_mm''%s',error_base_str1,error_base_str2)
end
if isempty(radius)
error('You requested PlotQ or QMulPow, but neither the q-vector nor radius values are included in the file and thus q cannot be computed.');
end
q_A = pixel_to_q( radius, pixel_size_mm, det_dist_mm, E_keV );
else
% q_A is not needed -- set it to empty to indicate this
q_A = [];
end
end
% set some x-axis related values for plotting
if (plot_angle)
no_of_x_values = size(I_all,2);
if (no_of_x_values < 2)
error('At least two segments must be present for a plot as the function of the azimuthal angle.\n');
end
% calculate the azimuthal axis values for the angular plot
if isfield(d,'phi_det')
x_values = d.phi_det;
else % For backwards compatilibity with integrated data without angle
x_values = 0:(360/no_of_x_values):(360-0.99*360/no_of_x_values);
end
% corresponding axis label
x_label = '\Theta [ ^\circ ]';
else
if (plot_q)
x_values = q_A;
if (inverse_nm)
x_values = x_values * 10;
x_label = 'q [ nm^{-1} ]';
else
x_label = 'q [ A^{-1} ]';
end
else
if not((isfield(d,'radius')))
x_values = d.q;
x_label = 'q [ A^{-1} ]';
else
x_values = radius;
x_label = 'pixel no.';
end
end
end
% exclude zero or negative radii in case of logarithmic x-scale
if (xlog)
ind_x = find(x_values > 0);
else
ind_x = 1:length(x_values);
end
% set intensity multiplication values
I_times = ones(length(x_values),1,1);
y_label = 'average counts per pixel';
if (~isempty(q_mul_pow))
I_times(:,1,1) = q_A .^ q_mul_pow;
y_label = [ y_label ' \times (q [ A^{-1} ])^{' ...
num2str(q_mul_pow,'%.1f') '}' ];
end
if (isempty(y_values_returned))
d1 = 0;
d2 = 0;
d3 = 0;
else
d1 = size(y_values_returned,1);
d2 = size(y_values_returned,2);
d3 = size(y_values_returned,3);
end
for (ind_point = 1:no_of_points)
% determine the number of the point to be plotted
if ((point_avg) || (isempty(point_range)))
plot_ind_point = ind_point;
else
plot_ind_point = point_range(ind_point);
end
if (plot_angle)
% plot as a function of the azimuthal angle
% check for negative y-values
if (ylog)
ind_y = find( I_all(1,:,plot_ind_point) > 0 );
else
ind_y = 1:no_of_segments;
end
ind = intersect(ind_x,ind_y);
% plot the intensity as a function of the azimuthal angle
x_values_plotted = x_values(ind);
y_values_plotted = I_all(1,ind,plot_ind_point);
if (show_fig)
if (fig_no > 0)
plot_function(x_values_plotted, y_values_plotted);
end
end
% store the plotted values in the return array (untested)
y_values_returned((d1+1):(d1+1), (d2+1):(d2+length(ind)), (d3+ind_point):(d3+ind_point)) = ...
y_values_plotted;
x_values_returned((d1+1):(d1+1), (d2+1):(d2+length(ind)), (d3+ind_point):(d3+ind_point)) = ...
x_values_plotted;
% do not add a legend
legend_mul_seg = 0 ;
hold all;
else
% plot as a function of radius or q
for (ind_seg = 1:no_of_segments)
% determine the number of the segment to be plotted
if ((seg_avg) || (isempty(seg_range)))
plot_ind_seg = ind_seg;
else
plot_ind_seg = seg_range(ind_seg);
end
% check for negative y-values
if (ylog)
ind_y = find( I_all(:, ind_seg,plot_ind_point) > 0 );
else
ind_y = 1:size(I_all,1);
end
ind = intersect(ind_x,ind_y);
% plot the segment
x_values_plotted = x_values(ind);
y_values_plotted = I_all(ind, ind_seg,plot_ind_point) .* I_times(ind,1,1);
if show_fig
if (fig_no > 0)
plot_function(x_values_plotted, y_values_plotted);
end
end
% store the plotted values in the return array
y_values_returned((d1+1):(d1+length(ind)), (d2+ind_seg):(d2+ind_seg), (d3+ind_point):(d3+ind_point)) = ...
y_values_plotted;
x_values_returned((d1+1):(d1+length(ind)), (d2+ind_seg):(d2+ind_seg), (d3+ind_point):(d3+ind_point)) = ...
x_values_plotted;
% add the segment to the legend
if (fig_no > 0)
if (~new_fig)
legend_str{ind_seg} = [ 'seg. ' num2str(plot_ind_seg,'%03d') ];
else
legend_str(file_ind,:) = ...
[ num2str(file_ind,'%04d') ' seg.' num2str(plot_ind_seg,'%03d') ];
end
hold all;
end
end
end
if (show_fig)
if (fig_no > 0)
if (clear_fig > 1)
hold off;
else
hold all;
end
end
title_str = strrep(filename,'\','\\');
title_str = strrep(title_str,'_','\_');
if (no_of_points > 1)
title_str = [ title_str ', point ' num2str(plot_ind_point-1) ];
end
if (fig_no > 0)
title( title_str );
axis tight;
xlabel(x_label);
ylabel(y_label);
if (~isempty(axis_scale))
axis( axis_scale );
end
if ((legend_mul_seg) && (no_of_segments > 1))
legend(char(legend_str));
end
drawnow;
end
first_plot = 0;
if (sleep_time > 0.0)
pause(sleep_time);
end
end
if ((new_fig) && (fig_no > 0))
fig_no = fig_no +1;
end
end
end
% if ((~new_fig) && (size(legend_str,1) <= 10))
% legend(char(legend_str));
% end
end
function [I_all] = calc_I_point_avg(I_all_prev,point_range)
% average over all pixels with positive intensities, i.e., skip
% negative intensities
no_of_radii = size(I_all_prev,1);
no_of_segments = size(I_all_prev,2);
I_all = zeros(no_of_radii,no_of_segments,1);
for (ind1=1:no_of_radii)
for (ind2=1:no_of_segments)
no_of_el = 0;
for (ind3=1:length(point_range))
if (I_all_prev(ind1,ind2,point_range(ind3)) >= 0)
I_all(ind1,ind2,1) = I_all(ind1,ind2,1) + I_all_prev(ind1,ind2,point_range(ind3));
no_of_el = no_of_el +1;
end
end
if (no_of_el > 1)
I_all(ind1,ind2,1) = I_all(ind1,ind2,1) / no_of_el;
end
end
end
+77
View File
@@ -0,0 +1,77 @@
import plotting.plot_radial_integ
import io.spec_read
scan_nr=565;
%backgroundscan=343;
base_path='~/Data10/';
eaccount=beamline.identify_eaccount;
%spec_data = spec_read(base_path,'ScanNr',scan_nr);
%transmission_data=mean(spec_data.diode);
datafile=sprintf('%sanalysis/radial_integration/%s_1_%05d_00000_00000_integ.mat',base_path,eaccount,scan_nr);
%backgroundfile=sprintf('%sanalysis/radial_integration/%s_1_%05d_00000_00000_integ.mat',base_path,eaccount,backgroundscan);
%spec_data_bgr = spec_read(base_path,'ScanNr',backgroundscan);
%transmission_bgr=mean(spec_data_bgr.diode);
%correction=transmission_data/transmission_bgr;
plot_radial_integ(...
datafile,...
'FigNo',102,... number of the figure for plotting the integrated intensities, default is 100
'NewFig',1,... open a new figure for each file, default is 0
'ClearFig',0,... clear the figure before plotting, default is 1
'XLog',1,... logarithmic scaling of the x-axis, default is 0
'YLog',1,... logarithmic scaling of the y-axis, default is 1
'PlotQ',0,... plot as a function of momentum transfer q rather than pixel no., default is 0
'PlotAngle',0,... plot as a function of the azimuthal angle rather than q or the radius, default is 0
'RadiusRange',[],... for azimuthal plots the intensity over this radius range is averaged, default is [] for all radii
'QMulPow',[],... multiply intensity with q to the power of this value, default is [ ] for no multiplication
'Inverse_nm',1,... plot q in inverse nm rather than inverse Angstroem, default is 0
'SegAvg',1,... average over angular segments rather than plotting them with different line colours, default is 1
'SegRange',[],... segment range to plot, default is [] for all segments
'LegendMulSeg',1,... show a legend in case of multiple segments being plotted, default is 1
'PointAvg',0,... plot the average of all intensity curves in the file, which typically means the average of a scan line, default is 1
'PointRange',[]);%,... %point range to plot, default is [] for all points in a file
%'BgrFilename',backgroundfile,... % background to subtract from each intensity profile, must have the same dimensions the data have
%'BgrScale',correction); % scaling factor to apply to the backgroubnd data, default is 1.000e+00
%'Axis',<[ x_from x_to y_from y_to ]> fixed scale for the plot
%'SleepTime',<seconds> wait time after each plot, default is 0.000
%'XLog',<0-no, 1-yes> logarithmic scaling of the x-axis, default is 0
%'YLog',<0-no, 1-yes> logarithmic scaling of the y-axis, default is 1
%'FilenameIntegMasks',<filename> Matlab file containing the integration masks, needed for normalization in case of averaging over radii, default is '~/Data10/analysis/data/pilatus_integration_masks.mat'
%'BgrFilename',<'filename'> background to subtract from each intensity profile, must have the same dimensions the data have
%'BgrScale',<value> scaling factor to apply to the backgroubnd data, default is 1.000e+00
%'BgrPoint',<integer> point to use from the file BgrFilename, default is 1, use [] to subtract 1:1
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
+76
View File
@@ -0,0 +1,76 @@
import io.image_read
% this script is used to visualize the sgalil positions
clear
scan_init=11103;
number_of_scans = 10;
for jj=1:number_of_scans
this_scan=scan_init+jj-1;
filename = sprintf('~/Data10/sgalil/S%05d.dat',this_scan);
data = beamline.read_position_file(filename);
x = data.Avg_x;
y = data.Avg_y;
pos_arrayx(:,jj) = x;
pos_arrayy(:,jj) = y;
end
plot(pos_arrayx,pos_arrayy,'-bo')
grid on
axis equal
title(sprintf('S%05d - S%05d',scan_init,scan_init+number_of_scans))
pos_arrayy_aux = pos_arrayy;
pos_arrayy_aux(:,2:2:end) = flipud(pos_arrayy_aux(:,2:2:end));
offset = mean(mean(abs(diff(pos_arrayy_aux(1:6,1:6),1,2))));
fprintf('**************************************************************************** \n');
fprintf('The mean step size is %.05f microns \n', mean(abs(diff(y(:, 1))))*1000);
fprintf('The standard deviation is %.05f microns \n', std(abs(diff(y(:, 1))))*1000);
fprintf('The offset between lines (absolute value) is is %.05f microns \n', offset*1e3);
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
%
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing la this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS scanning SAXS package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% Additionally, any publication using the package, or any translation of the
% code into another computing language should cite:
% O. Bunk, M. Bech, T. H. Jensen, R. Feidenhans'l, T. Binderup, A. Menzel
% and F Pfeiffer, Multimodal x-ray scatter imaging, New J. Phys. 11,
% 123016 (2009). (doi: 10.1088/1367-2630/11/12/123016)
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -0,0 +1,83 @@
import io.image_read
% this script is used to plot the sgalil positions in the order that they
% occur
clear
scan_init=11103;
number_of_scans=10;
%%
%pos_arrayx=zeros(pts_per_scan+1,number_of_scans);
%pos_arrayy=zeros(pts_per_scan+1,number_of_scans);
figure
pos_arrayx = [];
pos_arrayy = [];
for jj=1:number_of_scans
this_scan=scan_init+jj-1;
filename = sprintf('~/Data10/sgalil/S%05d.dat',this_scan);
data = beamline.read_position_file(filename);
x = data.Avg_x;
y = data.Avg_y;
pos_arrayx = [pos_arrayx; x];
pos_arrayy = [pos_arrayy; y];
end
%%
figure (1)
for i= 1:numel(pos_arrayx)
plot(pos_arrayx(i),pos_arrayy(i),'-bo')
axis equal
grid on
hold on
pause(0.1)
title(sprintf('S%05d - S%05d',scan_init,scan_init+number_of_scans))
end
hold off
fprintf('**************************************************************************** \n');
fprintf('The mean step size is %.05f microns \n', mean(abs(diff(y(:, 1))))*1000);
fprintf('The standard deviation is is %.05f microns \n', std(abs(diff(y(:, 1))))*1000);
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
%
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing la this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS scanning SAXS package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% Additionally, any publication using the package, or any translation of the
% code into another computing language should cite:
% O. Bunk, M. Bech, T. H. Jensen, R. Feidenhans'l, T. Binderup, A. Menzel
% and F Pfeiffer, Multimodal x-ray scatter imaging, New J. Phys. 11,
% 123016 (2009). (doi: 10.1088/1367-2630/11/12/123016)
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+130
View File
@@ -0,0 +1,130 @@
%[p object probe] = ptycho_show_recons(file,param1,val1,...)
% Receives a path+filename, reads it and makes plots of the ptychography
% reconstruction, in default it will also save the plotted images
%
% Optional parameters
% 'imagesavefolder' '~/Data10/analysis/online/ptycho/show_recons/'
% (default = [], which means no plot is saved)
% param can be updated with another struct
% [p, probe, object] = core.ptycho_show_recons(filepath, p_updated)
%
% and / or with single field names
% [p, probe, object] = core.ptycho_show_recons(filepath, p_updated, 'windowautopos', 1, 'extrastringtitle', 'Final recon')
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [p, object, probe] = ptycho_show_recons(file,varargin)
import utils.param_protect_field
import utils.update_param
import utils.find_latest_file
import io.*
msk = {'*recons*.h5', '*recons*.mat', '*recons*.cxs'};
if nargin==0
file = find_latest_file('../../', msk);
elseif ischar(file) && isdir(file)
file = find_latest_file(file, msk);
elseif isnumeric(file)
file = find_latest_file('../../', msk, file);
end
%% load file
fprintf('Showing reconstruction: %s\n',file)
[object, probe, p] = load_ptycho_recons(file);
p.save.store_images = true;
p.use_display = true;
%% update p struct
p.windowautopos = 1;
if ~isempty(varargin)
p.plot = update_param(p.plot, varargin{:});
end
% orthogonalize probes
if p.ortho_probes && size(p.probes,4)>1
p.probes = core.probe_modes_ortho(p.probes);
end
% to allow different screen sizes
try
p.scrsz = get(0,'ScreenSize');
catch
p.scrsz = [1 1 2560 1024];
end
% to allow different save paths
if isfield(p, 'imagesavefolder')
imagesavefolder = p.imagesavefolder;
else
imagesavefolder = [];
end
% back compatibility
if ~isfield(p, 'numscans')
p.numscans = length(p.scan);
end
for ii = 1:p.numscans
p.scanidxs{ii} = p.scanindexrange(ii,1):p.scanindexrange(ii,2);
end
%% plot
core.analysis.plot_results(p, 'use_display', p.use_display, 'store_images', p.save.store_images, 'final', 1);
return
+264
View File
@@ -0,0 +1,264 @@
% Call function without arguments for instructions on how to use it
% Filename: $RCSfile: scan_movie.m,v $
%
% $Revision: 1.4 $ $Date: 2010/11/12 15:26:15 $
% $Author: $
% $Tag: $
%
% Description:
% plot a sequence of 2D data frames, optionally save them as .avi file
%
% Note:
% Call without arguments for a brief help text.
%
% Dependencies:
% - image_read
%
% history:
%
% June 10th 2008: 1st documented version
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [vararg_remain] = scan_movie(filenames,varargin)
import io.image_info
import io.image_read
import plotting.image_show
import utils.find_files
% set default values
% figure number for display
fig_no = 2;
% do not display time in title
display_time = 0;
% do not write AVI files
write_avi = 0;
% avi filename
avi_filename = '~/Data10/scan_movie.avi';
% AVI frames per second
avi_fps = 5;
% capture the full figure
capture_figure = 1;
% screen frames per second, 0 for no wait
screen_fps = 0;
% search masks rather than filenames are specified
is_fmask = 1;
% use Linux/Unix find command to interprete filename mask
use_find = 1;
% check minimum number of input arguments
if (nargin < 1)
fprintf('Usage:\n')
fprintf('[vararg_remain]=%s(<filenames> [[,<name>,<value>] ...]);\n',...
mfilename);
fprintf('The optional <name>,<value> pairs are:\n');
fprintf('''FigNo'',<integer value> figure number for data display, default is %d\n',fig_no);
fprintf('''WriteAVI'',<0-no, 1-yes> write the image frames as AVI file, default is %d\n',write_avi);
fprintf('''AVIfilename'',<filename> default is %s\n',avi_filename);
fprintf('''AVI_fps'',<value in Hz> default is %.1f\n',avi_fps);
fprintf('''CaptureFigure'',<0-axes,1-figure> capture image or full figure, default is %d\n',capture_figure);
fprintf('''Screen_fps'',<value in Hz> pause if update is faster than this rate / 0 for no pause, default is %.1f\n',screen_fps);
fprintf('''IsFmask'',<0-no,1-yes> interprete the filename(s) as search mask that may include wildcards, default %d',is_fmask);
fprintf('''UseFind'',<0-no, 1-yes> use Linux/Unix command find to interprete the filename mask, default is %d\n',use_find);
fprintf('Additional <name>,<value> pairs recognized by image_show can be specified. Please call image_show for an overview\n');
fprintf('\n');
fprintf('Examples:\n');
fprintf('%s({''file1.cbf'',''file2.cbf''});\n',mfilename);
fprintf('%s(''dir/*.cbf'');\n',mfilename);
fprintf('%s(''dir/*.cbf'', ''WriteAVI'',1);\n',mfilename);
fprintf('%s(''dir/*.cbf'',''ColumnFrom'',700,''ColumnTo'',1100,''RowFrom'',500,''RowTo'',1000,''Screen_fps'',0.5,''LogScale'',0,''AxisMax'',1e3);\n',mfilename);
fprintf('%s(''dir/*.cbf'',''WriteAVI'',1,''AVIfilename'',''test.avi'');\n',mfilename);
error('At least the filenames have to be specified as input parameter.');
end
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = 1 + length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 1)
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments
vararg = cell(1,2);
% do not display current time by default, can be overruled with parameters
vararg{1} = 'DisplayTime';
vararg{2} = 0;
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch name
case 'FigNo'
fig_no = value;
case 'WriteAVI'
write_avi = value;
case 'AVIfilename'
avi_filename = value;
case 'AVI_fps'
avi_fps = value;
case 'Screen_fps'
screen_fps = value;
case 'IsFmask'
is_fmask = value;
case 'UseFind'
use_find = value;
case 'CaptureFigure'
capture_figure = value;
otherwise
vararg{end+1} = name; %#ok<AGROW>
vararg{end+1} = value; %#ok<AGROW>
end
end
% pass some parameters to image_show
vararg{end+1} = 'FigNo';
vararg{end+1} = fig_no;
image_handle = 0;
vararg{end+1} = 'ImageHandle';
vararg{end+1} = image_handle;
% initialize the list of unhandled parameters
vararg_remain = cell(0,0);
% convert the filename to a cell array to use the same loop for single and
% multiple file names
if (~iscell(filenames))
filenames = { filenames };
end
% convert single filename to cell array to ease handling
if (~is_fmask)
fnames = struct('name',cell(1,1),'isdir',cell(1,1));
fnames.isdir = false;
end
% loop over all filenames or filename masks
frame_no = 0;
tic;
previous_time = toc;
file_ind_max = length(filenames);
figure(fig_no);
hold off;
clf;
avi_obj = [];
for (file_ind = 1:file_ind_max)
filename = filenames{file_ind};
if (is_fmask)
[data_dir,fnames,vararg_remain] = find_files( filename, 'UseFind',use_find );
if (length(fnames) < 1)
fprintf('No matching files found for %s.\n',filename);
continue;
end
else
fnames.name = filename;
end
for (fname_ind =1:length(fnames))
if (~fnames(fname_ind).isdir)
frame_no = frame_no +1;
% initialize avi object in case this is the first frame
if ((write_avi) && (isempty(avi_obj)))
fprintf('Opening video output file %s, %.1f fps\n',...
avi_filename,avi_fps);
avi_obj=VideoWriter(avi_filename);
avi_obj.FrameRate=avi_fps;
open(avi_obj);
end
% this does currently not work in case of several frames per
% file
vararg{end} = image_handle;
filename = [data_dir fnames(fname_ind).name];
fi = image_info(filename);
for (frame_ind = 1:fi.no_of_frames)
if (frame_ind == 1)
vararg_mod = vararg;
vararg_mod{length(vararg_mod)+1} = 'FrameNumber';
frame_ind_pos = length(vararg_mod)+1;
vararg_mod{frame_ind_pos} = frame_ind;
[frame,image_handle] = image_show(filename,vararg_mod);
% hand over the already read data to image_show for the
% display of the following frames
vararg_mod{length(vararg_mod)+1} = 'Frame';
vararg_mod{length(vararg_mod)+1} = frame;
else
vararg_mod{frame_ind_pos} = frame_ind;
image_show(filename,vararg_mod);
end
drawnow;
% add frame to avi file
if (write_avi)
if (capture_figure)
avi_frame = getframe(fig_no);
else
avi_frame = getframe(gca);
end
writeVideo(avi_obj,avi_frame);
end
% pause in the unlikely case that the screen update is too fast
if ((~isempty(screen_fps)) && (screen_fps > 0))
time_now = toc;
time_remain = 1.0/screen_fps - time_now + previous_time;
if (time_remain > 0)
pause(time_remain);
previous_time = 1.0/screen_fps + previous_time;
else
previous_time = time_now;
end
end
end
end
end
end
% close avi file, if necessary
if (write_avi)
close(avi_obj); %#ok<NASGU>
end
+82
View File
@@ -0,0 +1,82 @@
%SMART_FIGURE update figure without stealing focus
% fig = plotting.smart_figure(varargin)
%
% **varargin same inputs as for MATLAB's figure function
%
% returns:
% ++ fig figure handle
%
% EXAMPLE:
% fig = plotting.smart_figure(1);
%
% see also: plotting.imagesc3D
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [varargout] = smart_figure(varargin)
if nargin ~= 1
% use MATLAB's figure function for name-value pairs
fig = figure(varargin{:});
else
try
% check if figure already exists and retrieve ID
id = varargin{1};
figList = get(groot, 'Children');
figID = find([figList==id]);
% if the figure exists, set it as the current figure
if ~isempty(figID)
fig = figList(figID);
set(groot, 'CurrentFigure', fig)
else
% figure does not exist - create new one
fig = figure(id);
end
catch
% ... just in case
fig = figure(varargin{:});
end
end
% return figure handle if needed
if nargout>0
varargout{1} = fig;
end
end
+127
View File
@@ -0,0 +1,127 @@
% function h = plotting.spec_mesh_plot(spec_dat_file, scan, ['counter',counter_name])
%
%SPEC_MESH_PLOT Plot the counter values from a mesh scan. In the future to
% be generalized to other types of scans
%
% inputs
%
% ** spec_dat_file Filename and path of the SPEC dat file. A base path can
% also be given and the code will search for the file
% ** scan Scan number
%
%*optional*
% ** 'counter',counter_name counter_name is the name of the SPEC
% counter, by default it will be 'bpm4i'
%
% returns
% ++ h Figure handle
%
%
% see also:
%
% EXAMPLES:
% plotting.spec_mesh_plot('~/Data10', 10)
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2019 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function h = spec_mesh_plot(spec_dat_file, scan, varargin)
% set default values for the variable input arguments:
counter = 'bpm4i';
% check minimum number of input arguments
if (nargin < 2)
error('At least the spec dat filename and scan number have to be specified as input parameters.');
end
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 0)
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% parse the variable input arguments
vararg_remain = cell(0,0);
for ind = 1:2:length(varargin)
name = varargin{ind};
value = varargin{ind+1};
switch lower(name)
case 'counter'
counter = value;
otherwise
vararg_remain{end+1} = name; %#ok<AGROW>
vararg_remain{end+1} = value; %#ok<AGROW>
end
end
S = io.spec_read(spec_dat_file,'ScanNr',scan);
scanstring = strsplit(S.S);
scantype = scanstring{3};
switch lower(scantype)
case 'mesh'
name_axis_fast = scanstring{4};
N_fast = str2num(scanstring{7})+1;
name_axis_slow = scanstring{8};
N_fast = str2num(scanstring{7})+1;
N_slow = str2num(scanstring{11})+1;
otherwise
error(['Scan type ' lower(scantype) ' is not defined for this function'])
end
%%%% HASTA AQUI VOY %%%%
data = reshape(S.(counter),N_fast,N_slow).';
axis_fast = reshape(S.(name_axis_fast),N_fast,N_slow).';
axis_slow = reshape(S.(name_axis_slow),N_fast,N_slow).';
if nargout > 0
h = figure(1);
else
figure(1)
end
imagesc(axis_fast(1,:),axis_slow(:,1),data)
title(S.S);
xlabel(name_axis_fast)
ylabel(name_axis_slow)
axis xy
end
+334
View File
@@ -0,0 +1,334 @@
% function [varargout] = spec_plot(specDatFile, varargin)
% call 'spec_plot()' for further help
%
% please reports bugs, problems, suggestions for improvements to:
% CXS group
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [varargout] = spec_plot(specDatFile, varargin)
import io.spec_help
import io.spec_read
% check minimum number of input arguments
if (nargin<1)
spec_help(mfilename);
error('At least the spec data filename has to be specified as input parameter.')
end
% accept cell array with name/value pairs as well
no_of_in_arg = nargin;
if (nargin == 2)
if (isempty(varargin))
% ignore empty cell array
no_of_in_arg = no_of_in_arg -1;
else
if (iscell(varargin{1}))
% use a filled one given as first and only variable parameter
varargin = varargin{1};
no_of_in_arg = 1 + length(varargin);
end
end
end
% check number of input arguments
if (rem(no_of_in_arg,2) ~= 1)
error('The optional parameters have to be specified as ''name'',''value'' pairs');
end
% here the default parameters
unhandled_par_error = 1;
wait_for = 0;
axno = -1;
% parse the variable input arguments
vararg = cell(0,0);
for jj = 1:2:length(varargin)
name = varargin{jj};
value = varargin{jj+1};
switch name
case 'Counter'
counter = value;
case 'FigNo'
figno = value;
case 'Sleep'
wait_for = value;
case 'ContMesh'
saxis = value;
case 'PFunction'
pfunction = value;
counter = 'Pilatus';
vararg{end+1} = 'OutPut'; %#ok<AGROW>
vararg{end+1} = '+pilatus'; %#ok<AGROW>
case 'UnhandledParError'
unhandled_par_error = value;
otherwise
vararg{end+1} = name; %#ok<AGROW>
vararg{end+1} = value; %#ok<AGROW>
end
end
vararg{end+1} = 'Cell';
vararg{end+1} = 1;
vararg{end+1} = 'UnhandledParError';
vararg{end+1} = 0;
[S,vararg_new] = spec_read(specDatFile,vararg);
vararg = cell(0);
pilatusDir = cell(0);
for jj = 1:2:length(vararg_new)
name = vararg_new{jj};
value = vararg_new{jj+1};
switch name
case 'PilatusDir'
pilatusDir{end+1} = value;
otherwise
vararg{end+1} = name; %#ok<AGROW>
vararg{end+1} = value; %#ok<AGROW>
end
end
varargout{1} = cell(size(S));
for jj=1:numel(S)
S_j = S{jj};
titlestr = S_j.S;
if (isfield(S_j,counter))
scanstr = regexp(S_j.S,' *','split');
data = S_j.(counter);
if (iscell(data))
data = PilatusCounter(data,S_j.PilatusDir,pfunction);
numall = zeros(size(data));
for ii=1:numel(data)
numall(ii) = numel(data{ii});
end
if (all(numall==1))
for ii=1:numel(data)
numall(ii) = data{ii}{:};
end
data = numall;
end
end
if (numel(data)<=1 && ~iscell(data))
continue;
end
if (~exist('figno','var'))
figno = figure;
elseif (~ishandle(figno))
figure(figno)
else
switch get(figno,'type')
case 'figure'
figure(figno)
case 'axes'
axno = figno;
figno = get(figno,'parent');
otherwise
while (strcmp(get(figno,'type'),'axes'))
figno = get(figno,'parent');
end
axno = figno;
figno = get(figno,'parent');
end
if (ishandle(axno))
axes(axno);
cla;
end
end
if (~isempty(regexp(scanstr{3},'[ad][0-3]?scan','match')))
faxis = scanstr{4};
fpos = S_j.(faxis);
h = plot(fpos,data);
xlabel(faxis); ylabel(counter);
elseif (~isempty(regexp(scanstr{3},'loopscan','match')))
faxis = 'Time';
fpos = S_j.(faxis);
h = plot(fpos,data);
xlabel(faxis); ylabel(counter);
elseif (~isempty(regexp(scanstr{3},'cont_line','match')))
faxis = scanstr{4};
if (~exist('saxis','var'))
fpos = linspace(str2double(scanstr{5}),str2double(scanstr{6}), ...
str2double(scanstr{7})+1);
sdata = cell2mat(data{1});
h = plot(fpos,sdata);
xlabel(faxis); ylabel(pfunction,'Interpreter','None');
else
scannr = str2double(scanstr{2});
if (~exist('fpos','var'))
fpos = linspace(str2double(scanstr{5}),str2double(scanstr{6}), ...
str2double(scanstr{7})+1);
spos = S_j.(saxis);
sdata = cell2mat(data{1});
minnr = scannr;
maxnr = scannr;
else
fpos = [fpos, ...
linspace(str2double(scanstr{5}),str2double(scanstr{6}), ...
str2double(scanstr{7})+1)];
spos = [spos, S_j.(saxis)];
fpos = unique(fpos);
spos = unique(spos);
sdata = [sdata;cell2mat(data{1})];
minnr = min(minnr,scannr);
maxnr = max(minnr,scannr);
titlestr = sprintf('#S %05d-%05d cont_mesh %s %f %f %d %s %f %f %d %s %s', ...
minnr,maxnr, ...
faxis, min(fpos), max(fpos), numel(fpos)-1, ...
saxis, min(spos), max(spos), numel(spos)-1, ...
scanstr{8},scanstr{9});
end
h = imagesc(fpos,spos,sdata);
if (numel(spos)>1)
axis equal tight;
hold on
contour(fpos,spos,sdata,'k');
hold off
end
xlabel(faxis); ylabel(saxis);
colorbar;
end
elseif (~isempty(regexp(scanstr{3},'mesh','match')))
faxis = scanstr{4};
saxis = scanstr{8};
fpos = unique(S_j.(faxis));
spos = unique(S_j.(saxis));
if (numel(data) == numel(fpos)*numel(spos))
data = transpose(reshape(data,numel(fpos),numel(spos)));
elseif (mod(numel(data)/(numel(fpos)*numel(spos)),1) == 0)
data = reshape(data,[],numel(fpos),numel(spos));
data = transpose(squeeze(sum(data,1)));
end
if ((mod(numel(data)/(numel(fpos)*numel(spos)),1) == 0) && ...
numel(data) > 1)
h = imagesc(fpos,spos,data);
else
[fpos,spos,data,h] = plot_grid(S_j.(faxis),S_j.(saxis),data);
end
if (size(data,1)>1)
axis equal tight;
hold on
contour(fpos,spos,data,'k');
hold off
end
xlabel(faxis); ylabel(saxis);
colorbar;
elseif (~isempty(regexp(scanstr{3},'round_scan','match')))
faxis = scanstr{4};
saxis = scanstr{5};
[fpos,spos,data,h] = plot_grid(S_j.(faxis),S_j.(saxis),data);
axis equal tight;
hold on
contour(fpos,spos,data,'k');
hold off
xlabel(faxis); ylabel(saxis);
colorbar;
elseif (~isempty(regexp(scanstr{3},'round_roi_scan','match')))
faxis = scanstr{4};
saxis = scanstr{7};
[fpos,spos,data,h] = plot_grid(S_j.(faxis),S_j.(saxis),data);
axis equal tight;
hold on
contour(fpos,spos,data,'k');
hold off
xlabel(faxis); ylabel(saxis);
colorbar;
else
fprintf('unknown scan ''%s'' encountered\n', ...
scanstr{3})
end
title(titlestr,'Interpreter','None')
drawnow;
if (wait_for && jj<numel(S))
pause(wait_for);
end
else
error('Counter ''%s'' not found in scan ''%s''', ...
counter,S_j.S);
end
if (exist('h','var'))
varargout{1}{jj} = h;
end
end
if ((unhandled_par_error) && (~isempty(vararg)))
vararg %#ok<NOPRT>
error('Not all named parameters have been handled.');
end
varargout{2} = vararg;
return
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x,y,Z,h] = plot_grid(xaxis,yaxis,data)
pos = [xaxis,yaxis];
diff = pos(2:end,:) - pos(1:end-1,:);
[y,x] = hist(sqrt(sum(diff.^2,2)),200);
[~,n] = max(y(2:end));
s = x(n)/2;
[X,Y] = meshgrid(linspace(min(xaxis)-s,max(xaxis)+s,200), ...
linspace(min(yaxis)-s,max(yaxis)+s,200));
Z = zeros(size(X));
N = Z;
for ii=1:numel(data)
Z = Z+data(ii)*exp(-((X-xaxis(ii)).^2 + (Y-yaxis(ii)).^2)/(2*s^2)); %/(2*pi*s^2);
N = N+ exp(-((X-xaxis(ii)).^2 + (Y-yaxis(ii)).^2)/(2*s^2)); %/(2*pi*s^2);
end
Z = Z./N;
x = X(1,:);
y = Y(:,1);
h = imagesc(x,y,Z);
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = PilatusCounter(fnames,fpath,evalfunction)
if (iscell(fnames{1}))
data = cell(size(fnames));
else
data = -ones(size(fnames));
end
for ii=1:numel(fnames)
if (iscell(fnames{ii}))
data{ii} = cell(size(fnames{ii}));
for jj=1:numel(fnames{ii})
data{ii}{jj} = eval(sprintf(evalfunction, ...
strcat(fpath,fnames{ii}{jj})));
end
else
data(ii) = eval(sprintf(strcat(evalfunction,';'), ...
strcat(fpath,fnames{ii}{jj})));
end
end
end
+121
View File
@@ -0,0 +1,121 @@
% Function modified by CXS group from:
%
%SUPTITLE puts a title above all subplots.
%
% SUPTITLE('text') adds text to the top of the figure
% above all subplots (a "super title"). Use this function
% after all subplot commands.
%
% SUPTITLE is a helper function for yeastdemo.
% Copyright 2003-2014 The MathWorks, Inc.
function hout=suptitle(str, varargin)
%SUPTITLE puts a title above all subplots.
%
% SUPTITLE('text') adds text to the top of the figure
% above all subplots (a "super title"). Use this function
% after all subplot commands.
%
% SUPTITLE is a helper function for yeastdemo.
% Copyright 2003-2014 The MathWorks, Inc.
% Warning: If the figure or axis units are non-default, this
% function will temporarily change the units.
% Parameters used to position the supertitle.
% Amount of the figure window devoted to subplots
plotregion = .92;
% Y position of title in normalized coordinates
titleypos = .95;
% Fontsize for supertitle
fs = get(gcf,'defaultaxesfontsize')+4;
% Fudge factor to adjust y spacing between subplots
fudge=1;
% keyboard
haold = gca;
figunits = get(gcf,'units');
% Get the (approximate) difference between full height (plot + title
% + xlabel) and bounding rectangle.
if ~strcmp(figunits,'pixels')
set(gcf,'units','pixels');
pos = get(gcf,'position');
set(gcf,'units',figunits);
else
pos = get(gcf,'position');
end
ff = (fs-4)*1.27*5/pos(4)*fudge;
% The 5 here reflects about 3 characters of height below
% an axis and 2 above. 1.27 is pixels per point.
% Determine the bounding rectangle for all the plots
h = findobj(gcf,'Type','axes');
oldUnits = get(h, {'Units'});
if ~all(strcmp(oldUnits, 'normalized'))
% This code is based on normalized units, so we need to temporarily
% change the axes to normalized units.
set(h, 'Units', 'normalized');
cleanup = onCleanup(@()resetUnits(h, oldUnits));
end
max_y=0;
min_y=1;
oldtitle = [];
numAxes = length(h);
thePositions = zeros(numAxes,4);
for i=1:numAxes
pos=get(h(i),'pos');
thePositions(i,:) = pos;
if ~strcmp(get(h(i),'Tag'),'suptitle')
if pos(2) < min_y
min_y=pos(2)-ff/5*3;
end
if pos(4)+pos(2) > max_y
max_y=pos(4)+pos(2)+ff/5*2;
end
else
oldtitle = h(i);
end
end
if max_y > plotregion
scale = (plotregion-min_y)/(max_y-min_y);
for i=1:numAxes
pos = thePositions(i,:);
pos(2) = (pos(2)-min_y)*scale+min_y;
pos(4) = pos(4)*scale-(1-scale)*ff/5*3;
set(h(i),'position',pos);
end
end
np = get(gcf,'nextplot');
set(gcf,'nextplot','add');
if ~isempty(oldtitle)
delete(oldtitle);
end
axes('pos',[0 1 1 1],'visible','off','Tag','suptitle');
ht=text(.5,titleypos-1,str, varargin{:});set(ht,'horizontalalignment','center','fontsize',fs);
set(gcf,'nextplot',np);
% axes(haold);
if nargout
hout=ht;
end
end
function resetUnits(h, oldUnits)
% Reset units on axes object. Note that one of these objects could have
% been an old supertitle that has since been deleted.
valid = isgraphics(h);
set(h(valid), {'Units'}, oldUnits(valid));
end
+81
View File
@@ -0,0 +1,81 @@
import plotting.plot_radial_integ
import io.spec_read
scan_nr=345;
backgroundscan=343;
base_path='~/Data10/';
eaccount='e15581';
spec_data = spec_read(base_path,'ScanNr',scan_nr);
transmission_data=mean(spec_data.diode);
datafile=sprintf('%sanalysis/radial_integration/%s_1_%05d_00000_00000_integ.mat',base_path,eaccount,scan_nr);
backgroundfile=sprintf('%sanalysis/radial_integration/%s_1_%05d_00000_00000_integ.mat',base_path,eaccount,backgroundscan);
spec_data_bgr = spec_read(base_path,'ScanNr',backgroundscan);
transmission_bgr=mean(spec_data_bgr.diode);
correction=transmission_data/transmission_bgr;
plot_radial_integ(...
datafile,...
'FigNo',101,... number of the figure for plotting the integrated intensities, default is 100
'NewFig',1,... open a new figure for each file, default is 0
'ClearFig',0,... clear the figure before plotting, default is 1
'XLog',1,... logarithmic scaling of the x-axis, default is 0
'YLog',1,... logarithmic scaling of the y-axis, default is 1
'PlotQ',1,... plot as a function of momentum transfer q rather than pixel no., default is 0
'PlotAngle',0,... plot as a function of the azimuthal angle rather than q or the radius, default is 0
'RadiusRange',[],... for azimuthal plots the intensity over this radius range is averaged, default is [] for all radii
'QMulPow',[],... multiply intensity with q to the power of this value, default is [ ] for no multiplication
'Inverse_nm',1,... plot q in inverse nm rather than inverse Angstroem, default is 0
'PixelSize_mm',0.172,... pixel size for q-calculation, default is 0.172 mm
'DetDist_mm',7281.9,... sample to detector distance for q-calculation, default is 7200.000 mm
'E_keV',11.2,... x-ray energy for q-calculation, default is 11.200 mm
'SegAvg',1,... average over angular segments rather than plotting them with different line colours, default is 1
'SegRange',[],... segment range to plot, default is [] for all segments
'LegendMulSeg',1,... show a legend in case of multiple segments being plotted, default is 1
'PointAvg',1,... plot the average of all intensity curves in the file, which typically means the average of a scan line, default is 1
'PointRange',[],... %point range to plot, default is [] for all points in a file
'BgrFilename',backgroundfile,... % background to subtract from each intensity profile, must have the same dimensions the data have
'BgrScale',correction); % scaling factor to apply to the backgroubnd data, default is 1.000e+00
%'Axis',<[ x_from x_to y_from y_to ]> fixed scale for the plot
%'SleepTime',<seconds> wait time after each plot, default is 0.000
%'XLog',<0-no, 1-yes> logarithmic scaling of the x-axis, default is 0
%'YLog',<0-no, 1-yes> logarithmic scaling of the y-axis, default is 1
%'FilenameIntegMasks',<filename> Matlab file containing the integration masks, needed for normalization in case of averaging over radii, default is '~/Data10/analysis/data/pilatus_integration_masks.mat'
%'BgrFilename',<'filename'> background to subtract from each intensity profile, must have the same dimensions the data have
%'BgrScale',<value> scaling factor to apply to the backgroubnd data, default is 1.000e+00
%'BgrPoint',<integer> point to use from the file BgrFilename, default is 1, use [] to subtract 1:1
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
+88
View File
@@ -0,0 +1,88 @@
function ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w)
% tight_subplot creates "subplot" axes with adjustable gaps and margins
%
% ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w)
%
% in: Nh number of axes in hight (vertical direction)
% Nw number of axes in width (horizontaldirection)
% gap gaps between the axes in normalized units (0...1)
% or [gap_h gap_w] for different gaps in height and width
% marg_h margins in height in normalized units (0...1)
% or [lower upper] for different lower and upper margins
% marg_w margins in width in normalized units (0...1)
% or [left right] for different left and right margins
%
% out: ha array of handles of the axes objects
% starting from upper left corner, going row-wise as in
% going row-wise as in
%
% Example: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01])
% for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end
% set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','')
% Pekka Kumpulainen 20.6.2010 @tut.fi
% Tampere University of Technology / Automation Science and Engineering
% License
%
% Copyright (c) 2016, Pekka Kumpulainen
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
if nargin<3; gap = .02; end
if nargin<4 || isempty(marg_h); marg_h = .05; end
if nargin<5; marg_w = .05; end
if numel(gap)==1;
gap = [gap gap];
end
if numel(marg_w)==1;
marg_w = [marg_w marg_w];
end
if numel(marg_h)==1;
marg_h = [marg_h marg_h];
end
axh = (1-sum(marg_h)-(Nh-1)*gap(1))/Nh;
axw = (1-sum(marg_w)-(Nw-1)*gap(2))/Nw;
py = 1-marg_h(2)-axh;
ha = zeros(Nh*Nw,1);
ii = 0;
for ih = 1:Nh
px = marg_w(1);
for ix = 1:Nw
ii = ii+1;
ha(ii) = axes('Units','normalized', ...
'Position',[px py axw axh], ...
'XTickLabel','', ...
'YTickLabel','');
px = px+axw+gap(2);
end
py = py-axh-gap(1);
end
+135
View File
@@ -0,0 +1,135 @@
% function h=vline(x, linetype, label)
%
% Draws a vertical line on the current axes at the location specified by 'x'. Optional arguments are
% 'linetype' (default is 'r:') and 'label', which applies a text label to the graph near the line. The
% label appears in the same color as the line.
%
% The line is held on the current axes, and after plotting the line, the function returns the axes to
% its prior hold state.
%
% The HandleVisibility property of the line object is set to "off", so not only does it not appear on
% legends, but it is not findable by using findobj. Specifying an output argument causes the function to
% return a handle to the line, so it can be manipulated or deleted. Also, the HandleVisibility can be
% overridden by setting the root's ShowHiddenHandles property to on.
%
% h = vline(42,'g','The Answer')
%
% returns a handle to a green vertical line on the current axes at x=42, and creates a text object on
% the current axes, close to the line, which reads "The Answer".
%
% vline also supports vector inputs to draw multiple lines at once. For example,
%
% vline([4 8 12],{'g','r','b'},{'l1','lab2','LABELC'})
%
% draws three lines with the appropriate labels and colors.
%
% By Brandon Kuczenski for Kensington Labs.
% brandon_kuczenski@kensingtonlabs.com
% 8 November 2001
%
% Copyright (c) 2001, Brandon Kuczenski
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function hhh=vline(x,in1,in2)
if length(x)>1 % vector input
for I=1:length(x)
switch nargin
case 1
linetype='r:';
label='';
case 2
if ~iscell(in1)
in1={in1};
end
if I>length(in1)
linetype=in1{end};
else
linetype=in1{I};
end
label='';
case 3
if ~iscell(in1)
in1={in1};
end
if ~iscell(in2)
in2={in2};
end
if I>length(in1)
linetype=in1{end};
else
linetype=in1{I};
end
if I>length(in2)
label=in2{end};
else
label=in2{I};
end
end
h(I)=vline(x(I),linetype,label);
end
else
switch nargin
case 1
linetype='r:';
label='';
case 2
linetype=in1;
label='';
case 3
linetype=in1;
label=in2;
end
g=ishold(gca);
hold on
y=get(gca,'ylim');
h=plot([x x],y,linetype);
if length(label)
xx=get(gca,'xlim');
xrange=xx(2)-xx(1);
xunit=(x-xx(1))/xrange;
if xunit<0.8
text(x+0.01*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))
else
text(x-.05*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))
end
end
if g==0
hold off
end
set(h,'tag','vline','handlevisibility','off')
end % else
if nargout
hhh=h;
end