plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
Abakumov/MLIB-master
|
s_cplot.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_cplot.m
| 19,603 |
utf_8
|
e95b0b24a71e60e9219c74f10bc647c5
|
function aux=s_cplot(seismic,varargin)
% Plot seismic data in color-coded form.
%
% Written by: E. Rietsch: May 16, 2000
% Last updated: October 24, 2009: Remove the lines between facets
% (parameter "shading")
%
% aux=s_cplot(seismic,varargin)
% INPUT
% seismic seismic structure
% varargin one or more cell arrays; the first element of each cell array
% is a keyword, the other elements are parameters.
% Presently, keywords are:
% 'annotation' header mnemonic to use for the horizontal axis
% Default: {'annotation','trace_no'}
% 'clim' two numbers representing fractions of the difference between smallest and
% largest sample value (see also keyword 'limits') to compute lower and
% upper limits limit of values to which colors will be assigned.
% limits(1)=min(seismic.traces) + (max(seismic.traces)-min(seismic.traces)*clim(1)
% limits(2)=max(seismic.traces) - (max(seismic.traces)-min(seismic.traces)*clim(2)
% Default: {'clim',0.3333,0.3333}
% 'colorbar' plot colorbar; possible values are 'yes' and 'no'.
% Default: {'colorbar','yes'}
% 'colormap' color map to be used to map seismic amplitudes to color. Can be
% any of those predefined in MATLAB (such as 'copper','hot');
% type "help graph3d" in MATLAB for a list of color maps.
% Also, {'colormap','gray'} creates a gray-scale color map
% (the smaller the value the darker the color)
% Default: {colormap,'seismic'}; this creates a blue-to-red colormap
% (function "mycolormap('seismic')")
% 'direction' plot direction. Possible values are: left-to-right, 'l2r',
% and right-to-left, 'r2l'.
% Default: {'direction','l2r')
% 'figure' specifies if new figure should be created or if the seismic
% traces should be plotted to an existing figure.
% Possible values are 'new' and any other string.
% Default: {'figure','new'}
% 'flip_colormap' keyword to flip the colormap (e.g. the default "blue-to-red"
% colormap is converted to "red-to-blue"); possible values are 'yes'
% and any other string.
% Default: {'flip_colormap','no'}
% 'fontsize' size of the font for axis annotations, labels, and legends.
% Default: {'fontsize',11}
% 'imagemenu' specifies if figure should have a menu button to allow
% interactive change of color parameters.
% Possible values are: 'yes' and 'no'
% Default: {'imagemenu','yes'}
% 'interpol' speifies how traces should be interpolated. Possible
% values are: 'no','cubic','v5cubic' (see Matlab function
% "interp1".
% Default: {'interpol','v5cubic'}
% 'limits' lower and upper limit of values to which colors will be assigned;
% if given it overrides parameters specified via keyword 'clim'.
% Default: {'limits',[],[]}
% specifies how data should be interpolated in time
% 'orient' plot orientation. Possible values are: 'portrait' and 'landscape'
% Default: {'orient','landscape'}
% 'polarity' 2-element cell array. Possible values are 1 and -1;
% Default: {'polarity',1}
% 'scale' 2-element cell array which specifies if individual traces
% should be scaled relative to one another. There are two scaling options:
% 'median' makes the median of the absolute values of each trace the same.
% 'max' makes the maximum of the absolute values of each trace the same.
% The third alternative is 'no', meaning data are displayed "as is".
% The previously used option 'yes' is the same as 'median' and,
% while deprecated, still works.
% Default: {'scale','no'}
% 'shading' color shading (see Matlab function "shading")
% possible values are '', 'flat', 'faceted', 'interp'
% if not empty function "pcolor" is used to create the plot
% with the type of shading specified. Shading 'interp" tends to
% give a more continuous display.
% Otherwise, function imagesc" is used. This is faster.
% Default: {'shading',''}
% 'times' 2-element or 3-element cell array
% {'times',vector of first and last time to plot} or ('times',first,last}.
% Default: {'times',seismic.first,seismic.last} which is
% equivalent to {'times',[seismic.first,seismic.last]}
% 'time_lines' Two-element or three-element cell array. the second and
% third element indicate time intervals at multiples of which
% time lines will be plotted. The time lines of the third
% element (if given), are thicker than those of the first.
% No time lines are plotted if {'time_lines',[]}.
% Default: {'time_lines',500,1000}
% 'title' 2-element cell array. The second element is a plot title.
% Default: {'title',seismic.name}
% 'traces' 2-element or 3-element cell array. The second element can
% be an array of trace numbers or it can be a string. If it is a
% string it can be a header mnemonic or it can contain a logical
% expression involving header values to include.
% The "pseudo-header" 'trace_no' can also be used.
% If the second element is a string containing a header mnemonic
% there must be a third element containing a vector of values
% (see "s_select")
% Default: {'traces',[]} which is equivalent to
% {'traces',1:ntr} where ntr denotes the number of traces
% in the input data set (ntr = size(seismic.traces,2))
% 'tracking' track cursor position; possible values are 'yes', 'no', and ''.
% In the latter case a tracking button is created if the the
% seismic is plotted in a new figure. Otherwise it is not.
% Default: {'tracking',''}
% OUTPUT
% aux structure with information about the plot
% 'figure_handle' handle of the figure with this plot
%
% EXAMPLE
% seismic=s_data;
% s_cplot(seismic,{'limits',-0.5,0.5},{'colormap','copper'})
% s_cplot(seismic,{'limits',-0.5,0.5},{'colormap','copper'},{'shading','interp'})
% UPDATE HISTORY
% July 25, 2007: Use a function for subset creation
% April 22, 2008: bug fix if number of traces is 1
% March 7, 2009: Make axes and axis annotations bold
% March 8, 2009: Make size of axis-related fonts an input parameter
if ~istype(seismic,'seismic')
if isnumeric(seismic)
seismic=s_convert(seismic,1,1);
seismic.units='Rows';
isseismic=false;
seismic=add_header(seismic,1:size(seismic.traces,2),{'columns','n/a','Columns'});
else
error('First input argument must be a seismic dataset or a matrix.')
end
else
isseismic=true;
end
run_presets_if_needed
nsamp=size(seismic.traces,1);
if nsamp == 1
disp('Only one sample per trace; data set not plotted')
return
end
% Set default valuesz
if isseismic
param.annotation='trace_no';
else
param.annotation='columns';
end
param.clim={0.3333,0.3333};
param.colorbar='yes';
param.colormap='seismic';
param.direction='l2r';
param.figure='new';
param.figure_only='no';
param.flip_colormap='no';
param.flip_colors=[]; % Deprecated (replaced by "flip_colormap"
param.fontsize=11;
param.imagemenu='yes';
param.interpol='v5cubic';
param.limits=cell(1,2);
param.npixels=1000;
param.orient='landscape';
param.polarity=1;
param.scale='no';
param.shading='';
param.time_lines={200,1000};
param.times=[];
param.title=strrep(seismic.name,'_','\_');
try
param.title(1)=upper(param.title(1));
catch
% do nothing
end
param.traces=[];
param.tracking='';
% Decode input arguments
param=assign_input(param,varargin,'s_cplot');
if ~isempty(param.flip_colors)
alert(' Keyword "flip_colors" has been replaced by "flip_colormap".')
param.flip_colormap=param.flip_colors;
end
% Select subset of seismic data
seismic=select_subset_of_seismic_traces(seismic,param.times,param.traces);
[nsamp,ntr]=size(seismic.traces);
if nsamp == 1
disp('Only one sample per trace; data set not plotted')
return
end
% Change polarity if necessary
if param.polarity < 0
seismic.traces=-seismic.traces;
end
% Interpolate data in time if necessary
if strcmpi(param.interpol,'cubic') && nsamp < param.npixels
npix=round(param.npixels/(nsamp-1))*(nsamp-1);
dti=(seismic.last-seismic.first)/npix;
times=(seismic.first:dti:seismic.last)';
if isnull(seismic) % Turn off warnings caused by NaN's in seismic traces
warning('off','MATLAB:interp1:NaNinY')
yi=interp1(seismic.first:seismic.step:seismic.last,seismic.traces,times,param.interpol);
warning('on','MATLAB:interp1:NaNinY')
else
yi=interp1(seismic.first:seismic.step:seismic.last,seismic.traces,times,param.interpol);
end
else
dti=seismic.step;
yi=seismic.traces;
end
% Compute horizontal trace locations
xi=s_gh(seismic,param.annotation);
if min(xi) == max(xi) && ntr > 1
error([' Header requested for annotation (',param.annotation,') is constant'])
end
% Check if header values change uniformly from one trace to the next.
if ntr == 1 || isconstant(diff(xi),0.001)
text2append='';
else
text2append=' - approximate';
alert(['Trace annotation with header "',param.annotation,'" is only an approximation.'])
end
%% Create figure window (unless an existing figure is to be used)
if strcmpi(param.figure,'new')
if isempty(param.orient)
if ntr > 10
figure_handle=lfigure;
else
figure_handle=pfigure;
end
else
if strcmpi(param.orient,'portrait')
figure_handle=pfigure;
else
figure_handle=lfigure;
end
end
% set(figure_handle,'Color','w','DoubleBuffer',param.doublebuffer)
% Create menu botton for "Options"
options_menu_handle=uimenu(figure_handle,'Label','Options','ForegroundColor','b','Tag','options_menu');
% Create menu item for scoll bars
cseismic_scrollbar_menu_item(figure_handle,options_menu_handle,seismic,param.direction);
% Create menu item for cursor tracking
yinfo=info4units(seismic.units);
if isempty(param.tracking) || isyes(param.tracking)
[dummy,xinfo]=s_gh(seismic,param.annotation); %#ok First output argument is not required
y=linspace(seismic.first,seismic.last,nsamp);
xi2use=s_gh(seismic,param.annotation);
initiate_3d_tracking_item(options_menu_handle,seismic.traces*param.polarity, ...
xi2use,y,xinfo,yinfo,{'amplitude','','Amplitude'})
% Button for menu to change image (color, etc. ...)
if isyes(param.imagemenu)
myimagemenu % Create menu button to interactively change colors, etc.
end
else
ylabel([yinfo{3},' (',yinfo{2},')'])
end
elseif strcmpi(param.figure,'old')
figure_handle=gcf;
else
error(['Unknown parameter for keyword "figure": "',param.figure,'"'])
end
bgGray % Gray background
if nargout > 0
aux.figure_handle=figure_handle;
end
set(figure_handle,'DoubleBuffer','on')
if ntr > 1
dxi=min(diff(xi))*0.5;
else
dxi=0.5;
end
if isyes(param.colorbar)
colorbar
end
axis([min(xi)-dxi,max(xi)+dxi,seismic.first,seismic.last])
ha=get(figure_handle,'CurrentAxes');
set(ha,'TickDir','out','YDir','reverse','XAxisLocation','top')
hold on
% Handle reversal of plot direction
if strcmpi(param.direction,'r2l')
set(ha,'xdir','reverse')
elseif ~strcmpi(param.direction,'l2r')
error(['Keyword for plot direction is wrong (',param.direction,')'])
end
if strcmpi(param.figure_only,'yes')
return
end
% Scale traces relative to one another
switch param.scale
case {'yes','median'}
trace_max=zeros(1,ntr);
for ii=1:ntr
temp=abs(yi(:,ii));
trace_max(ii)=median(temp(temp>0 & ~isnan(temp)));
end
trace_max(isnan(trace_max))=1;
yi=mrt(yi,mean(trace_max)./(trace_max+eps));
case 'max'
trace_max=max(abs(yi));
yi=mrt(yi,mean(trace_max)./(trace_max+eps));
otherwise
% Do nothing
end
%% Compute limits for color display
if iscell(param.limits)
param.limits=cat(2,param.limits{:});
end
ma=max(yi(~isnan(yi)));
if isempty(ma)
iname=inputname(1);
if strcmpi(iname,'')
iname='data set';
end
alert([' All elements of ',iname,' are null values']);
return
end
mi=min(yi(~isnan(yi)));
if ma*mi < 0
ma=(ma-mi)*0.5;
mi=-ma;
elseif ma == mi
ma=ma+10000*max(ma*eps,eps);
mi=mi-10000*max(mi*eps,eps);
end
dmami=ma-mi;
if isempty(param.limits)
if iscell(param.clim)
param.clim=cat(2,param.clim{:});
end
param.limits(2)=ma-dmami*param.clim(2);
param.limits(1)=mi+dmami*param.clim(1);
if param.limits(1) >= param.limits(2)
alert(' clim(1) + clim(2) must be less than 1; present values ignored')
param.limits(1)=mi;
param.limits(2)=ma;
end
else
if param.limits(1) >= param.limits(2)
alert(' limits(1) must be less than limits(2); present values ignored')
param.limits(1)=mi;
param.limits(2)=ma;
end
end
%% Define colormap to use
try
cm=mycolormap(param.colormap);
catch %#ok
disp(' Reqested colormap not found; seismic colormap used instead.')
cm=mycolormap('seismic');
end
% Flip color matrix if requested
if isyes(param.flip_colormap)
cm=flipud(cm);
end
% Plot data
if isempty(param.shading)
cplot_no1(yi,seismic.first,dti,xi,param.direction,cm, ...
param.limits,ha)
else
cplot_no2(yi,seismic.first,dti,xi,param.direction,cm, ...
param.limits,ha,param.shading)
end
% Title
if ~isempty(param.title)
if iscell(param.title) % Handle multi-line titles
mytitle(param.title{1})
else
mytitle(param.title)
end
end
% Add annotation of horizontal axis
xtext=s_gd(seismic,param.annotation);
hunits=s_gu(seismic,param.annotation);
if ~isempty(xtext) && ~strcmpi(xtext,'not available')
if ~isempty(hunits) && ~strcmpi(hunits,'n/a')
xtext=[xtext,' (',hunits,')'];
end
xlabel([xtext,text2append])
end
if ~isempty(param.time_lines)
if ~iscell(param.time_lines)
param.time_lines={param.time_lines};
end
v=axis;
width=1.5;
for ii=1:length(param.time_lines)
t1=ceil(v(3)/param.time_lines{ii})*param.time_lines{ii};
temp=t1:param.time_lines{ii}:v(4);
mygrid(temp,'h','k',width);
width=width*1.5;
end
end
box on
grid on
zoom on
make_axes_bold(ha)
% set(ha,'gridlinestyle','-','xgrid','off','Layer','top', ...
% 'FontSize',param.fontsize)
% Make axes, labels, etc. bold
% Update colorbar
if isyes(param.colorbar)
colorbar
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cplot_no1(seis,stm,prm,xannot,plot_dir,cm,param_scale,ha)
% Function plot seismic data as image plot
%
% cplot(seis,stm,prm,xannot,plot_dir,cm,param_scale,ha,colbar)
% INPUT
% seis seismic traces
% stm start time
% prm sample interval
% xannot x-axis annotation
% plot_dir plot direction ('l2r' or 'r2l'); default: 'l2r'
% cm color matrix
% param_scale a 2-element vector containing clow and chigh (see imagesc and colormap).
%
% or by global variable param.clim which computes
% ma=max(seis(:));
% if ma > 0
% param_scale(2)=ma*param.clim(2);
% else
% param_scale(2)=ma/param.clim(2);
% end
% mi=min(seis(:));
% if mi > 0
% param_scale(1)=mi/param.clim(1);
% else
% param_scale(1)=mi*param.clim(1);
% end
% if param_scale(1) >= param_scale(2)
% cc=mean(param_scale);
% param_scale(1)=cc*(1-eps);
% param_scale(2)=cc*(1+eps);
% end
% ha handle of axis
[nbin,ntr]=size(seis);
% Handle plot and CDP direction
if strcmp(plot_dir,'r2l') == 1 && xannot(1) < xannot(ntr),
flip_axis=true;
elseif strcmp(plot_dir,'r2l') ~= 1 && xannot(1) > xannot(ntr),
xannot=flipud(xannot(:));
seis=fliplr(seis);
flip_axis=true;
elseif strcmp(plot_dir,'r2l') == 1 && xannot(1) > xannot(ntr),
xannot=flipud(xannot(:));
flip_axis=false;
seis=fliplr(seis);
else
flip_axis=false;
end
if ~isempty(param_scale)
handle=imagesc(xannot,stm:prm:(nbin-1)*prm+stm,seis,param_scale);
else
handle=imagesc(xannot,stm:prm:(nbin-1)*prm+stm,seis);
end
set(handle,'Tag','image_displayed') % Create tag for image object which is
% used in "myimagemenu"
try
colormap(cm),
catch %#ok
% Do nothing
end
set(ha,'XAxisLocation','top','YDir','Reverse');
if flip_axis
set(ha,'XDir','Reverse');
end
drawnow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cplot_no2(seis,stm,prm,xannot,plot_dir,cm,param_scale,ha,param_shading)
% Function plot seismic data using "pcolor"
%
% cplot(seis,stm,prm,xannot,plot_dir,cm,param_scale,ha,colbar)
% INPUT
% seis seismic traces
% stm start time
% prm sample interval
% xannot x-axis annotation
% plot_dir plot direction ('l2r' or 'r2l'); default: 'l2r'
% cm color matrix
% param_scale a 2-element vector containing clow and chigh (see imagesc and colormap).
%
% or by global variable param.clim which computes
% ma=max(seis(:));
% if ma > 0
% param_scale(2)=ma*param.clim(2);
% else
% param_scale(2)=ma/param.clim(2);
% end
% mi=min(seis(:));
% if mi > 0
% param_scale(1)=mi/param.clim(1);
% else
% param_scale(1)=mi*param.clim(1);
% end
% if param_scale(1) >= param_scale(2)
% cc=mean(param_scale);
% param_scale(1)=cc*(1-eps);
% param_scale(2)=cc*(1+eps);
% end
% ha handle of axis
% param_shading shading parameter (see Matlab function shading)
[nbin,ntr]=size(seis);
% Handle plot and CDP direction
if strcmp(plot_dir,'r2l') == 1 && xannot(1) < xannot(ntr),
flip_axis=true;
xannot=xannot(:);
elseif strcmp(plot_dir,'r2l') ~= 1 && xannot(1) > xannot(ntr),
xannot=flipud(xannot(:));
seis=fliplr(seis);
flip_axis=true;
elseif strcmp(plot_dir,'r2l') == 1 && xannot(1) > xannot(ntr),
xannot=flipud(xannot(:));
flip_axis=false;
seis=fliplr(seis);
else
flip_axis=false;
xannot=xannot(:);
end
try
colormap(cm),
catch %#ok
% Do nothing
end
%axis([xannot(1)-0.5,xannot(ntr)+0.5,stm,stm+(nbin-1)*prm])
seis=double(seis);
seis(end+1,end+1)=0;
seis(:,end)=seis(:,end-1);
% shading flat
handle=pcolor([0;xannot]+0.5,stm-prm/2:prm:(nbin-1)*prm+stm+prm/2,seis);
set(handle,'LineStyle','none') % Remove the lines between facets
if ~isempty(param_scale)
set(gca, 'CLim', param_scale);
end
set(handle,'Tag','image_displayed') % Create tag for pplot object which is
% used in "myimagemenu"
try
shading(param_shading)
catch %#ok
disp([' Unknown parameter for keyword "shading": ',param_shading])
end
set(ha,'XAxisLocation','top','YDir','Reverse');
if flip_axis
set(ha,'XDir','Reverse');
end
drawnow
|
github
|
Abakumov/MLIB-master
|
read_las_file.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/read_las_file.m
| 5,604 |
utf_8
|
67e4827a715b5dca7711a5a4c860b9ab
|
function wlog=read_las_file(filename,varargin)
% Function reads well logs from a disk file in LAS format (Log ASCII Standard)
% Versions 2.0 or 3.0 as specified by the Canadian Well Logging Society.
% See also: "read_las2_file"
%
% Written by: E. Rietsch: December 15, 2006;
% Last updated: October 12, 2007: remove fields with text strings that
% appear to provide no real information
%
% wlog=read_las_file(filename,varargin)
% INPUT
% filename string with the file name (and full path if desired);
% if the file is not found a file selection box will pop up to
% allow interactive file selection
% varargin one or more cell arrays; the first element of each cell array
% is a keyword, the other elements are parameters (only used
% if the file is in LAS 3.0 format).
% Presently, keywords are:
% 'section' string with names of sections that schould be read in
% The actual log curves (Section ~ASCII) and the parameters
% (Section ~Parameter) are always read.
% Example: {'section','tops','inclinometry'};
% the sections can also be written as one comma-separated string
% Example: {'section','tops,inclinometry'} reads sections "tops" and
% "inclinometry", if they exist.
% {'section','all'} reads all sections.
% Default: {'section',[]} No additional sections are read.
% OUTPUT
% wlog structure containing the log curves and ancillary information
% wlog.curves Matrix of curve values
% Each log curve is in a column and the first column is usually the depth.
% Thus, if w1log.curves has n columns, then there are n-1 log curves.
% If necessary, the rows of curve data are resorted so that
% depth increases from one row to the next
%
% wlog.curve_info Cell array (3 x number of curves) with curve
% mnemonics, curve units of measurement, and curve descriptions
% wlog.first Start of log (first depth in file)
% wlog.last End of log (last depth in file)
% wlog.step Depth increment (0 if unequal)
% wlog.units Units of measurement for depth
% wlog.null Null value (set to NaN) if there are no-data values
% otherwise, this field is not set
% wlog.wellname Name of well
% wlog.location Location of well
% wlog.company Oil/gas company which drilled the well
% wlog.field Field in which well is located
%
% The following components, while desirable, may or may not be present
% (depending on LAS file), and others may be present.
% They include well identification such as
% wlog.country Country in which well is located
% wlog.wellid Well Identifier
% wlog.api API number of the well
% wlog.service Service company which logged the well
%
% Also included are all parameters in the Parameter Section of the
% LAS header which have numerical values other than the null value.
% Each parameter is stored in a field of the log structure; its
% units of measurement and a description are stored in a row of
% the cell array "wlog.parameter_info"
% Examples illustrating such parameters are
% wlog.ekb=84 Kelly bushing elevation
% wlog.egl=0 Ground level elevation
% wlog.parameter_info={'ekb','ft','Kelly bushing elevation';
% 'egl','ft','Ground level elevation'}
run_presets_if_needed
% Sections of LAS 3.0 file to read in addition to the standard ones
param.section=[];
% Replace defaults by actual input parameters
param=assign_input(param,varargin);
if ~isempty(param.section)
param.section=tokens(param.section,',');
end
if nargin == 0 || isempty(filename);
[fid,filename]=open_file('rt','.las');
else
[fid,filename]=open_file('rt',filename);
end
tlines=textscan(fid,'%s','delimiter','\n');
fclose(fid);
tlines=tlines{1};
bool=~cellfun(@isempty,tlines); % Matlab version > 7.04
% bool=~cellfun('isempty',tlines);
tlines=tlines(bool);
bool=cellfun(@isempty,regexp(tlines,'^#')); % Matlab version > 7.04
% bool=cellfun('isempty',regexp(tlines,'^#'));
tlines=tlines(bool);
% Check version
temp=tokens(tlines{1},' ');
tlines(1)=temp(1);
if strcmpi(tlines{1},'~VERSION')
comp=split_line(tlines{2});
if strcmp(comp{1},'VERS')
if str2double(comp{2}) == 3
wlog=interpret_las3(tlines(3:end),param);
elseif str2double(comp{2}) == 2
wlog=interpret_las2(tlines(3:end));
elseif str2double(comp{2}) == 1.2
warning(warnid,'LAS-file version is 1.2')
else
error(['Unknown LAS-file version ',comp{2}])
end
end
else
error(['The file specified, "',filename,'", is not a LAS file.'])
end
% Remove unnecessary fields
wlog=clean_up_well_log(wlog);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=clean_up_well_log(wlog)
% Remove certain text fields if they are either empty or their value
% is "unknown".
fields={'wellname','country','county','state','api','wellid', ...
'location','field','company','service','date'};
lfields=length(fields);
bool=false(1,lfields);
for ii=1:lfields
try
txt=wlog.(fields{ii});
if isempty(txt) || ~isempty(findstr('unknown',lower(txt)))
bool(ii)=true;
end
catch
% Do nothing
end
end
if any(bool)
wlog=rmfield(wlog,fields(bool));
end
|
github
|
Abakumov/MLIB-master
|
s_create_qfilter.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_create_qfilter.m
| 3,649 |
utf_8
|
653c5f5d0ffbf454f9275950598ab48f
|
function qf=s_create_qfilter(varargin)
% Function computes a series of constant-Q absorption filters. These filters have
% an amplitude spectrum equal to exp(-pi*f*t/Q) where f is frequency, t is travel
% time, and Q denotes the quality factor (usually in the range of 30 to 200).
% The total number of traces output equals the product or the number of Q values
% and time values specified. They are sorted in the order:
% Q1T1, Q2T1, ... , QnT1, Q1T2, Q2T2, ...
%
% Written by: E. Rietsch: July 4, 2000
% Last updated: January 1, 2007: convert to single-precision if required
%
% qfilter=s_create_qfilter(varargin)
% INPUT
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters
% 'q' sequence or vector of Q values
% Default: {'q',140,120,100,80,60,40} which is equivalent to
% {'q',[140,120,100,80,60,40]}
% 'times' one or more travel time values
% Default: {'time',1000}
% 'length' Length of the absorption filters in ms. Default: {'length',1000}
% 'step' Sample interval if the absorption filters in ms. Default: {'step',1}
% OUTPUT
% qfilter seismic structure with the computed filters
% Headers Q and TIME record the parameters used for each filter
% EXAMPLE
% qf = s_create_qfilter({'q',50,100,150},{'times',500,1000})
global S4M
run_presets_if_needed
% Set default values for input arguments
param.q=[140,120,100,80,60,40];
param.time=[];
param.times=1000;
param.length=1000;
param.step=1;
% Decode and assign input arguments
param=assign_input(param,varargin);
if ~isempty(param.time) % Handle legacy parameter
param.times=param.time;
disp(' s_create_qfilter: keyword "time" is deprecated; use "times" instead.')
end
if iscell(param.q)
param.q=cat(1,param.q{:});
else
param.q=param.q(:);
end
nq=length(param.q);
if iscell(param.times)
param.times=cat(1,param.times{:});
end
nt=length(param.times);
nqnt=nq*nt;
nsamp=fix(param.length/param.step)+1;
qf.type='seismic';
qf.tag='wavelet';
qf.name='Q-filter';
qf.first=0;
qf.step=param.step;
qf.last=param.length;
qf.units='ms';
qf.traces=f_qfilter(param.q,param.times,nsamp,param.step);
qf.null=[];
qf.headers=zeros(2,nqnt);
qf.header_info=[{'q','n/a','Absorption parameter'}; ...
{'time','ms','Two-way travel time used for filter'}];
qf.headers(1,:)=reshape(param.q(:,ones(nt,1)),1,nqnt);
param.times=param.times(:);
qf.headers(2,:)=reshape(param.times(:,ones(nq,1))',1,nqnt);
% Create history field
if S4M.history
qf=s_history(qf,'add','Q-filters');
end
% Convert to single-precision if required
if strcmpi(S4M.precision,'single')
qf=single(qf);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function qf=f_qfilter(q,t,nsamp,dt)
% Function computes constant-Q absorption filters
% INPUT
% q array of Q values for which to compute the filters
% t array of one-way time values for which to compute the filters (ms)
% nsamp filter length in samples
% dt sample interval (ms)
% OUTPUT
% qf samples of absorption filter
nq=length(q);
nt=length(t);
nqnt=nq*nt;
nyquist=500/dt;
nsamp=nsamp*2; % Compute filter for twice the requested filter length
f=(0:2:nsamp)'*(nyquist/nsamp);
qt=reshape((0.001*pi./q(:))*t(:)',1,nqnt);
amp=exp(-f*qt);
amp=[amp;flipud(amp)];
qf=zeros(nsamp,nqnt);
for ii=1:nqnt
qf(:,ii)=minimum_phase(amp(:,ii),nsamp);
qf(:,ii)=qf(:,ii)/sum(qf(:,ii)); % DC component should be 1
end
qf=qf(1:nsamp/2,:); % Shorten filter to the requested filter length
|
github
|
Abakumov/MLIB-master
|
s_spectrum2wavelet.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_spectrum2wavelet.m
| 3,686 |
utf_8
|
fefc784e467d1c3d52b51e2d1b682b19
|
function wavelet=s_spectrum2wavelet(freq,amps,varargin)
% Compute zero-phase wavelet from its amplitude spectrum;
% unless spectral amplitudes are defined for zero frequency and/or Nyquist
% frequency (i.e. freq(1) == 0 and/or freq(end) == 500/step) they are set
% to zero.
%
% Written by: E. Rietsch: November 27, 2004
% Last updated: March 30, 2008: bug fix%
%
% wavelet=s_spectrum2wavelet(freq,amps,varargin)
% INPUT
% freq frequency values at which the spectrum is defined
% amps associated values of the amplitude spectrum
% varargin one or more cell arrays; the first element of each cell array
% is a keyword, the other elements are parameters.
% Presently, keywords are:
% 'dc_removal' should DC be removed. Possible values: 'yes' and 'no'.
% Default: {'dc_removal','yes'}
% 'method' Interpolation method used for spectrum; possible values are
% parameters allowed for function "interp1".
% Default: {'method','linear'}
% 'step' sample interval of the seismic
% Default: {'step',4}
% 'window' Type of window to apply to the wavelet. Possible windows are
% in function "mywindow". Use 'rect' or 'none' if you do not
% want a window.
% Default: {'window','trapezoid'}
% 'wlength' wavelet length
% Default: {'wlength',100}
% OUTPUT
% wavelet zero-phase wavelet with spectrum defined by "freq" and "amps".
%
% EXAMPLE
% wavelet=s_spectrum2wavelet([10,20,40,60],[0,1,1,0],{'wlength',80})
% s_spectrum(wavelet)
% UPDATE HISTORY
% August 3, 2006: Added option to apply window to wavelet;
% better DC removal
global S4M
% Set defaults of input arguments
param.dc_removal='yes';
param.method='linear';
param.step=4;
param.window='trapezoid';
param.wlength=100;
% Replace defaults by actual input parameters
param=assign_input(param,varargin);
nsamp=odd(param.wlength/param.step);
ansamp1=nsamp-1;
awlength=ansamp1*param.step;
% Wavelet length used for spectrum interpolation
nsamp1=4*ansamp1;
nsamp=nsamp1+1;
% Sample interval in the frequency domain
equidist=(0:2:nsamp)*500/(param.step*nsamp);
equidist(end)=min(equidist(end),freq(end));
if freq(1) > 0
freq=[0;freq(:)];
amps=[0;amps(:)];
end
if freq(end) < 500/param.step;
freq=[freq(:);equidist(end)];
amps=[amps(:);0];
else
freq(end)=equidist(end);
end
[freq,index]=unique(freq);
amps=amps(index);
aspectrum=reshape(interp1(freq,amps,equidist,param.method),[],1);
aspectrum(isnan(aspectrum))=0;
aspectrum=[aspectrum;aspectrum(end:-1:2)];
wavelet.type='seismic';
wavelet.tag='wavelet';
wavelet.name='Wavelet with defined spectrum';
wavelet.first=-awlength/2;
wavelet.last=-wavelet.first;
wavelet.step=param.step;
wavelet.units='ms';
traces=fftshift(real(ifft(aspectrum)));
inc=(nsamp1-ansamp1)/2;
wavelet.traces=traces(inc+1:end-inc);
% keyboard
% Check for null values
if any(isnan(wavelet.traces))
wavelet.null=NaN;
else
wavelet.null=[];
end
% Apply window to wavelet
if ~ismember(lower(param.window),{'rect','none'})
wavelet.traces=wavelet.traces.*mywindow(length(wavelet.traces),param.window);
else
wavelet.traces([1,end])=wavelet.traces([1,end])*0.5;
end
% Remove DC
if strcmpi(param.dc_removal,'yes')
wavelet.traces=lf_dc_removal(wavelet.traces,2);
% wavelet.traces=wavelet.traces-sum(wavelet.traces)/(length(wavelet.traces)-1);
end
if strcmp(S4M.precision,'single')
wavelet=single(wavelet);
else
wavelet=double(wavelet);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function m=odd(m)
m=2*round((m-1)*0.5)+1;
|
github
|
Abakumov/MLIB-master
|
read_las2_file.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/read_las2_file.m
| 18,770 |
utf_8
|
2c29248cebe60ad5c5580af2cefa4a69
|
function [wlog,las_header]=read_las2_file(filename,iprint)
% Function reads well logs from a disk file in LAS format (Log ASCII Standard),
% Version 2.0, as specified by the Canadian Well Logging Society.
% Generally somewhat faster than "read_las_file" but may be deprecated in
% the future.
% See also: read_las_file
%
% Written by: E. Rietsch: February 6, 2000;
% Last updated: October 10, 2006: Replace "strim" by "strtrim"
%
% [wlog,las_header]=read_las2_file(filename,iprint)
% INPUT
% filename string with the file name (and full path if desired);
% if the file is not found a file selection box will pop up to
% allow interactive file selection
% iprint Control diagnostic output (optional)
% iprint = 0 ==> no output; DEFAULT
% iprint ~= 0 ==> print out progress of file reading
% OUTPUT
% wlog structure containing the log curves and ancillary information such as:
% wlog.type type of structure; set to 'well_log'
% wlog.name name of the file (without extension) from which the log was red
% wlog.curves Matrix of curve values
% Each log curve is in a column and the first column is usually the depth.
% Thus, if wlog.curves has n columns, then there are n-1 log curves.
% If necessary, the rows of curve data are resorted so that
% depth increases from one row to the next
%
% wlog.curve_info Cell array (3 x number of curves) with curve
% mnemonics, curve units of measurement, and curve descriptions
% wlog.first Start of log (first depth in file)
% wlog.last End of log (last depth in file)
% wlog.step Depth increment (0 if unequal)
% wlog.units Units of measurement for depth
% wlog.null Null value (set to NaN) if there are no-data values
% otherwise, this field is not set
% wlog.wellname Name of well
% wlog.location Location of well
% wlog.company Oil/gas company which drilled the well
% wlog.field Field in which well is located
%
% The following components, while desirable, may or may not be present
% (depending on LAS file), and others may be present.
% They include well identification such as
% wlog.country Country in which well is located
% wlog.wellid Well Identifier
% wlog.api API number of the well
% wlog.service Service company which logged the well
%
% Also included are all parameters in the Parameter Section of the
% LAS header which have numerical values other than the null value.
% Each parameter is stored in a field of the log structure; its
% units of measurement and a description are stored in a row of
% the cell array "wlog.parameter_info"
% Examples illustrating such parameters are
% wlog.ekb=84 Kelly bushing elevation
% wlog.egl=0 Ground level elevation
% wlog.parameter_info={'ekb','ft','Kelly bushing elevation';
% 'egl','ft','Ground level elevation'}
% las_header LAS header of log (provides additional information about the well)
global S4M
run_presets_if_needed
if nargin <= 1;
iprint=0;
if nargin == 0
filename='';
end
end
% Open the file
if ~isempty(filename)
fid=fopen(filename,'rt');
if fid > 0
filename2S4M(filename)
end
else
fid=-1;
end
if fid == -1
[filename,ierr]=get_filename4r('las');
if ierr
error('No file selected')
end
fid=fopen(filename,'rt');
if fid < 0
error(['File "',filename,'" could not be opened.'])
end
end
lashead=repmat(32,3,100);
nhead=1;
buffer=get_buffer(fid);
lashead(1,1:length(buffer))=buffer;
while strcmpi(buffer(1),'#')
buffer=get_buffer(fid);
nhead=nhead+1;
lashead(nhead,1:length(buffer))=buffer;
end
if ~strcmpi(buffer(1:2),'~v')
error('File is not a LAS file');
end
% Determine the version of LAS
buffer=get_buffer(fid);
nhead=nhead+1;
lashead(nhead,1:length(buffer))=buffer;
% if length(buffer) > bmax, bmax=length(buffer); end
ind=find(buffer == ':')-1;
ind1=find(buffer == '.')+1;
%vernum=sscanf(buffer(ind1(1):ind),'%*s%f');
vernum=sscanf(buffer(ind1(1):ind),'%f');
% Check for wrapping
buffer=get_buffer(fid);
nhead=nhead+1;
lashead(nhead,1:length(buffer))=buffer;
% if length(buffer) > bmax, bmax=length(buffer); end
ind=find(buffer == ':')-1;
wrapflag=sscanf(buffer(1:ind),'%*s%s');
if strcmpi(wrapflag,'YES')
disp(' LAS file is wrapped')
% disp([mfilename,' cannot read wrapped LAS files'])
% error(' use REFORMAT.EXE from http://www.cwls.org to unwrap file');
end
if vernum ~= 2.0
disp([mfilename,' can only read Version 2.0 LAS files'])
error(' use REFORMAT.EXE from http://www.cwls.org to convert from version 1.2 to 2.0');
else
[wlog,las_header] = read_las_v20(fid,iprint);
end
las_header=char(strtrim(char(lashead)),las_header);
% Check log start and end time and step size
if isempty(wlog.curves)
disp(' No log curve values read; there may be non-numeric characters in the data block')
error(' Check data section of LAS file')
end
wlog.units=wlog.curve_info{1,2};
if wlog.first ~= wlog.curves(1,1)
fprintf(['Log start depth (',num2str(wlog.curves(1,1)), ...
') differs from header information (',num2str(wlog.first), ...
'); now corrected\n'])
wlog.first=wlog.curves(1,1);
end
if wlog.last ~= wlog.curves(end,1)
fprintf(['Log end depth (',num2str(wlog.curves(end,1)), ...
') differs from header information (',num2str(wlog.last), ...
'); now corrected\n']);
wlog.last=wlog.curves(end,1);
end
if wlog.step ~= 0
if ~isconstant(diff(wlog.curves(:,1)),S4M.log_step_error)
fprintf('Log step size not uniform enough; step size changed to 0\n')
end
end
% Make sure that log depths are ascending
if wlog.first > wlog.last
wlog.curves=flipud(wlog.curves);
temp=wlog.first;
wlog.first=wlog.last;
wlog.last=temp;
wlog.step=-wlog.step;
end
% Replace null values by NaNs
idx=find(wlog.curves == wlog.null);
if ~isempty(idx)
wlog.curves(idx)=NaN;
wlog.null=NaN;
else
wlog.null=[];
end
% Replade 'UNDEFINED' in curve description when it is obvious from the mnemonic
wlog.curve_info=description_substitution(wlog.curve_info);
% Replace unadmissible curve mnemonics
wlog.curve_info(:,1)=fix_mnemonics(wlog.curve_info(:,1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [wlog,las_header]=read_las_v20(fid,iprint)
% Function reads LAS file version 2.0
% Date Feb. 12, 2000; written by E. Rietsch
% Feb. 19, 2000; updated to handle better missing key words
%
% INPUT
% fid File id of LAS file
% iprint Control diagnostic output (optional)
% iprint = 0 ==> No output; DEFAULT
% iprint ~= 0 ==> diagnostic output
%
% OUTPUT
% wlog structure contining the log curves and ancillary information
% wlog.curves Matrix of curve values
% Each log is in a column and the first column is usually the depth.
% Thus, if wlog.curves has n columns, then there are n-1 log curves.
% If necessary, the rows of curve data are resorted so that
% depth increases from one line to the next
%
% wlog.curve_info Cell array (3 x number of curves) with curve mnemonics,
% curve units of measurement, and curve descriptions
% wlog.first Start of log (first depth in file)
% wlog.last End of log (last depth in file)
% wlog.step Depth increment (0 if unequal)
% wlog.null Null value (set to NaN)
% wlog.las_header LAS header of log (provides additional information about the well)
% wlog.wellname Name of well
% wlog.location Location of well
% wlog.company Oil/gas company which drilled the well
% wlog.field Field in which well is located
%
% The following components, while desirable, may or may not be present
% (depending on LAS file), and others may be present.
% They include well identification such as
% wlog.country Country in which well is located
% wlog.county County in which well is located
% wlog.province Province in which well is located
% wlog.state State in whichwell is located
% wlog.uwi Universal well identifier (Canada)
% wlog.wellid Well Identifier
% wlog.api API number of the well (USA)
% wlog.service Service company which logged the well
%
% Also included are all parameters in the Parameter Section of the
% LAS header which have numerical values other than the null value.
% Each parameter is stored in a field of the log structure; its
% units of measurement and a description are stored in a row of
% the cell array "wlog.parameter_info"
% Examples illustrating such parameters are
% wlog.ekb=84 Kelly bushing elevation
% wlog.egl=0 Ground level elevation
% wlog.parameter_info={'ekb','ft','Kelly bushing elevation';
% 'egl','ft','Ground level elevation'}
global S4M
wlog.type='well_log';
wlog.tag='unspecified';
[dummy,wlog.name]=fileparts(S4M.filename); %#ok The first output argument
% is not required
wlog.from=fullfile(S4M.pathname,S4M.filename);
% Allocate space for a 200x100-byte header
nchar=100;
% las_header=32*ones(200,nchar);
las_header=repmat(32,200,nchar);
mnem_length=25; % Maximum length of curve mnemonic
% Accomodate up to 100 curves and up to 100 parameters
%n_curves=100;
%n_param=100;
if nargin == 1; iprint=0; end
nhead=0;
bmax=0;
buffer=get_buffer(fid);
while isempty(buffer) || ~strcmpi(buffer(1:2),'~a')
unknown_block=1; % Used to check if an unknown block is in the file
% Well information block
if strcmpi(buffer(1:2),'~w')
if iprint ~= 0, disp('... reading well info'); end
unknown_block=0;
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if iprint ~= 0
disp('... reading well info');
end
buffer=get_buffer(fid);
while buffer(1:1) ~= '~'
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
ia=find(buffer == '.')+1;
if length(ia) > 1
ia=ia(1);
end
ind=find(buffer==':')-1;
kw=deblank(buffer(1:ia-2));
% Check for start, stop and step
if strcmpi(kw,'STRT')
% if buffer(ia) ~= ' '
if ~strcmp(buffer(ia),' ')
temp=sscanf(buffer(ia:ind),'%s',1);
nu=length(temp);
else
nu=0;
end
wlog.first = sscanf(buffer(ia+nu:ind),'%f',1);
end
if strcmpi(kw,'STOP')
if ~strcmp(buffer(ia),' ')
% if buffer(ia) ~= ' '
temp=sscanf(buffer(ia:ind),'%s',1);
nu=length(temp);
else
nu=0;
end
wlog.last = sscanf(buffer(ia+nu:ind), '%f',1);
end
if strcmpi(kw,'STEP')
% if buffer(ia) ~= ' '
if ~strcmp(buffer(ia),' ')
nu=length(temp);
else
nu=0;
end
wlog.step = sscanf(buffer(ia+nu:ind), '%f');
wlog.units=''; % Place holder
end
if strcmpi(kw,'NULL')
wlog.null = sscanf(buffer(ia:ind), '%f');
end
if strcmpi(kw,'COMP')
wlog.company = strtrim(buffer(ia:ind));
end
if strcmpi(kw,'WELL')
wlog.wellname = strtrim(buffer(ia:ind));
end
if strcmpi(kw,'FLD')
wlog.field = strtrim(buffer(ia:ind));
end
if strcmpi(kw,'LOC')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.location = temp; end
end
if strcmpi(kw,'PROV')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.province = temp; end
end
if strcmpi(kw,'CTRY')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.country = temp; end;
end
if strcmpi(kw,'CNTY')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.county = temp; end;
end
if strcmpi(kw,'STAT')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.state = temp; end;
end
if strcmpi(kw,'UWI')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.wellid = temp; end
end
if strcmpi(kw,'API')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.api = temp; end
end
if strcmpi(kw,'SRVC')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.service = temp; end
end
if strcmpi(kw,'DATE')
temp=strtrim(buffer(ia:ind));
if ~isempty(temp), wlog.date = temp; end
end
buffer=get_buffer(fid);
end
if iprint ~= 0, disp('... finished reading well info'); end
end
% Parameter information block
if strcmpi(buffer(1:2),'~p')
unknown_block=0;
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if iprint ~= 0, disp('... reading parameter info'); end
buffer=get_buffer(fid);
while buffer(1:1) ~= '~'
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if ~strcmpi(buffer(1),'#')
ind=find(buffer(1:min([lb-1,21])) == '.')-1;
ind=ind(1);
parameter=lower(strtrim(buffer(1:ind)));
ind1=find(buffer == ':');
if ~strcmpi(buffer(ind+2),' ') && ~strcmpi(buffer(ind+2),':')
unit=sscanf(buffer(ind+2:ind1-1),'%s',1);
nu=length(unit);
unit=char(unit_substitution(unit));% Change abbreviations for units of measurement
else
unit='UNDEFINED';
nu=0;
end
value=strtrim(buffer(ind+nu+2:ind1-1));
temp=strtrim(buffer(ind1+1:end));
if ~isempty(temp)
n=min([60 length(temp)]);
descr=temp(1:n);
else
descr='UNDEFINED';
end
if isnumber(value)
if str2double(value) ~= wlog.null
if ~isfield(wlog,'parameter_info')
wlog.parameter_info={parameter,unit,descr};
else
wlog.parameter_info=[wlog.parameter_info;
{parameter,unit,descr}];
end
% wlog.parameter_info=setfield(wlog.parameter_info,parameter,{unit,descr});
% wlog=setfield(wlog,parameter,str2double(value));
wlog.(parameter)=str2double(value);
end
end
end
buffer=get_buffer(fid);
end
% if isempty(wlog.parameter_info), wlog=rmfield(wlog,'parameter_info'); end
if iprint ~= 0, disp('... finished reading parameter info'); end
end
% Curve information block
if strcmpi(buffer(1:2),'~c')
unknown_block=0;
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if iprint ~= 0, disp('... reading curve info'); end
buffer=get_buffer(fid);
nlogs=0;
curve_info=cell(3,100); % Reserve sufficient room for curve information
while isempty(buffer) || buffer(1:1) ~= '~'
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if ~strcmp(buffer(1),'#')
nlogs=nlogs+1;
ind=find(buffer(1:min(length(buffer),mnem_length+1)) == '.')-1;
if isempty(ind)
disp(' No period (dot) found.')
disp([' Curve mnemonic could be longer than ',num2str(mnem_length),' characters:'])
disp(buffer)
fclose(fid);
error(' Abnormal termination')
end
% Get units of measurement
ind1=find(buffer == ':');
if ~strcmp(buffer(ind+2),' ')
% curve_info(2,nlogs)={sscanf(buffer(ind+2:ind1-1),'%s',1)};
temp=strtrim(buffer(ind+2:ind1-1));
idx=findstr(temp,' ');
if ~isempty(idx) % Are there blanks in the unit description?
idx1=find(diff(idx)==1);
if isempty(idx1)
curve_info{2,nlogs}=temp;
else
curve_info{2,nlogs}=temp(1:idx(idx1(1))-1);
end
else
curve_info{2,nlogs}=temp;
end
else
curve_info{2,nlogs}='UNDEFINED';
end
% Get description
ind2=find(buffer(ind1+1:end) > 64);
if ~isempty(ind2)
curve_info{3,nlogs}=buffer(ind1+ind2(1):end);
else
curve_info{3,nlogs}='UNDEFINED';
end
curve_info{1,nlogs}=deblank(buffer(1:ind(1)));
end
buffer=get_buffer(fid);
end
curve_info=curve_info(:,1:nlogs); % Release unused, reserved space
if iprint ~= 0, disp('... finished reading curve info'); end
end
% Other information block
if strcmpi(buffer(1:2),'~o')
unknown_block=0;
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
if iprint ~= 0, disp('... reading other information'); end
buffer=deblank(fgetl(fid));
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
while isempty(buffer) || buffer(1:1) ~= '~'
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
buffer=deblank(fgetl(fid));
end
if iprint ~= 0, disp('... finished reading other information'); end
end
if unknown_block == 1 % Unknown block encountered:
% Write it to header
nhead=nhead+1;
lb=min([length(buffer)-1,nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
buffer=deblank(fgetl(fid));
while ~isempty(buffer) && buffer(1:1) ~= '~'
nhead=nhead+1;
lb=min([length(buffer),nchar]);
bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
buffer=get_buffer(fid);
end
end
end % Last block (log curves) reached
nhead=nhead+1;
lb=min([length(buffer),nchar]);
% bmax=max([lb,bmax]);
las_header(nhead,1:lb)=buffer(1:lb);
las_header=deblank(char(las_header(1:nhead,:)));
% ASCI log curves
if iprint ~= 0, disp('... reading ASCII curve values'); end
wlog.curves=fscanf(fid,'%g',[nlogs,inf])';
if iprint ~= 0, disp('... finished reading ASCII curve values'); end
fclose(fid);
wlog.curve_info=curve_info';
if strcmpi(curve_info{1,1},'dept')
wlog.curve_info{1,1}='DEPTH';
end
% Change abbreviations for units of measurement
for ii=1:nlogs
wlog.curve_info(ii,2)=unit_substitution(wlog.curve_info(ii,2));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function buffer=get_buffer(fid)
% Get next line in file
% INPUT
% fid file identifier
% OUTPUT
% buffer line of text
buffer=strtrim(fgetl(fid));
while isempty(buffer)
buffer=strtrim(fgetl(fid));
end
if length(buffer == 1) %#ok
buffer=[buffer,' '];
end
|
github
|
Abakumov/MLIB-master
|
show_segy_header.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/show_segy_header.m
| 2,859 |
utf_8
|
4bd3527ee2effbdee496ea4c6265bc38
|
function header=show_segy_header(filename)
% Function displays the EBCDIC header of a SEG-Y file
% Date Feb. 20, 2000; written by E. Rietsch
% INPUT
% filename name of the file
% if the name is omitted or does not refer to an existing file
% a file selector box will pop up to allow interactive file
% selection
% OUTPUT
% header EBCDIC header as an ASCII string
% if argument is omitted the header will be printed
%
% header=show_segy_header(filename)
% Open the file
if nargin == 1
fid=fopen(filename,'r');
end
if nargin == 0 || fid==-1
selected_file=get_filename4r('sgy'); % Open file selector box
fid=fopen(selected_file,'r','ieee-be');
end
% Read EBCDIC header 1
header_ebcdic=fread(fid,3200,'uchar');
header_ascii=char(ebcdic2ascii(reshape(header_ebcdic,80,40)'));
if nargout == 0
disp(header_ascii);
else
header=header_ascii;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ascii=ebcdic2ascii(ebcdic)
% Function converts EBCDIC string to ASCII
% see http://www.room42.com/store/computer_center/code_tables.shtml
% Date Feb. 20, 2000; written by E. Rietsch
% INPUT
% ebcdic EBCDIC string
% OUTPUT
% ascii ASCII string
% ascii=ebcdic2ascii(ebcdic)
pointer= ...
[ 0 16 32 46 32 38 45 46 46 46 46 46 123 125 92 48
1 17 33 46 46 46 47 46 97 106 126 46 65 74 46 49
2 18 34 50 46 46 46 46 98 107 115 46 66 75 83 50
3 19 35 51 46 46 46 46 99 108 116 46 67 76 84 51
4 20 36 52 46 46 46 46 100 109 117 46 68 77 85 52
5 21 37 53 46 46 46 46 101 110 118 46 69 78 86 53
6 22 38 54 46 46 46 46 102 111 119 46 70 79 87 54
7 23 39 55 46 46 46 46 103 112 120 46 71 80 88 55
8 24 40 56 46 46 46 46 104 113 121 46 72 81 89 56
9 25 41 57 46 46 46 46 105 114 122 46 73 82 90 57
10 26 42 58 46 33 124 58 46 46 46 46 46 46 46 46
11 27 43 59 46 36 44 35 46 46 46 46 46 46 46 46
12 28 44 60 60 42 37 64 46 46 46 46 46 46 46 46
13 29 45 61 40 41 95 39 46 46 91 93 46 46 46 46
14 30 46 46 43 59 62 61 46 46 46 46 46 46 46 46
15 31 47 63 124 94 63 34 46 46 46 46 46 46 46 46];
pointer=reshape(pointer,1,256);
ascii=pointer(ebcdic+1);
|
github
|
Abakumov/MLIB-master
|
s_shift.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_shift.m
| 6,837 |
utf_8
|
4614f27f8884374473742651300926f2
|
function seismic=s_shift(seismic,varargin)
% Function applies user-specified time shifts to seismic traces
%
% Written by: E. Rietsch: July 2001
% Last updated: March 23, 2008: bug fix for constant shift; output
% precision is input precision
%
% seismic=s_shift(seismic,varargin)
% INPUT
% seismic seismic structure
% varargin one or more cell arrays; the first element of each cell array
% is a keyword, the other elements are parameters.
% Presently, keywords are:
% 'shifts' the second cell is either a constant time shift applied to
% all traces, cell an array with a shift for each trace of
% "seismic", or a header mnemonic.
% Shifts are rounded to the nearest integer multiples of the
% sample interval "seismic.step"
% 'header' header mnemonic to be used if shifts should be put into header (if they
% are not already there). It must not yet exist in the input data set.
% Default: {'header',[]}; i.e. not used
% 'interpol' interpolate trace values if the shifts are not integer
% multiples of the sample interval; default is 'no' (shifts are
% rounded to the nearest multiple of the sample interval.
% NOT YET IMPLEMENTED
% 'scale' factor to apply to the shifts before they are applied to
% the traces this is generally meant for shifts stored in a
% header (e.g. multiplication by -1).
% 'option' this keyword determines what should be done with data that
% are shifted outside the time range of "seismic". Possible values are:
% 'extend' extend the time range to accommodate all shifts. It means that
% seisout.first=seismic.first+min(shifts)
% seisout.last=seismic.last+max(shifts)
% 'truncate' trace values that fall outside the time range of
% seismic are discarded
% 'circular' a circular time shift is applied.
% Default: {'option','extend'}
% 'null' value to use for samples that have been shifted into the time range of
% "seisout". This will happen whenever different traces are shifted by
% different amounts AND 'option' is not 'circular'.
% Default: {'null',0}.
% OUTPUT
% seisout seismic input dataset with shifts applied
%
% EXAMPLE
% seis=s_data;
% ntr=size(seis.traces,2);
% seis_shifted=s_shift(seis,{'shifts',linspace(-72,60,ntr)},{'header','shifts'});
% s_compare(seis,seis_shifted)
% UPDATE HISTORY
% March 30, 2006: Apply scale before computing sample indices
% November 6, 2007: same input and output dataset
% Set defaults of input parameters
param.shifts=0;
param.header=[];
param.interpol='no';
param.scale=1;
param.option='extend';
param.null=0;
param.precision=class(seismic.traces);
% Replace defauls by actual input arguments
param=assign_input(param,varargin);
if isyes(param.interpol)
alert(' Interpolation not yet implemented; shifts rounded to nearest sample instead.')
end
ntr=size(seismic.traces,2);
% Get the shifts
if ~ischar(param.shifts)
if iscell(param.shifts)
error(' Cell array with keyword "shifts" can have only two elements (including ''shifts'')')
end
nsh=length(param.shifts);
shifts=round(param.shifts*(param.scale/seismic.step));
if nsh ~= ntr && nsh ~= 1
error([' Number of shifts (',num2str(nsh), ...
') differs from number of traces (',num2str(ntr),')'])
end
else % Get shifts from headers
shifts=s_gh(seismic,param.shifts)*(param.scale/seismic.step);
shifts=round(shifts);
nsh=ntr;
end
if nsh == 1
seismic=constant_shift_no1(seismic,shifts,param);
else
if isconstant(shifts,eps) % all shifts are the same
seismic=constant_shift_no1(seismic,shifts(1),param);
else
[seismic,shmin,shmax]=tracewise_shift_no2(seismic,shifts,param);
end
end
% Add header (if requested)
if ~isempty(param.header)
seismic=s_header(seismic,'add_ne',param.header,shifts*seismic.step,seismic.units,'Shifts applied');
end
if isnan(param.null)
seismic.null=NaN;
end
% Append history field
if isfield(seismic,'history')
try
htext=[param.option,': Minimum shift: ',num2str(seismic.step*shmin), ...
', maximum shift: ',num2str(seismic.step*shmax)];
catch
htext='';
end
seismic=s_history(seismic,'append',htext);
end
% Update dataset name
seismic.name=[seismic.name,' - shifted'];
% Change precision to that of input data
if strcmpi(param.precision,'single')
seismic=single(seismic);
else
seismic=double(seismic);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic=constant_shift_no1(seismic,shift,param)
switch param.option
case 'extend'
shift=shift*seismic.step;
seismic.first=seismic.first+shift;
seismic.last=seismic.last+shift;
case 'truncate'
shift=shift*seismic.step;
first=seismic.first;
last=seismic.last;
seismic.first=seismic.first+shift;
seismic.last=seismic.last+shift;
seismic=s_select(seismic,{'times',first,last});
case 'circular'
seismic.traces=circshift(seismic.traces,double(shift));
otherwise
error(['Unknown parameter for keyword "option": ',param.option])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [seismic,shmin,shmax]=tracewise_shift_no2(seismic,shifts,param)
% Each trace has its own amount of shift
[nsamp,ntr]=size(seismic.traces);
first=seismic.first;
last=seismic.last;
shmin=min(shifts);
shmax=max(shifts);
switch param.option
case {'extend','truncate'}
if isnan(param.null)
traces=NaN(nsamp+shmax-shmin,ntr,param.precision);
else
traces=repmat(param.null,nsamp+shmax-shmin,ntr);
end
for ii=1:ntr
ish=shifts(ii)-shmin;
if ~isnan(ish) && ~isempty(ish)
traces(ish+1:nsamp+ish,ii)=seismic.traces(:,ii);
end
end
case 'circular'
for ii=1:ntr
seismic.traces(:,ii)=circshift(seismic.traces(:,ii),double(shift));
end
otherwise
error(['Unknown parameter for keyword "option": ',param.option])
end
seismic.first=first+shmin*seismic.step;
seismic.last=last+shmax*seismic.step;
seismic.traces=traces;
switch param.option
case 'extend'
if any(isnan(traces(:)))
seismic.null=NaN;
else
seismic.null=[];
end
case 'truncate'
seismic=s_select(seismic,{'times',first,last});
if any(isnan(seismic.traces(:)))
seismic.null=NaN;
else
seismic.null=[];
end
otherwise
% do nothing
end
|
github
|
Abakumov/MLIB-master
|
s_wavextra.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_wavextra.m
| 13,805 |
utf_8
|
69e64aa24cda0071b2063aa33670384c
|
function [wavelet,aux]=s_wavextra(seismic,refl,varargin)
% Function extracts wavelet from seismic data using a log-derived
% reflectivity sequence.
%
% Written by E. Rietsch, May 6, 2000
% Last update: January 16, 2007: Discontinued use of "spdiags"
%
% [wavelet,aux]=s_wavextra(seismic,refl,varargin)
% INPUT
% seismic seismic traces in the vicinity of the well
% refl seismic structure representing the reflection coefficient sequence
% seismic and refl must have the same sample interval
% varargin one or more cell arrays; the first element of each cell array is a keyword,
% the other elements are parameters. Presently, keywords are:
% 'downstep' step size (in seismic time units - usually ms) by which log and
% seismic move down to compute a new wavelet.
% Default: {'downstep',20}
% 'headers' Header to copy from seismic to wavelets.
% Default: {'headers','*'} meaning all headers
% 'header_null' No-data value to use for missing header values.
% Default: {'header_null',NaN}
% 'wlength' wavelet length. Default 60 ms
% 'logshifts' vector of global shifts of the reflection coefficient
% sequence vs the seismic that are to be used (to account
% for a possible error in the time to the top of the log,
% bad check shot data). It can be one value or a vector.
% A wavelet is computed for each shift.
% Default: {'logshifts',0}
% 'logwindow' length of log segment matched to seismic. Recommended:
% logwindow >= 5*wlength
% Default: {'logwindow',refl.last-refl.first} i.e. the
% whole reflection coefficient series
% 'null' Null value to use; Default: {'null',NaN}
% 'print' Controls printed output showing progress of wavelet estimation;
% no output if set to 0. Default: {'print',1}
% 'scale' scale wavelets so that synthetic has about the same
% amplitude level as the seismic (counteract noise in data)
% Default: {'scale','yes'}
% 'sp_constraint' Controls use of spectrum constraints, representing
% the ratio of Frobenius norm of spectrum constraint to
% Frobenius norm of convolution matrix. If set to zero
% spectrum constraint is not used.
% Default: {'sp_constraint',0)
% 'dc_constraint' Constraint on the DC component of the wavelet
% Default: {'dc_constraint',0}
% 'wavshifts' vector of shifts of seismic data with respect to the
% reflection coefficients. It can be one value or a vector.
% It is intended to allow small changes in
% shifts for any value of 'logshifts'. Only the best wavelet
% found for any of the shifts is output
% Default: {'wavshifts',0}
% 'wnoise' White noise (ratio of to maximum reflection coefficient)
% Default: {'wnoise',0.1}
%
% OUTPUT
% wavelet wavelet(s) extracted from the seismic data. A number of headers are added to this
% data set to capture the following information about the wavelet.
% wstart start time of window over which wavelet is estimated
% cc_wavelet correlation coefficient for this wavelet and for this particular
% trace, window, and value of "logshifts"
% cc_max maximum correlation coefficient for this particular trace and
% value of "logshift" (common for all wavelets derived from the same
% seismic trace and the same value of "logshift")
% cc_median median correlation coefficient for this particular trace and
% value of "logshift" (common for all wavelets derived from the same
% seismic trace and the same value of "logshift")
% swstart start of seismic window used
% rwstart start of log window used
% aux structure with additional information
% aux.logsegments number of log segments used (==> number of
% wavelets per trace
% aux.logshifts number of bulk logshifts used (see keyword 'logshifts')
%
% EXAMPLES wavelets=s_wavextra(seismic,refl,{'logshifts',-40,4,32})
global ABORTED
ABORTED=true; %#ok Used in in compiled, GUI-based environment
% Set defaults for input parameters
param.downstep=20;
param.headers='*';
param.header_null=NaN;
param.wlength=60;
param.logshifts=0;
param.logwindow=refl.last-refl.first;
param.null=NaN;
param.print=1;
param.sp_constraint=0.0;
param.dc_constraint=0.0;
param.scale='yes';
param.wavshifts=0;
param.wnoise=0.1;
% Decode input arguments
param=assign_input(param,varargin); % Read input parameters
% Check input parameters
if param.logwindow > refl.last-refl.first
param.logwindow=refl.last-refl.first;
end
if strcmp(param.scale,'yes')
scaling=true;
else
scaling=false;
end
if iscell(param.wavshifts) % Legacy code
param.wavshifts=cell2mat(param.wavshifts);
end
temp(1)=round(param.wavshifts(1)/seismic.step);
temp(3)=round(param.wavshifts(end)/seismic.step);
increment=max(fix(temp(3)-temp(1))/length(param.wavshifts),1);
temp(2)=increment;
param.wavshifts=temp*seismic.step;
% Convert times to samples
nsampw=round(param.wlength/seismic.step)+1; % Number of samples of wavelet
nlogwindow=round(param.logwindow/seismic.step)+1; % Number of samples of log window
ndownstep=round(param.downstep/seismic.step); % Number of samples to step down for next window
nsampr=length(refl.traces); % Number of samples of reflection coefficient
[nsamp,ntr]=size(seismic.traces);
% Checking of input parameters
if abs(seismic.step - refl.step) > 1.06*eps*seismic.step
error([' Seismic and reflection coefficients have different sample intervals: ', ...
num2str([seismic.step,refl.step])])
end
temp=(seismic.first-refl.first)/seismic.step;
if abs(round(temp)-temp) > 1.0e6*eps
disp(' Start time of seismic and reflection coefficients differ by a non-integer')
disp(' multiple of the sample interval')
error(' Abnormal termination')
end
%{
if iscell(param.logshifts) % Legacy parameters
logshifts=param.logshifts{1}:param.logshifts{2}:param.logshifts{3};
else
logshifts=param.logshifts;
if isempty(logshifts)
error(' Empty array of log shifts supplied')
end
end
%}
first=round(param.logshifts(1)/seismic.step);
last=round(param.logshifts(end)/seismic.step);
step=max(fix(temp(end)-temp(1))/length(param.logshifts),1);
logshifts=(first:step:last)*seismic.step;
% Prepare for newly created headers
header_info=[ ...
{'cc_wavelet','n/a','Cross-correlation of synthetic and seismic'}; ...
{'cc_max','n/a','Maximum correlation for this trace and shift'}; ...
{'cc_median','n/a','Median correlation for this trace and shift'}; ...
{'swstart','ms','Start of seismic window used'}; ...
{'rwstart','ms','Start of reflection coefficient window used'}];
% Select seismic headers to copy to wavelet and append header_info
if isfield(seismic,'headers')
if ~iscell(param.headers)
param.headers={param.headers};
end
if length(param.headers) == 1 && strcmp(param.headers{1},'*')
param.headers=seismic.header_info(:,1);
end
[index,ier]=mnemonics_match(seismic.header_info(:,1),param.headers);
if ier
error(' Abnormal termination')
end
seismic_headers=seismic.headers(index,:);
header_info=[header_info;seismic.header_info(index,:)];
end
nheaders=size(header_info,1);
% Reserve room for arrays
nlogsegments=fix((nsampr-nlogwindow)/ndownstep)+1; % Number of log windows
nwavelets=ntr*nlogsegments*length(logshifts);
shifts=NaN*zeros(nwavelets,1);
% cc_wavelets=param.header_null*zeros(nwavelets,1);
wavelets=zeros(nsampw,nwavelets);
headers=param.header_null*zeros(nheaders,nwavelets);
iawav=1;
iewav=ntr;
nseiswindow=round((param.logwindow-param.wlength+ ...
param.wavshifts(end)-param.wavshifts(1))/seismic.step); % Correction
if param.print
disp(['S_WAVEXTRA uses ',num2str(nlogsegments),' log segment(s) and ', ...
num2str(length(logshifts)),' log shift(s)'])
end
aux.logsegments=nlogsegments;
aux.logshifts=logshifts;
nulls=0;
% Create constraint matrix
if param.sp_constraint ~= 0 % Create spectral constraint matrix
temp=s_select(seismic,{'times',refl.first,refl.last});
spc=spectral_constraints(sum(correlate(temp.traces,temp.traces),2),nsampw);
clear temp
spc=spc/norm(spc,'fro');
if param.dc_constraint ~= 0 % Add DC constraint matrix
spc(1,:)=spc(1,:)*(1+abs(param.dc_constraint/param.sp_constraint));
end
constraint=param.sp_constraint;
elseif param.dc_constraint ~= 0 % Create DC constraint matrix
spc=ones(1,nsampw)/sqrt(nsampw);
constraint=param.dc_constraint;
else
constraint=0;
spc=[];
end
if iscell(param.wavshifts)
increment=round(param.wavshifts{2}/seismic.step);
else
increment=round(param.wavshifts(2)/seismic.step);
end
ik=0;
% keyboard
for lshift=logshifts
ik=ik+1;
disp([' Shift: ',num2str(lshift),' (',num2str(ik),' of ',num2str(length(logshifts)),')'])
seismic_ta=refl.first+lshift+param.wavshifts(1)+param.wlength*0.5;
ia0=round((seismic_ta-seismic.first)/seismic.step);
ia=ia0+1;
iawav0=iawav;
ie=ia+nseiswindow;
ia=max(1,ia);
ia_refl=1;
ie_refl=nlogwindow;
%
for ii=1:nlogsegments
if ia > 0 && ie <= nsamp
s1=refl.traces(ia_refl:ie_refl,:);
s2=seismic.traces(ia:ie,:);
[filters,cc,shift,scale]=mfilter_t2d(s1,s2, ...
nsampw,param.wnoise,increment,constraint,spc);
if scaling
for jj=iawav:iewav
wavelets(:,jj)=filters(:,jj-iawav+1)*scale(jj-iawav+1);
end
% wavelets(:,iawav:iewav)=filters*spdiags(scale,0,length(scale),length(scale));
else
wavelets(:,iawav:iewav)=filters;
end
headers(1,iawav:iewav)=cc(:)';
headers(4,iawav:iewav)=seismic.first+((ia-1)+shift(:)')*seismic.step;
headers(5,iawav:iewav)=refl.first+ia_refl+refl.step;
shifts(iawav:iewav)=shift+ia0;
else % Not enough seismic data for a requested shift
nulls=1;
end
if exist('seismic_headers','var')
headers(6:end,iawav:iewav)=seismic_headers; % Store seimic headers
end
ia_refl=ia_refl+ndownstep;
ie_refl=ie_refl+ndownstep;
ia=ia+ndownstep;
ie=ie+ndownstep;
iawav=iawav+ntr;
iewav=iewav+ntr;
end
% Compute maximum and median correlation coefficient for each trace
temp=reshape(headers(1,iawav0:iewav-ntr),ntr,nlogsegments);
temp_max=max(temp,[],2);
if nulls
temp_median=NaN*zeros(size(temp,1),1);
for ll=1:size(temp,1)
idx=find(~isnan(temp(ll,:)));
if ~isempty(idx)
temp_median(ll)=median(temp(ll,idx));
end
end
else
temp_median=median(temp,2);
end
headers(2,iawav0:iewav-ntr)= ...
reshape(temp_max(:,ones(nlogsegments,1)),1,nlogsegments*ntr);
headers(3,iawav0:iewav-ntr)= ...
reshape(temp_median(:,ones(nlogsegments,1)),1,nlogsegments*ntr);
end
idx=find(~isnan(shifts))';
min_shift=min(shifts(idx));
shifts(idx)=shifts(idx)-min_shift;
max_shift=max(shifts(idx));
try
wavelet.type='seismic';
wavelet.tag='wavelet';
wavelet.name='';
wavelet.traces=param.null*zeros(nsampw+max_shift,nwavelets);
catch
disp(' Not enough space in MATLAB to store all requires wavelets')
%keyboard
end
for ii=idx
wavelet.traces(shifts(ii)+1:shifts(ii)+nsampw,ii)=wavelets(:,ii);
end
wavelet.first=seismic.first-refl.first+(min_shift-nsampw)*seismic.step;
wavelet.last=wavelet.first+(nsampw+max_shift-1)*seismic.step;
wavelet.step=seismic.step;
wavelet.units=seismic.units;
if (nulls || max_shift > 0) && isnan(param.null)
wavelet.null=NaN;
end
if isfield(wavelet,'headers')
wavelet.headers=[wavelet.headers;headers];
wavelet.header_info=[wavelet.header_info;header_info];
else
wavelet.headers=headers;
wavelet.header_info=header_info;
end
if isfield(seismic,'history') && isfield(refl,'history')
wavelet.history=seismic.history;
wavelet=s_history(wavelet,'append',' ');
wavelet=s_history(wavelet,'merge',refl.history);
end
ABORTED=false;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function matrix=spectral_constraints(ac,ncol)
% Function creates a matrix which imposes a spectral constraint on on the solution
% of a linear system of equations
% INPUT
% ac autocorrelation of a function with the desired spectral shape
% ac must be symmetric and have at least ncol samples;
% the number of samples is odd
% ncol number of columns/rows of the spectral constraint matrix
%
% OUTPUT
% matrix constraint matrix
% matrix=spectral_constraints(ac,ncol)
nac=length(ac);
nc=(nac+1)/2;
if mod(ncol,2)
ncolh=(ncol-1)/2;
fac=fft(ac(nc-ncolh:nc+ncolh));
fac=sqrt(sqrt(abs(fac)));
fac=1./(fac+0.01*max(fac));
tempm=fac(1:ncolh+1,ones(1,ncol)).*ftmatrix(ncolh+1,ncol);
matrix=[real(tempm);imag(tempm(2:end,:))];
else
ncolh=ncol/2-1;
fac=fft(ac(nc-ncolh:nc+ncolh),ncol);
fac=sqrt(sqrt(abs(fac)));
fac=1./(fac+0.01*max(fac));
tempm=fac(1:ncolh+2,ones(1,ncol)).*ftmatrix(ncolh+2,ncol);
matrix=[real(tempm);imag(tempm(2:end-1,:))];
end
% matrix=matrix/norm(matrix,'fro');
|
github
|
Abakumov/MLIB-master
|
write_segy_file.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/write_segy_file.m
| 20,874 |
utf_8
|
69b0175b19bd94329d6a7426a85b3501
|
function write_segy_file(seismic,filename,varargin)
% Function writes seismic data to disk in SEG-Y file format.
% If the start time is greater than zero, zeros are prepended. If it is less
% than zero, a warning message is printed.
% The only floating-point format supported is IEEE big-endian, which is one of
% the official SEG-Y standard formats.
% ProMAX recognizes the numeric code associated with this format and reads
% SeisLab-generated SEG-Y files without need for for any special settings.
%
% Written by: E. Rietsch: March 12, 2000
% Last updated: July 10, 2009: If datset has negative start time shift it to
% zero and set "lag" header tp start time.
%
% write_segy_file(seismic,filename,varargin)
% INPUT
% seismic structure; the following fields are required
% traces seismic traces
% first
% last
% step
% units
% filename Full filename; if empty (or invalid) a file-selection window will
% pop up to allow interactive file selection
% varargin Variable number of arguments. Each argument is a cell array whose
% first element is a keyword and whose other elements can be
% strings, numeric values, or other cell arrays. Possible keywords
% are:
% 'headers' header values to be written to the binary trace header in
% addition to those written by default (if available);
% Headers stored by default are:
% ds_seqno Trace sequence number within line (1-4)
% ffid Original Field record number (9-12)
% o_trace_no Trace sequence number within original field record (13-16)
% source Energy source point number (17-20)
% cdp CDP ensemble number (21-24)
% seq_cdp Trace sequence number within CDP ensemble (25-28)
% trc_type Trace ID (1=live,2=dead,3=dummy,4=time break,...) (29-30)
% offset Distance from source point to receiver group (37-40)
% depth Source depth below surface (49-52)
% sou_h2od Water depth at source (61-64)
% rec_h2od Water depth at receiver group (65-68)
% sou_x X coordinate of source (73-76)
% sou_y Y coordinate of source (77-80)
% sou_elev surface elevation at source (45-48)
% rec_x X coordinate of receiver (81-84)
% rec_y Y coordinate of receiver (85-88)
% rec_elev receiver elevation (41-44);
% lag Lag time between shot and recording start in ms (109-110)
% (the value of lag is added to the start time of the
% seismic; hence it can be used to simulate non-zero start
% time of the data)
% cdp_x X coordinate of CDP (181-184)
% cdp_y Y coordinate of CDP (185-189)
% iline_no In-line number (189-192)
% xline_no Cross-line number (193-196)
% The numbers in parentheses at the end of the line denote the location
% of the corresponding bytes in the SEG-Y trace header
%
% The cell array for the user-specified headers has the form
% {'headers',{mnem1,first,bytes},{mnem2,first,bytes},...} where
% "mnem1", "mnem2", ... denote header mnemonics (such as ILINE_NO, XLINE_NO),
% "first" denotes the first byte in the binary header,
% "bytes" denotes the number of bytes occupied by the mnemonic (2 or 4),
% Example: {'headers',{'ILINE_NO',181,4},{'XLINE_NO',185,4}}
% these headers must, of course, be present in the input data set.
% Default: no headers other than the standard SEG-Y headers listed above
% will be saved.
% 'print' printout of messages. possible values 0 or 1.
% Default: {'print',1} this means that messages are printed.
% 'ascii_header' ASCII version of the 40-line, 3200 byte EBCDIC header
% a default EBCDIC header will be inserted if this header is not supplied
% EXAMPLE
% seismic=s_data3d;
% write_segy_file(seismic,filename,{'headers',{'iline_no',189,4},{'xline_no',193,4}});
% UPDATE HISTORY
% July 23, 2006: Replaced header mnemonics "field_rec_no" by "ffid"
% and "trc_id" by "trc_type";
% write field "sort" with trace-sort code (if it
% exists) to bytes 29-30 of the binary tape
% header
% November 5. 2008: Fixed bug that caused a problem under Linux
global ABORTED
if ~istype(seismic,'seismic');
error(' The first input argument must be a seismic data set.')
end
% Set default parameters
param.format='ieee';
param.headers={};
param.ascii_header='';
param.print=1;
% Decode and assign input arguments
param=assign_input(param,varargin);
if nargin < 2
filename='';
end
% Add zeros to make start time zero
if seismic.first > 0
seismic=s_select(seismic,{'times',0,seismic.last});
elseif seismic.first < 0
display([' WARNING! Start time of seismic < 0. Seismic data will be shifted by ', ...
num2str(-seismic.first),' ms']);
if isheader(seismic,'lag');
display('Existing header "LAG" will be written to the SEG-Y file')
else
seismic=add_header(seismic,seismic.first,{'lag','ms','Lag'});
display('A header "LAG" will be written to the SEG-Y file')
end
end
% Define file format
if strcmpi(param.format,'ieee')
param.format='ieee-be';
o_format='ieee-be';
datafmt=5; % Data-format code
fidx=0;
end
% Create additional headers for output
[nsamp,ntr]=size(seismic.traces);
dt=seismic.step*1000;
seismic=ds_header(seismic,'add','gen_scale_factor',1,'','Scale factor');
seismic=ds_header(seismic,'add','number_of_samples',nsamp,'','Number of samples in this trace');
seismic=ds_header(seismic,'add','samp_int',dt,'us','Sample interval of this trace in us');
% Handle nulls in traces
if isnull(seismic)
seismic.traces(isnan(seismic.traces))=0;
end
% Handle nulls in headers
if isfield(seismic,'header_null')
if isnan(seismic.header_null)
seismic.headers(isnan(seismic.headers))=0;
end
end
% Open file
if ~isempty(filename)
fid=fopen(filename,'w',o_format);
if fid < 0
disp(['... unable to create requested file "', filename,'"']);
end
else
fid=-1;
filename=[seismic.name,'.sgy'];
end
if fid == -1
[selected_file,ierr]=get_filename4w('sgy',filename);
if ierr
return;
end
fid=fopen(selected_file,'w',o_format);
if fid < 0
disp(['... unable to create requested file "', filename,'"']);
ABORTED=true;
return
end
% [pathname,filename]=fileparts(selected_file);
% S4M.seismic_path=pathname;
end
% Write EBCDI reel header
if isempty(param.ascii_header)
ascii_header=make_header;
else
ascii_header=param.ascii_header;
[nh1,mh1]=size(ascii_header);
if nh1*mh1 ~= 3200
error('ASCII/EBCDIC header nust have 3200 bytes')
else
if nh1 > mh1
ascii_header=ascii_header';
end
end
end
% fwrite(fid,ascii2ebcdic(ascii_header),'char'); % Linux problem?
fwrite(fid,ascii2ebcdic(ascii_header),'uchar');
if param.print
disp('EBCDIC reel header written')
end;
% Write binary reel header
two_bytes=zeros(194,1);
if isfield(seismic,'job_id')
jobid=seismic.job_id;
else
jobid=1;
end
if isfield(seismic,'line_number')
lineid=seismic.line_number;
else
lineid=1;
end
if isfield(seismic,'reel_number')
reelid=seismic.reel_number;
else
reelid=1;
end
if isfield(seismic,'traces_per_record')
two_bytes(1)=seismic.traces_per_record;
else
two_bytes(1)=ntr;
end
if isfield(seismic,'aux_per_record')
two_bytes(2)=seismic.aux_per_record;
else
two_bytes(2)=0;
end
two_bytes(3:7)=[dt,dt,nsamp,nsamp,datafmt]';
if isfield(seismic,'cdp_fold')
two_bytes(8)=seismic.cdp_fold;
end
if isfield(seismic,'sort')
two_bytes(9)=seismic.sort;
end
if ~isfield(seismic,'headers')
two_bytes(22)=0;
else
idx=find(ismember(seismic.header_info(:,1), ...
{'offset','sou_x','rec_x','cdp_x','sou_y','rec_y','cdp_z'}));
if isempty(idx)
two_bytes(22)=0;
else
units=unique(seismic.header_info(idx,2));
if length(units) > 1
disp(' Units of measurement for distance:')
disp(units)
warning(warnid,'Inconsistent distance units in headers; units in SEG-Y file are set to unknown');
elseif strcmpi(char(units),'m')
two_bytes(22)=1;
elseif strcmpi(char(units),'ft')
two_bytes(22)=2;
else
warning(warnid,'Distance units in headers are neither ft nor m; units in SEG-Y file are set to unknown');
two_bytes(22)=0;
end
end
end
fwrite(fid,[jobid lineid reelid],'int32');
fwrite(fid,two_bytes,'int16');
if param.print, disp('Binary reel header written'), end;
% Write headers and traces
nh=size(seismic.header_info,1);
start=zeros(nh,1);
bytes=zeros(nh,1);
index=zeros(nh,1);
kk=1;
[start,bytes,index,kk]=set_parameters(seismic,'ds_seqno',1,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'ffid',9,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'o_trace_no',13,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'source',17,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'cdp',21,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'seq_cdp',25,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'trc_type',29,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'offset',37,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'depth',49,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'sou_h2od',61,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'rec_h2od',65,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'sou_x',73,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'sou_y',77,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'sou_elev',45,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'rec_x',81,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'rec_y',85,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'rec_elev',41,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'gen_scale_factor',69,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'gen_scale_factor',71,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'gen_scale_factor',89,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'number_of_samples',115,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'samp_int',117,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'lag',109,2,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'cdp_x',181,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'cdp_y',185,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'iline_no',189,4,start,bytes,index,kk,param.print);
[start,bytes,index,kk]=set_parameters(seismic,'xline_no',193,4,start,bytes,index,kk,param.print);
% Add user-specified headers
for ii=1:length(param.headers)
if length(param.headers{ii}) ~= 3
disp([char(13),' Error in specification of headers to be written to file: ', ...
cell2str(param.headers{ii}(1))])
error(' Probably insufficient number of parameters')
end
[start,bytes,index,kk]=set_parameters(seismic,param.headers{ii}{1}, ...
param.headers{ii}{2},param.headers{ii}{3},start,bytes,index,kk,param.print);
end
start(kk:end)=[]; % Remove unneeded, previously reserved array elements
bytes(kk:end)=[]; % Remove unneeded, previously reserved array elements
index(kk:end)=[]; % Remove unneeded, previously reserved array elements
for ii=1:ntr
write_trace(fid,seismic.traces(:,ii),seismic.headers(index,ii),start,bytes,fidx);
end
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [start,bytes,index,kk]=set_parameters(seismic,mnem,sb,nb,start,bytes,index,kk,iprint)
% Function sets values start(index),bytes(index) to the starting location
% of the header mnemonic and increments index
% seismic seismic structure
% mnem header mnemonic whose starting location in the four-byte representation
% (nb=4) or the two-byte representation (nb=2) needs to be set
% sb starting byte
% nb number of bytes
% start array where the index for the two-byte and four-byte header is stored
% bytes array where the number of bytes required by this header is stored
% index index into row of header which contains the header values of
% the mnemonic mnem
% kk next location in arrays start and bytes
% OUTPUT
% start updated start array
% bytes updated bytes array
% index updated index
% kk input index incremented by 1
% iprint print-out control parameter: 1 printout, 0 no printout
global S4M
if S4M.case_sensitive
idx=find(ismember(seismic.header_info(:,1),mnem));
else
idx=find(ismember(lower(seismic.header_info(:,1)),mnem));
end
if isempty(idx)
if iprint, disp(['Header "',mnem,'" not found in dataset and assumed to be zero']), end
return,
end
index(kk)=idx;
bytes(kk)=nb;
if nb == 2
temp=fix((sb-1)/2);
if temp*2 ~= sb-1
error(['Starting byte location for header ',mnem,'(',num2str(sb),' is not odd'])
else
start(kk)=temp+1;
end
else
temp=fix((sb-1)/4);
if temp*4 ~= sb-1
error(['Starting byte location for header ',mnem,'(',num2str(sb),' is not 1 plus a multiple of 4'])
else
start(kk)=temp+1;
end
end
kk=kk+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function write_trace(fid,trace,headers,start,bytes,fidx)
% Function writes one seismic trace together with its header to file
% fid file identification number
% trace seismic trace
% headers header values associated with the trace
% start starting four-byte or two-byte index in the 240-byte header
% for each header value
% bytes number of bytes for each header value
% fidx format index;
% fidx=0; no conversion
% fidx=1; conversion to IMB floating point format
% nsamp=length(trace);
nh=length(headers);
fbytes=zeros(60,1);
tbytes=zeros(120,1);
for ii=1:nh
if bytes(ii) == 4
fbytes(start(ii))=headers(ii);
else
tbytes(start(ii))=headers(ii);
end
end
fwrite(fid,fbytes( 1: 7),'int32');
fwrite(fid,tbytes(15:18),'int16');
fwrite(fid,fbytes(10:17),'int32');
fwrite(fid,tbytes(35:36),'int16');
fwrite(fid,fbytes(19:22),'int32');
fwrite(fid,tbytes(45:90),'int16');
fwrite(fid,fbytes(46:60),'int32');
% Write trace
if fidx == 0
fwrite(fid,trace,'float32');
else
error('IBM floating point not yet implemented')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ascii_header=make_header
% Function creates ASCII version of standard EBCIC header of SEG-Y format
ascii_header=char(...
'C 1 CLIENT COMPANY CREW NO', ...
'C 2 LINE AREA MAP ID ', ...
'C 3 REEL NO DAY-START OF REEL YEAR OBSERVER', ...
'C 4 INSTRUMENT: MFG MODEL SERIAL NO', ...
'C 5 DATA TRACES/RECORD AUXILIARY TRACES/RECORD CDP FOLD', ...
'C 6 SAMPLE INTERNAL SAMPLES/TRACE BITS/IN BYTES/SAMPLE', ...
'C 7 RECORDING FORMAT FORMAT THIS REEL MEASUREMENT SYSTEM', ...
'C 8 SAMPLE CODE: FLOATING PT FIXED PT FIXED PT-GAIN CORRELATED ', ...
'C 9 GAIN TYPE: FIXED BINARY FLOATING POINT OTHER ', ...
'C10 FILTERS: ALIAS HZ NOTCH HZ BAND - HZ SLOPE - DB/OCT ', ...
'C11 SOURCE: TYPE NUMBER/POINT POINT INTERVAL', ...
'C12 PATTERN: LENGTH WIDTH', ...
'C13 SWEEP: START HZ END HZ LENGTH MS CHANNEL NO TYPE', ...
'C14 TAPER: START LENGTH MS END LENGTH MS TYPE', ...
'C15 SPREAD: OFFSET MAX DISTANCE GROUP INTERVAL', ...
'C16 GEOPHONES: PER GROUP SPACING FREQUENCY MFG MODEL', ...
'C17 PATTERN: LENGTH WIDTH', ...
'C18 TRACES SORTED BY: RECORD CDP OTHER', ...
'C19 AMPLITUDE RECOVEY: NONE SPHERICAL DIV AGC OTHER', ...
'C20 MAP PROJECTION ZONE ID COORDINATE UNITS', ...
'C21 PROCESSING:', ...
'C22 PROCESSING:', ...
'C23 ', ...
'C24 ', ...
'C25 ', ...
'C26 ', ...
'C27 ', ...
'C28 ', ...
'C29 ', ...
'C30 ', ...
'C31 ', ...
'C32 ', ...
'C33 ', ...
'C34 ', ...
'C35 ', ...
'C36 ', ...
'C37 ', ...
'C38 ', ...
'C39 ', ...
'C40 END EBCDIC')';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ebcdic=ascii2ebcdic(ascii)
% Function converts ASCII string to EBCDIC
% see http://www.room42.com/store/computer_center/code_tables.shtml
% Date Feb. 20, 2000; written by E. Rietsch
% INPUT
% ascii ASCII string
% OUTPUT
% ebcdic EBCDIC string
% ebcdic=ascii2ebcdic(ascii)
pointer = ...
[0 16 64 240 124 215 125 151 75 75 75 75 75 75 75 75
1 17 90 241 193 216 129 152 75 75 75 75 75 75 75 75
2 18 127 242 194 217 130 153 75 75 75 75 75 75 75 75
3 19 123 243 195 226 131 162 75 75 75 75 75 75 75 75
4 20 91 244 196 227 132 163 75 75 75 75 75 75 75 75
5 21 108 245 197 228 133 164 75 75 75 75 75 75 75 75
6 22 80 246 198 229 134 165 75 75 75 75 75 75 75 75
7 23 125 247 199 230 135 166 75 75 75 75 75 75 75 75
8 24 77 248 200 231 136 167 75 75 75 75 75 75 75 75
9 25 93 249 201 232 137 168 75 75 75 75 75 75 75 75
10 26 92 122 209 233 145 169 75 75 75 75 75 75 75 75
11 27 78 94 210 173 146 192 75 75 75 75 75 75 75 75
12 28 107 76 211 224 147 106 75 75 75 75 75 75 75 75
13 29 96 126 212 189 148 208 75 75 75 75 75 75 75 75
14 30 75 110 213 95 149 161 75 75 75 75 75 75 75 75
15 31 97 111 214 109 150 75 75 75 75 75 75 75 75 75];
pointer=pointer(:);
ebcdic=pointer(ascii+1);
|
github
|
Abakumov/MLIB-master
|
s_resample.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_resample.m
| 7,673 |
utf_8
|
48867adae303fed7f8360b744e370d69
|
function seismic=s_resample(seismic,sample_interval,varargin)
% Function resamples seismic data to new sample interval. If the new sample
% interval is greater than the old sample interval and interpolation is done
% in the time domain an Ormsby filter with corner frequencies
% 0, 0, 0.8*fnyquist, fnyquist
% is applied to the data prior to resampling.
% "fnyquist" is the Nyquist frequency associated with the new sample interval.
%
% Written by: E. Rietsch: April 14, 2000
% Last update: January 1, 2007: Assure that the precision of the input datset
% is the same as the output dataset.
%
% seismic=s_resample(seismic,sample_interval,varargin)
% INPUT
% seismic seismic structure
% sample_interval new sample interval (can be larger or smaller than seismic.step);
% varargin one or more cell arrays; the first element of each cell array
% is a keyword, the other elements are parameters.
% Presently, keywords are:
% 'option' parameter which specifies the kind of interpolation.
% Possible values are:
% 'standard' Straight forward interpolation. Frequency-domain anti-alias filter.
% if sample_interval > seismic.step.
% 'smooth' Straightforward interpolation. Time-domain smoothing if
% sample_interval > seismic.step
% 'wavelet' Interpolation intended for wavelets. This interpolation
% includes the sample prior to the first and the one after the
% last in the interpolation, assuming they are zero.
% Default: {'option','standard'}
% 'domain' parameter specifies it interpolation is to be done in the frequency
% domain ('frequency') or in the time domain ('time').
% Default: {'domain','time')
% 'filter' parameter specifies if band-pass filter is to be applied
% (to the input data if seismic.step < sample_interval (anti-alias)
% to the output data if seismic.step > sample_interval)
% Default: {'filter','yes'}
% OUTPUT
% seismic seismic structure after resampling
%
% EXAMPLE
% wavelet4=s_create_wavelet;
% wavelet4.name='4-ms wavelet';
% wavelet2=s_resample(wavelet4,2);
% wavelet2.name='2-ms wavelet';
% s_compare(wavelet4,wavelet2,{'interpol','linear'},{'times',-40,40})
global S4M
%% Set default values for input arguments
param.domain='time';
param.filter='yes';
param.option='standard';
% Replace defaults by actual input arguments
param=assign_input(param,varargin);
%% Handle case where "seismic" is a dataset vector
nseismic=length(seismic);
if nseismic > 1
for ii=1:nseismic
seismic(ii)=s_resample(seismic(ii),sample_interval,{'domain',param.domain}, ...
{'filter',param.filter},{'option',param.option});
end
return
end
%% Do nothing if sample interval is not changed
if seismic.step == sample_interval
return
end
% Change the sample interval if seismic is a spike (start and end time are the same)
if seismic.first == seismic.last
if strcmp(class(seismic.traces),'single')
seismic.step=single(sample_interval);
else
seismic.step=double(sample_interval);
end
return
end
ntr=size(seismic.traces,2);
% Remove trace nulls
seismic=s_rm_trace_nulls(seismic);
first=floor(seismic.first/sample_interval)*sample_interval;
last=ceil(seismic.last/sample_interval)*sample_interval;
seismic=s_select(seismic,{'times',first,last});
new_times=(first:sample_interval:seismic.last)';
nsamp=length(new_times);
%%
switch param.option
case 'standard'
if isnull(seismic)
error(' Handling of null values not yet implemented')
end
if seismic.step > sample_interval
seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
param.domain,param.filter);
else
seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
param.domain,param.filter);
end
case 'smooth'
if isnull(seismic)
error(' Handling of null values not yet implemented')
end
if seismic.step > sample_interval
% seismic.traces=interp1(seismic.first:seismic.step:seismic.last,seismic.traces,new_times,param.domain);
seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
param.domain,param.filter);
else
ratio=sample_interval/seismic.step;
times=(seismic.first:seismic.step:seismic.last)';
for ii=1:ntr
temp=seismic.traces(:,ii);
idx=find(~isnan(temp));
temp(idx)=mysmooth(temp(idx),ratio);
seismic.traces(1:nsamp,ii)=interpolate(times,temp,new_times, ...
param.domain,param.filter);
end
seismic.traces=seismic.traces(1:nsamp,:);
end
case 'wavelet'
if seismic.step > sample_interval
seismic.traces=interpolate((seismic.first-seismic.step:seismic.step:seismic.last+seismic.step)', ...
[zeros(1,ntr);seismic.traces;zeros(1,ntr)],new_times,param.domain,param.filter);
else
fnyquist=500/sample_interval;
temp=ormsby([zeros(1,ntr);seismic.traces;zeros(1,ntr)],seismic.step,0,0,0.8*fnyquist,fnyquist);
seismic.traces=interpolate((seismic.first-seismic.step:seismic.step:seismic.last+seismic.step)', ...
temp,new_times,param.domain,param.filter);
if any(isnan(seismic.traces))
seismic.null=NaN;
temp=S4M.history;
S4M.history=false; % Make no entry in "history" field
seismic=s_rm_trace_nulls(seismic);
S4M.history=temp;
end
end
otherwise
error([' Unknown RESAMPLE option "',param.option,'"'])
end % End of switch block
seismic.first=first;
seismic.last=new_times(end);
seismic.step=sample_interval;
% Compatibility test (for frequency-domain interpolation)
if strcmpi(param.domain,'frequency')
if size(seismic.traces,1) ~= nsamp
try
seismic.traces=seismic.traces(1:nsamp,:);
catch
keyboard
end
end
end
% Check for NaNs
if any(isnan(seismic.traces(:)))
seismic.null=NaN;
end
% Append history field
if isfield(seismic,'history') && S4M.history
htext=['to ',num2str(sample_interval),' ',seismic.units, ...
' (',param.option,', ',param.domain,' domain)'];
seismic=s_history(seismic,'append',htext);
end
% Assure that the precision orf the output dataset is that of the input data set
if strcmp(class(seismic.traces),'single')
seismic=single(seismic);
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ynew=interpolate(xold,yold,xnew,type,filter)
% Function performs interpolation in time or frequency domain,
% assumes "xold" and "xnew" are uniform
% "type" is either 'time' or 'frequency';
% "filter" is either 'yes' or 'no' (only used if "type" is 'time')
dxold=mean(diff(xold));
dxnew=mean(diff(xnew));
if strcmpi(type,'time')
if (dxold < dxnew) && strcmpi(filter,'yes')
fnyquist=500/dxnew;
yold=ormsby(yold,dxold,0,0,0.8*fnyquist,fnyquist);
end
ynew=interp1(xold,yold,xnew,'*cubic');
if (dxold > dxnew) && strcmpi(filter,'yes')
fnyquist=500/dxold;
ynew=ormsby(ynew,dxold,0,0,fnyquist,1.2*fnyquist);
end
elseif strcmpi(type,'frequency')
if dxnew > dxold
[nsamp,ntr]=size(yold);
ratio=round(dxnew/dxold);
lold=ratio*length(xnew);
if lold > nsamp
yold=[yold;zeros(lold-length(xold),ntr)];
end
end
ynew=interpf(yold,dxold,dxnew);
else
error([' Unknown domain for resampling: ',type'])
end
|
github
|
Abakumov/MLIB-master
|
s_append.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_append.m
| 10,541 |
utf_8
|
e94f42634b346c9d4d692ffd41fcd27f
|
function seisout=s_append(seis1,seis2,varargin)
% Function combines two seismic data sets. On output the traces of the
% first input data set are followed by the traces of the second data set.
% The two data sets must satisfy the following two conditions:
% seis1.step=seis2.step;
% (seis1.first-seis2.first)/seis1.step is integer
% Unless keyword 'times' is {'min','max'} and keyword 'headers' is 'i' (intersect)
% some seismic samples and/or header values of "seisout" may not be defined by the
% input data.
% The precision of the output dataset is single-precision if at least one
% of the input datasets is single-precision.
%
% See also: s_select
%
% Written by: E. Rietsch: January 28, 2000
% Last updated: January 1, 2007: Ascertain that the precision of the output
% dataset is single-precision if one of the
% input datasets is single-precision
%
% seisout=s_append(seis1,seis2,varargin)
%
% INPUT
% seis1 seismic structure or empty; if it is empty the second input
% argument (second seismic dataset) is output (any other arguments
% are ignored). This is intended to make it more convenient to
% build a multi-trace dataset in a loop.
% seis2 seismic structure; can also be empty.
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'header_null' Null value to use for non-existing header values in the output data set
% 'null' Null value to use for non-existing trace samples in the output data set
% Only used if there are no null values in the input data
% 'times' This two-cell string defines what should be done if the two data sets have
% differing first-sample and/or last-sample times
% times{1} = 'min': seisout.start=min([seis1.first,seis2.first]);
% times{1} = 'max': seisout.start=max([seis1.first,seis2.first]);
% times{2} = 'min': seisout.start=min([seis1.last,seis2.last]);
% times{2} = 'max': seisout.start=max([seis1.last,seis2.last]);
% Default: {'times','min','max'}
% 'headers' This string parameter defines what should be done if the two data sets have
% different headers
% {'headers','u'} : Use the union of the headers (default)
% {'headers','i'} ; Use the intersection of the headers (the headers they have in common)
%
% OUTPUT
% seisout Combination of the two datasets
if ~istype(seis1,'seismic')
if isempty(seis1)
seisout=seis2;
return
else
error('First input argument must be a seismic dataset or empty.')
end
end
if ~istype(seis2,'seismic')
error('Second input argument must be a seismic dataset.')
end
% Set defaults parameters
param.header_null=NaN;
param.null=NaN;
param.times={'min','max'};
param.headers='u';
% Decode and assign input arguments
param=assign_input(param,varargin);
if isnull(seis1) || isnull(seis2)
param.null=NaN;
end
ttype=param.times;
htype=param.headers;
% Check compatibility of data sets
if ~strcmpi(seis1.units,seis2.units)
error(['Input data sets have different depth/time/frequncy units ("', ...
seis1.units,'" vs. "',seis2.units,'")'])
end
if seis1.step ~= seis2.step
error([' Input data sets have different sample intervals: ', ...
num2str(seis1.step),' ',seis1.units,' vs. ', num2str(seis2.step), ...
' ',seis2.units])
end
seisout.type=seis1.type;
seisout.tag=seis1.tag;
seisout.name='';
step=seis1.step;
seisout.step=step;
seisout.units=seis1.units;
null_value=param.null;
header_null_value=param.header_null;
fdiff=(seis1.first-seis2.first)/seis1.step;
ldiff=(seis1.last-seis2.last)/seis1.step;
[nsamp1,ntr1]=size(seis1.traces);
[nsamp2,ntr2]=size(seis2.traces);
if fdiff == 0 && ldiff == 0 % Simple case where both data sets have the same start and end times
seisout.traces=[seis1.traces,seis2.traces];
seisout.first=seis1.first;
seisout.last=seis1.last;
else
if strcmpi(ttype(1),'max')
first=max([seis1.first,seis2.first]);
elseif strcmpi(ttype(1),'min')
first=min([seis1.first,seis2.first]);
else
error(['Unknown input parameter ttype(1) (',ttype(1),')'])
end
if strcmpi(ttype(2),'max')
last=max([seis1.last,seis2.last]);
elseif strcmpi(ttype(2),'min')
last=min([seis1.last,seis2.last]);
else
error(['Unknown input parameter ttype(1) (',ttype(1),')'])
end
seisout.first=first;
seisout.last=last;
nsamp=round((last-first)/step)+1;
seisout.traces=null_value*zeros(nsamp,ntr1+ntr2);
ia=round((first-seis1.first)/step);
if ia >= 0
seisout.traces(1:min([nsamp1-ia,nsamp]),1:ntr1)=seis1.traces(ia+1:min([nsamp1,nsamp+ia]),:);
else
seisout.traces(1-ia:min([nsamp1-ia,nsamp]),1:ntr1)=seis1.traces(1:min([nsamp1,nsamp+ia]),:);
end
ia=round((first-seis2.first)/step);
if ia >= 0
seisout.traces(1:min([nsamp2-ia,nsamp]),ntr1+1:ntr1+ntr2)= ...
seis2.traces(ia+1:min([nsamp2,nsamp+ia]),:);
else
seisout.traces(1-ia:min([nsamp2-ia,nsamp]),ntr1+1:ntr1+ntr2)= ...
seis2.traces(1:min([nsamp2,nsamp+ia]),:);
end
end
% Set headers of output data set
if isfield(seis1,'headers') && isfield(seis2,'headers') % Both data sets have headers
seisout=merge_headers(seisout,seis1,seis2,htype,header_null_value);
elseif isfield(seis1,'headers') % Only the first data set has headers
seisout.header_info=seis1.header_info;
if header_null_value == 0
seisout.headers=[seis1.headers,zeros(size(seis1.headers,1),ntr2)];
else
seisout.headers=[seis1.headers,header_null_value*zeros(size(seis1.headers,1),ntr2)];
if isnan(header_null_value)
seisout.header_null=NaN;
end
end
elseif isfield(seis2,'headers') % Only the second data set has headers
seisout.header_info=seis2.header_info;
if header_null_value == 0
seisout.headers=[zeros(size(seis2.headers,1),ntr1),seis2.headers];
else
seisout.headers=[header_null_value*zeros(size(seis2.headers,1),ntr1),seis2.headers];
if isnan(header_null_value)
seisout.header_null=NaN;
end
end
else % Neither input data set has headers
% Do nothing
end
% Copy common fields that have not yet been set and that have the same value
% in both input data sets (string or number, no arrays)
set_fields={'traces','headers','header_info','first','last','step', ...
'units','history'};
fields1=fieldnames(seis1);
fields2=fieldnames(seis2);
fields=intersect(fields1,fields2);
fields=fields(~ismember(fields,set_fields));
for ii=1:length(fields);
fval1=seis1.(fields{ii});
fval2=seis2.(fields{ii});
% fval1=getfield(seis1,fields{ii});
% fval2=getfield(seis2,fields{ii});
try
if strcmpi(fval1,fval2)
% seisout=setfield(seisout,fields{ii},fval1);
seisout.(fields{ii})=fval1;
end
catch
end
try
if fval1 == fval2
seisout.(fields{ii})=fval1;
% seisout=setfield(seisout,fields{ii},fval1);
end
catch
end
end
%{
% Set null field, if necessary
% if isfield(seis1,'null') && isfield(seis2,'null')
if ~isnull(seis1) && ~isnull(seis2)
if seis1.null == seis2.null
param.null=seis1.null;
end
end
% end
if any(isnan(seisout.traces(:)))
if ~isfield(seisout,'null')
seisout.null=param.null;
end
else
if isfield(seisout,'null')
seisout=rmfield(seisout,'null');
end
end
%}
if any(isnan(seisout.traces(:)))
seisout.null=NaN;
else
seisout.null=[];
end
% Append history field
if isfield(seis1,'history') && isfield(seis2,'history')
seisout.history=seis1.history;
seisout=s_history(seisout,'append',['[',ttype{1},' ',ttype{2},'], ',htype]);
seisout=s_history(seisout,'merge',seis2.history);
end
if strcmp(class(seis1.traces),'single') || strcmp(class(seis2.traces),'single')
seisout=single(seisout);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seisout=merge_headers(seisout,seis1,seis2,htype,header_null_value)
% Function merges headers of the two seismic input data sets
% INPUT
% seisout seismic output data set with fields that have already been set
% seis1, seis2 seismic input data sets
% htype This string parameter defines what should be done if the two data sets have
% different headers
% htype='u': Use the union of the headers (default)
% htype='i'; Use the intersection of the headers (the headers they have in common)
% header_null_value Null value for missing header values
% OUTPUT
% seisout seismic output data set
% seisout=merge_headers(seis1,seis2,htype)
ntr1=size(seis1.headers,2);
ntr2=size(seis2.headers,2);
headers1=seis1.header_info(:,1);
headers2=seis2.header_info(:,1);
iheaders=intersect(headers1,headers2);
hidx1=find(ismember(headers1,iheaders));
hi1=seis1.header_info(hidx1,:);
hidx2=find(ismember(headers2,iheaders));
hi2=seis2.header_info(hidx2,:);
% Check that units of measurement are the same
lh1=length({hi1{:,2}});
if lh1 ~= sum(ismember({hi1{:,2}}',{hi2{:,2}}))
spaces=blanks(lh1)';
commas=char(44*ones(lh1,1));
units_of_measurement=[char({hi1{:,1}}),spaces,char({hi1{:,2}}),commas, ...
spaces,char({hi2{:,2}}),spaces,char({hi2{:,1}})];
disp(units_of_measurement)
error('Units of measurement in common headers of the two input data sets differ')
end
seisout.header_info=hi1;
seisout.headers=[seis1.headers(hidx1,:),seis2.headers(hidx2,:)];
if strcmpi(htype,'u')
if isempty(iheaders)
idx1=1:length(headers1(:,1));
idx2=1:length(headers2(:,1));
else
[dummy,idx1]=setdiff(headers1(:,1),iheaders(:,1)); %#ok Only second output argument required
[dummy,idx2]=setdiff(headers2(:,1),iheaders(:,1)); %#ok Only second output argument required
end
if ~isempty(idx1) || ~isempty(idx2)
seisout.header_null=header_null_value;
end
seisout.header_info=[seisout.header_info; ...
seis1.header_info(idx1,:);seis2.header_info(idx2,:)];
seisout.headers=[seisout.headers;
seis1.headers(idx1,:),header_null_value*zeros(length(idx1),ntr2);
header_null_value*zeros(length(idx2),ntr1),seis2.headers(idx2,:)];
elseif ~strcmpi(htype,'i')
error(['Unknown parameter htype (',htype,')'])
end
|
github
|
Abakumov/MLIB-master
|
l_unit_conversion.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_unit_conversion.m
| 9,388 |
utf_8
|
06ff65819756cdfd19ceda825126499a
|
function wlog=l_unit_conversion(wlog,varargin)
% Function converts units of measurements of curves and parameters in
% a log structure.
%
% DEPRECATED: Use "ds_unit_conversion" instead.
%
% Written by: E. Rietsch: January 10, 2001
% Last updated: April 11, 2007: Bug fix
%
% wlog=l_unit_conversion(wlog,varargin)
% INPUT
% wlog log structure
% varargin cell arrays with at least two elements. The first element is a string representing
% an existing unit of measurement, the second is the desired unit of measurement.
% If additional elements are given they represent curve mnemonics which should be
% changed. If no curves are found that have these units of measurements and/or
% these mnemonics, an alert is printed (see keyword 'alert').
% Possible pairs of units of measurement are (in alphabetical order) and
% vice versa:
% {'fraction','%'}
% {'g/cm3','ppg'}, {'g/cm3','kg/m3'}
% {'m','ft'} (this also converts '1/m' to '1/ft')
% {'m/s','ft/s')
% {'us/ft','us/m'}
% {'s','ms'}
% It is not an error if the two units are the same (e.g {'m','m'})
%
% 'alert' Print an alert. Possible values are 0 (false) and 1 (true).
% This keyword has an effect only on those conversions following it. Hence,
% it should be the first argument after the log structure
% Default: {'alert',1}
% OUTPUT
% wlog log structure with new units of measurement
%
% EXAMPLES
% % Change 'ft' to 'm' and '%' to 'fraction'
% wlog=l_data;
% wlog=l_unit_conversion(wlog,{'ft','m'},{'%','fraction'});
% l_curve(wlog)
%
% % Change 'ft/s' to 'm/s' (but only for Vs)
% wlog=l_unit_conversion(wlog,{'ft/s','m/s','Vs'});
% l_curve(wlog)
global S4M
alert('DEPRECATED: Use "ds_unit_conversion" instead.')
ier=0;
for kk=1:length(wlog)
for ll=1:length(varargin)
units=varargin{ll};
if strcmpi(units{1},'alert')
S4M.alert=units{2};
end
if ~strcmpi(units{1},units{2}) && ~strcmpi(units{1},'alert') % Perform conversion
% only if the two units are different
if size(units) < 2
disp(units)
error(' Input arguments: old and new units must be represented as a two-element cell')
end
switch units{1}
%===========================================================
case 'fraction'
if strcmp(units{2},'%') % fraction ==> %
[wlog,ier]=unit_conversion(wlog,units,'new=old*100');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'ft'
if strcmp(units{2},'m') % ft ==> m
wlog=unit_conversion(wlog,units,'new=old*0.3048');
[wlog,ier]=unit_conversion(wlog,{'1/ft','1/m'},'new=old/0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'g/cm3'
if strcmp(units{2},'ppg') % g/cm3 ==> ppg
[wlog,ier]=unit_conversion(wlog,units,'new=old*8.35');
elseif strcmp(units{2},'kg/m3') % g/cm3 ==> kg/m3
[wlog,ier]=unit_conversion(wlog,units,'new=old*1000');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'kg/m3'
if strcmp(units{2},'ppg') % kg/m3 ==> ppg
[wlog,ier]=unit_conversion(wlog,units,'new=old*0.00835');
elseif strcmp(units{2},'g/cm3') % kg/m3 ==> g/cm3
[wlog,ier]=unit_conversion(wlog,units,'new=old/1000');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'm'
if strcmp(units{2},'ft') % m ==> ft
wlog=unit_conversion(wlog,units,'new=old/0.3048');
[wlog,ier]=unit_conversion(wlog,{'1/m','1/ft'},'new=old*0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case '%'
if strcmp(units{2},'fraction') % % ==> fraction
[wlog,ier]=unit_conversion(wlog,units,'new=old/100');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'us/ft'
if strcmp(units{2},'us/m') % us/ft ==> us/m
[wlog,ier]=unit_conversion(wlog,units,'new=old/0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'us/m'
if strcmp(units{2},'us/ft') % us/m ==> us/ft
[wlog,ier]=unit_conversion(wlog,units,'new=old*0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'ft/s'
if strcmp(units{2},'m/s') % ft/s ==> m/s
[wlog,ier]=unit_conversion(wlog,units,'new=old*0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'm/s'
if strcmp(units{2},'ft/s') % m/s ==> ft/s
[wlog,ier]=unit_conversion(wlog,units,'new=old/0.3048');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 'ms'
if strcmp(units{2},'s') % ms ==> s
[wlog,ier]=unit_conversion(wlog,units,'new=old/1000');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
case 's'
if strcmp(units{2},'ms') % s ==> ms
[wlog,ier]=unit_conversion(wlog,units,'new=old*1000');
else
error([' No conversion option from "',units{1},'" to "',units{2},'" found'])
end
%===========================================================
otherwise
error([' No conversion option from "',units{1},'" available'])
end % End of "switch' block
%===========================================================
end % End of if statement checking if the two units are the same
end
end
if ier > 0
% Only insignificant warnings
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [wlog,ier]=unit_conversion(wlog,units,expression)
% Function converts values of one or more curves with the same units of
% measurement using the relationship in input argument "expression"
% INPUT
% wlog log structure
% units cell array with at least two elements (strings) representing original and
% new units of measurement; additional elements (if given) represent curve
% mnemonics
% expression matlab expression of the form 'new=function(old)'
% Examples: 'new=old*0.3048'
% 'new=10*log(old)'
% OUTPUT
% wlog log structure with the updated curve(s)
% ier error code: no error ==> ier = 0
% error ==> ier = 1
% error occur if no curve with specified units of measurement are found or
% if curve mnemonics are specified ("units" has more than 2 elements)
% but are not fund in wlog
% An ALERT message is printed if ier == 1 and global variable S4M.alert == 1
global S4M
ier=0;
% Check log curves
index=find(ismember(wlog.curve_info(:,2),units{1}));
if isempty(index)
if S4M.alert
disp([' Alert from "l_unit_conversion": no curve with units "',units{1},'" found'])
end
ier=1;
elseif length(units) > 2 % Are there specific curve mnemonics for which to convert units
idx=find(ismember(lower(wlog.curve_info(index,1)),lower(units(3:end))));
if isempty(idx)
if S4M.alert
disp([' Alert from "l_unit_conversion": no specified curve with units "',units{1},'" found'])
disp([' curves with these units: ', ...
cell2str(wlog.curve_info(index,1),', ')])
end
ier=1;
else
index=index(idx);
end
end
if ier == 0
old=wlog.curves(:,index); %#ok "old is used in "eval"
eval([expression,';']);
wlog.curves(:,index)=new;
alert([' Log curve(s) ',cell2str(wlog.curve_info(index,1),', '),' changed to units "',units{2},'"'])
wlog.curve_info(index,2)=units(2);
end
% Check parameters for units that need to be converted
if isfield(wlog,'parameter_info')
params=wlog.parameter_info(:,1);
for ii=1:length(params)
temp=param_info(wlog,params{ii});
if strcmp(temp{2},units{1})
% old=getfield(wlog,params{ii});
old=wlog.(params{ii}); %#ok "old is used in "eval"
eval([expression,';']);
wlog=ds_add_parameter(wlog,new,{params{ii},units{2},temp{3}});
alert([' Parameter "',params{ii},'" changed'])
end
end
end
% Handle change in the units for depth
if ~isempty(index) && index(1) == 1
wlog.first=wlog.curves(1,1);
wlog.last=wlog.curves(end,1);
old=wlog.step; %#ok "old is used in "eval"
eval([expression,';']);
wlog.step=new;
wlog.units=units{2};
end
|
github
|
Abakumov/MLIB-master
|
s_stack.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_stack.m
| 7,570 |
utf_8
|
11e9433cb1c39f519396e2a281b8058b
|
function [stack,aux]=s_stack(seismic,varargin)
% Function stacks seismic traces (sums the traces of gathers and divides
% the sum by the number of valid samples added; normalization).
% It a header mnemonic is specified, traces with the same value of
% that header (gathers) are stacked; otherwise all traces of the input
% data set are stacked. Also, a header can be specified
% which contains weights that are to be applied to the traces prior to
% stacking. In this case the stacked traces are not divided by the
% number of traces stacked
%
% Written by: E. Rietsch: June 20, 2001
% Last updated: September 3, 2006: Allow scaling the traces prior to stacking
%
% [stack,aux]=s_stack(seismic,varargin)
% INPUT
% seismic seismic structure
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'header' header mnemonic. Traces with the same header mnemonic
% are stacked.
% Default: {'header',''}; i.e. no header mnemonic selected:
% all traces of "seismic" are stacked.
% 'weight' mnemonic of header which contains weights to be
% applied to traces prior to stacking
% Default: {'weight',[]} i.e. all traces have equal weight 1
% OUTPUT
% stack seismic structure with the stacked data
% headers are averaged as well
% aux structure with additional data
% 'multiplicity' seismic structure with the same number of traces as "stack".
% Each trace sample represents the number of samples of "seismic"
% that were used to form the corresponding sample of "stack".
%
% EXAMPLE
% seismic=s_data;
% seismic.traces(20:30,1:3)=NaN;
% seismic.null=NaN;
% seismic=ds_header(seismic,'add_ne', ...
% 'weight',1:size(seismic.traces,2),'n/a','Weights');
%
% [stack,aux]=s_stack(seismic);
% s_wplot(aux.multiplicity,{'interpol','linear'},{'title','Multiplicity'})
%
% [wstack,aux]=s_stack(seismic,{'weight','weight'})
% s_wplot(aux.multiplicity,{'interpol','linear'},{'title','Weighted multiplicity'})
% Set defaults for input parameters
param.header='';
param.weight='';
% Decode and assign input arguments
param=assign_input(param,varargin);
if isnull(seismic)
no_null=false;
else
no_null=true;
end
if ~isempty(param.weight)
weights=s_gh(seismic,param.weight).';
end
% Case of no header specified (all traces are stacked together)
if isempty(param.header)
htext='Stack';
if isfield(seismic,'headers')
stack.headers=mean(seismic.headers,2);
end
if nargout == 1 % Multiplicity not requested
if isempty(param.weight)
[stack.traces,no_null]=normal_stack(seismic.traces,no_null);
else
[stack.traces,no_null]=weighted_stack(seismic.traces,no_null,weights);
end
else % Multiplicity requested
if isempty(param.weight)
[stack.traces,no_null,multi.traces]=normal_stack(seismic.traces,no_null);
else
[stack.traces,no_null,multi.traces]=weighted_stack(seismic.traces,no_null,weights);
end
% Copy rest of fields
if isfield(stack,'headers')
multi.headers=stack.headers;
end
multi=copy_fields(seismic,multi);
end
stack=copy_fields(seismic,stack);
if ~no_null
stack.null=NaN;
end
else % Header specified
htext='Stack';
no_null_out=1;
header=s_gh(seismic,param.header);
uh=unique(header);
ntr=length(uh);
stack.traces=zeros(size(seismic.traces,1),ntr);
stack.headers=zeros(size(seismic.headers,1),ntr);
if nargout == 1 % Auxiliary data (second output dataset) not requested
for ii=1:ntr
index=find(ismember(header,uh(ii)));
if isempty(param.weight)
[stack.traces(:,ii),temp]=normal_stack(seismic.traces(:,index),no_null);
else
[stack.traces(:,ii),temp]=weighted_stack(seismic.traces(:,index),no_null,weights);
end
stack.headers(:,ii)=mean(seismic.headers(:,index),2);
no_null_out=no_null_out*temp;
end
else % Auxiliary data requested
multi.curves=zeros(size(stack.traces));
for ii=1:ntr
index=find(ismember(header,uh(ii)));
if isempty(param.weight)
[stack.traces(:,ii),temp,multi.traces(:,ii)]= ...
normal_stack(seismic.traces(:,index),no_null);
else
[stack.traces(:,ii),temp,multi.traces(:,ii)]= ...
weighted_stack(seismic.traces(:,index),no_null,weights(index));
end
stack.headers(:,ii)=mean(seismic.headers(:,index),2);
no_null_out=no_null_out*temp;
end
multi.headers=stack.headers;
multi=copy_fields(seismic,multi);
end
stack=copy_fields(seismic,stack);
if ~no_null_out
stack.null=NaN;
end
end
% Append history field
if isfield(seismic,'history')
stack=s_history(stack,'append',htext);
end
if nargout > 1
aux.multiplicity=s_history(multi,'append','Multiplicity');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [stack,no_null,multipl]=normal_stack(traces,no_null)
% Function computes mean of elements of array traces along rows
% INPUT
% traces matrix of seismic traces to be stacked
% no_null logical variable (true (1) if "traces" contains no nulls)
% OUTPUT
% stack vector of stacked traces
% no_null logical variable (true (1) if "traces" contains no nulls)
% multipl multiplicity (number of samples averaged); unless NaNs are
% present, this is the number of columns of "traces".
[nsamp,ntr]=size(traces);
stack=mean(traces,2);
if nargout > 2
multipl=ntr*ones(nsamp,1);
end
if no_null
return
end
% Check for NaNs
index=find(isnan(stack));
if isempty(index)
no_null=true;
return
end
% Select rows (times) with NaNs
temp=traces(index,:);
logindex=isnan(temp);
mult=ntr-sum(logindex,2);
% Replace NaNs by zeros and stack
temp(logindex)=0;
temp=sum(temp,2);
index1=find(mult == 0);
if isempty(index1)
stack(index)=temp./mult;
no_null=true;
else
stack(index)=temp./max(mult,eps);
stack(index(index1))=NaN;
end
if nargout > 2
multipl(index)=mult;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [stack,no_null,multipl]=weighted_stack(traces,no_null,weights)
% Function computes mean of elements of array traces along rows
% INPUT
% traces matrix of seismic traces to be stacked
% no_null logical variable (true (1) if "traces" contains no nulls)
% OUTPUT
% stack vector of stacked traces
% no_null logical variable (true (1) if "stack" contains no nulls)
% multipl multiplicity (number of samples averaged); unless NaNs are
% present, this is the number of columns of "traces".
nsamp=size(traces,1);
stack=traces*weights(:);
if nargout > 2
multipl=sum(weights)*ones(nsamp,1);
end
if no_null
return
end
no_null=true;
% Check for NaNs
index=find(isnan(stack));
if isempty(index)
return
end
% Select rows (times) with NaNs
temp=traces(index,:);
logindex=~isnan(temp);
for ii=1:length(index)
bool=logindex(ii,:);
if any(bool)
stack(index(ii))=temp(ii,bool)*weights(bool);
multipl(index(ii))=sum(weights(bool));
else
stack(index(ii))=NaN;
multipl(index(ii))=NaN;
no_null=false;
end
end
|
github
|
Abakumov/MLIB-master
|
helpx.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/helpx.m
| 2,177 |
utf_8
|
a0c250c0e79137c109cf98947d2cae71
|
function warnings=helpx(func)
% Run the example in the help section of a function
% The help section starts with the line "% EXAMPLE"
string=blanks(80);
string=strrep(string,' ','=');
helptext = help(func);
if isempty(helptext)
warnings=['Function "',func,'" has no help section'];
return
end
%linesep = [1 regexp(helptext,'\n')]
htext=tokens_no2(helptext,'\n');
idx=strmatch('EXAMPLE',strtrim(htext));
if ~isempty(idx)
if length(idx) > 1
warnings=['Function "',func,'" has more than one EXAMPLE'];
else
label=['Example for "',func,'" '];
disp([label,string(1:80-length(label))])
hhh=htext(idx+1:end);
hhh=splice_continued_lines_no1(hhh);
try
for ii=1:length(hhh)
temp=[strtrim(hhh{ii}),' ']; % Add a blank so that empty lines are displayed
disp(temp)
pause(0) % Make sure that the preceeding "display" command is
% executed befor the result of "eval" is displayed
% if ~isempty(temp)
eval(temp,',');
% end
end
catch
% ple
% keyboard
end
if nargout > 0
warnings=' ';
end
end
else
warnings=['Function "',func,'" has no EXAMPLE'];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function htext=splice_continued_lines_no1(htext)
% Splice command lines that end in ...
for ii=length(htext)-1:-1:1
temp=deblank(htext{ii});
if length(temp) > 3
while strcmp(temp(end-2:end),'...')
temp=[temp(1:end-3),htext{ii+1}];
htext(ii+1)=[];
end
end
htext{ii}=temp;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cstr=tokens_no2(str,sep)
linesep = [0 regexp(str,sep)];
ntokens=length(linesep)-1;
if ntokens < 1
cstr=[];
return
end
cstr=cell(length(linesep),1);
ik=0;
for ii=1:ntokens
temp=str(linesep(ii)+1:linesep(ii+1)-1);
if 1 %~isempty(temp)
ik=ik+1;
cstr{ik}=temp;
end
end
cstr(ik+1:end)=[];
|
github
|
Abakumov/MLIB-master
|
create_button4tracking.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/create_button4tracking.m
| 2,745 |
utf_8
|
abe461cec0859fa80b7f858108619779
|
function button_handle=create_button4tracking(type_of_action)
% Create a menu item to track cursor movements
%
% Written by: E. Rietsch: August 31, 2003
% Last updated: January 8, 2004
%
% button_handle=create_button4tracking(type_of_action)
% INPUT
% type_of_action cell array or string with the call-back function to use for cursor tracking
% presently options are:
% {@display_cursor_location_2d,gca}
% @display_cursor_location_3d
% 'g_display_cursor_location_patch'
userdata4button.on_off='off';
userdata4button.button_action=type_of_action;
figure_handle=gcf;
set(figure_handle,'MenuBar','figure')
%button_handle=uimenu('Label','Tracking is off','Tag','tracking_button', ...
% 'ForeGroundColor',[0 0 1],'UserData',userdata4button);
button_handle=uimenu('Label','Tracking is off','Tag','tracking_button', ...
'ForeGroundColor',[0 0 1]);
setappdata(button_handle,'UserData',userdata4button)
set(button_handle,'Callback',{@tracking,figure_handle})
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tracking(hObject,evdata,figure_handle) %#ok
% GUI tool
% Written by: E. Rietsch: August 31, 2003
% Last updated: January 8, 2004: use function handle
%
% tracking(hObject,evdata,figure_handle)
% INPUT
% hObject handle of button
% evdata reserved by Matlab
% figure_handle handle of figure window
% set(gcf,'MenuBar','none')
% state = uisuspend(gcf);
zoom off
if isempty (hObject) % Window has no "tracking" button
disp('No "tracking" button')
return
end
userdata4button=getappdata(hObject,'UserData');
if strcmp(userdata4button.on_off,'off')
% zoom off
userdata4button.on_off='on';
% set(hObject,'UserData',userdata4button,'Label','Tracking is on');
set(hObject,'Label','Tracking is on');
set(figure_handle,'WindowButtonMotionFcn',userdata4button.button_action);
% userdata4button.zoom_handles=disable_zoom(figure_handle)%test
% zh=userdata4button.zoom_handles%test
zoom off
else
userdata4button.on_off='off';
% setappdata(hObject,'UserData','userdata4button')
% set(hObject,'UserData',userdata4button,'Label','Tracking is off');
set(hObject,'Label','Tracking is off');
set(figure_handle,'WindowButtonMotionFcn',[]);
hh=findobj(figure_handle,'Tag','cursor_tracking_data'); % Find and remove the display
delete(hh) % of the cursor tracking data
% set(gcf,'menuBar','figure')
% uirestore(state);
% set(userdata4button.zoom_handles,'enable','on')
end
drawnow
setappdata(hObject,'UserData',userdata4button)
|
github
|
Abakumov/MLIB-master
|
showcell.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/showcell.m
| 15,711 |
utf_8
|
7cf9c7a0321ab88200801279b1c0b63a
|
function showcell(varargin)
%SHOWCELL Displays cell array with long strings in the command window.
% SHOWCELL(A) displays the contents of a cell array A in the command
% window. It will format the display so that long strings will display
% appropriately. A can be a cell array of numbers, strings, and/or other
% objects.
%
% Typically, if a cell array contains long strings, it will not display
% the text:
%
% >> A
%
% A =
%
% [3] 'this is a text.' 'hello'
% [4] 'More text' [ 32]
% [6] [1x54 char] [ 53]
%
% SHOWCELL will display it properly:
%
% >> showcell(A)
% [ 3] 'this is a text.' 'hello'
% [ 4] 'More text' [32]
% [ 6] 'This is a very long text that may not show up properly' [53]
%
% Acceptable numbers are of class DOUBLE, SINGLE, LOGICAL, UINT8, UINT16,
% UINT32, UINT64, INT8, INT16, INT32, INT64. Elements other than CHAR or
% numbers are displayed as the size and name of the object,
% e.g. [1x1 struct]
%
% SHOWCELL(A,'option1',value1,...) specifies optional arguments passed
% in in pairs. Valid options are (abbreviated names accepted):
%
% 'spacing' - column spacing. Default is 4 spaces.
% 'numformat' - number of digits OR format string (see SPRINTF) for
% numerical values. Default is 5 digits.
%
% Example:
% showcell(A, 'spacing', 5);
% showcell(A, 'numformat', 3);
% showcell(A, 'n', '%0.4f');
% showcell(A, 'sp', 2, 'nu', 6);
%
% See also DISP, DISPLAY
%
%
% VERSIONS:
% v1.0 - first version
% v1.1 - add quotes around strings (Jan 2006)
% v1.2 - accepts uint8, uint16, uint32, uint64, int8, int16, int32,
% int64, single, double, logical for numeric values.
% v2.0 - each column does not have to be of the same class. the cell
% elements can be of any class. (Jan 2006)
% v2.1 - fixed problems with displaying empty cell elements. (Jan 2006)
% v2.2 - fixed displaying an empty cell {}. Remove MORE function, since
% this can be achieved externally by calling MORE. (Jan 2006)
% v2.3 - now displays multi-dimension cells (Feb 10, 2006)
%
% Jiro Doke
% June 2004
%-----------------------------------------------------------------------
% Check cell array
%-----------------------------------------------------------------------
if ~nargin
return;
end
arg = varargin{1};
if ~iscell(arg)
error('This is not a cell array.');
end
%-----------------------------------------------------------------------
% Parse optional arguments
%-----------------------------------------------------------------------
% Default values
num_spaces = 4;
num_digits = 5;
% Possible optional arguments
optSpacing = 'spacing ';
optNumformat = 'numformat';
if nargin > 1
vars = varargin(2 : end);
if mod(length(vars) , 2)
error('The optional arguments must come in pairs.');
end
for id = 1 : 2 : length(vars)
% Get number of characters provided for optional arguments
% Accepts abbreviated option names
varC = min([length(vars{id}), 9]);
switch lower(vars{id})
case optSpacing(1 : varC) % SPACING
if isnumeric(vars{id + 1})
num_spaces = round(vars{id + 1});
else
error('Bad value for SPACING. Must be an integer');
end
case optNumformat(1 : varC) % NUMFORMAT
if isnumeric(vars{id + 1})
num_digits = round(vars{id + 1});
else
num_digits = vars{id + 1};
end
otherwise
error('Unknown option.');
end
end
end
%-----------------------------------------------------------------------
% Deal with multi-dimension cells
%-----------------------------------------------------------------------
isLoose = isequal(get(0,'FormatSpacing'),'loose');
if ndims(arg) > 2
sz = size(arg);
id = cell(ndims(arg) - 2, 1);
else
sz = [0 0 1];
end
for ii = 1:prod(sz(3:end))
if exist('id', 'var')
[id{:}] = ind2sub(sz(3:end), ii); %#ok
str = ['(:,:', sprintf(',%d', id{:}), ')'];
this_arg = arg(:, :, id{:});
else
this_arg = arg;
str = '';
end
if ~isempty(inputname(1))
if isLoose
disp(' ');
fprintf('%s%s =\n', inputname(1), str);
disp(' ');
else
fprintf('%s%s =\n', inputname(1), str);
end
end
if isequal(size(this_arg), [0 0])
disp(' {}');
if isLoose
disp(' ');
end %
elseif ismember(0, size(this_arg))
fprintf(' Empty cell array: %d-by-%d\n', size(this_arg));
if isLoose
disp(' ')
end %
else
showcellEngine(this_arg, num_spaces, num_digits);
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
% showcellEngine
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function showcellEngine(arg, num_spaces, num_digits)
%-----------------------------------------------------------------------
% Determine class of cell elements
%-----------------------------------------------------------------------
cellArg = arg(:);
isNumChar = false(length(cellArg), 12);
isNumChar(:, 1) = cellfun('isclass', cellArg, 'char' );
isNumChar(:, 2) = cellfun('isclass', cellArg, 'double' );
isNumChar(:, 3) = cellfun('isclass', cellArg, 'single' );
isNumChar(:, 4) = cellfun('isclass', cellArg, 'uint8' );
isNumChar(:, 5) = cellfun('isclass', cellArg, 'uint16' );
isNumChar(:, 6) = cellfun('isclass', cellArg, 'uint32' );
isNumChar(:, 7) = cellfun('isclass', cellArg, 'uint64' );
isNumChar(:, 8) = cellfun('isclass', cellArg, 'int8' );
isNumChar(:, 9) = cellfun('isclass', cellArg, 'int16' );
isNumChar(:, 10) = cellfun('isclass', cellArg, 'int32' );
isNumChar(:, 11) = cellfun('isclass', cellArg, 'int64' );
isNumChar(:, 12) = cellfun('isclass', cellArg, 'logical');
% Number of elements in cell element
numElmt = cellfun('prodofsize', cellArg);
% Remove number cells with vectors (more than a scalar)
isNumChar(:, 2:end) = isNumChar(:, 2:end) & repmat(numElmt <= 1, 1, 11);
% Number elements
isNum = ~~sum(isNumChar(:, 2:end), 2);
% Cell elements
cellElements = cellfun('isclass', cellArg, 'cell');
% Empty elements
emptyElements = cellfun('isempty', cellArg);
emptyCells = emptyElements & cellElements;
emptyNums = emptyElements & isNum;
% All other objects (including objects with more than one element)
isObj = xor(emptyCells, ~sum(isNumChar, 2));
% Discard empty number elements. These will be processed separately.
isNumChar(isNumChar & repmat(emptyNums, 1, size(isNumChar, 2))) = false;
%-----------------------------------------------------------------------
% Deal with empty elements
%-----------------------------------------------------------------------
if any(emptyCells)
cellArg(emptyCells) = {'{}'};
end
if any(emptyNums)
cellArg(emptyNums) = {'[]'};
end
%-----------------------------------------------------------------------
% Deal with numeric elements
%-----------------------------------------------------------------------
numID = logical(sum(isNumChar(:, 2:end), 2));
if ~isempty(find(numID,1))
TOdouble = repmat(NaN, length(cellArg), 1);
% Convert the numeric/logical values to double
useIDX = find(sum(isNumChar(:, 2:end)));
% Only parse through valid types
for iType = useIDX + 1
TOdouble(isNumChar(:, iType), 1) = ...
double([cellArg{isNumChar(:, iType)}]');
end
TOdouble(~numID) = [];
% Convert DOUBLE to strings and put brackets around them
try
tmp = strcat({'['}, num2str(TOdouble, num_digits), {']'});
catch % ME
% getReport(ME)
error('Abnormal termination')
end
cellArg(numID) = tmp;
end
%-----------------------------------------------------------------------
% Deal with string elements
%-----------------------------------------------------------------------
% Put single quotes around the strings
stringCell = strcat({''''}, cellArg(isNumChar(:, 1)), {''''});
cellArg(isNumChar(:, 1)) = stringCell;
%-----------------------------------------------------------------------
% Deal with elements other than string or numeric
%-----------------------------------------------------------------------
objID = find(isObj);
objCell = cell(length(objID), 1);
for iObj = 1:length(objID)
sz = size(cellArg{objID(iObj)});
cl = class(cellArg{objID(iObj)});
% Display size and class type, wrapped by brackets
switch cl
case 'cell'
if length(sz) < 4
objCell{iObj} = ['{', sprintf('%dx', sz(1:end-1)), ...
num2str(sz(end)), sprintf(' %s}', cl)];
else
objCell{iObj} = sprintf('{%d-D %s}', length(sz), cl);
end
otherwise
if length(sz) < 4
objCell{iObj} = ['[', sprintf('%dx', sz(1:end-1)), ...
num2str(sz(end)), sprintf(' %s]', cl)];
else
objCell{iObj} = sprintf('[%d-D %s]', length(sz), cl);
end
end
end
cellArg(isObj) = objCell;
% Reconstruct the original size
arg = reshape(cellArg, size(arg));
%-----------------------------------------------------------------------
% Create FPRINTF format string based on length of strings
%--------------------------------------------------------------------------
char_len = cellfun('length', arg); %
if 0 % Change this to 1 in order to right justify numeric elements.
% This will be slightly slower.
conv_str = ' ';
for iCol = 1:size(arg, 2);
if length(unique(char_len(:, iCol))) == 1
conv_str = [conv_str, ...
sprintf('%%-%ds%s', unique(char_len(:, iCol)), ...
blanks(num_spaces))]; %#ok Don't bother ...
else
tmp = char(arg(:, iCol));
idx1 = strfind(tmp(:, 1)', '[');
idx2 = strfind(tmp(:, 1)', '{');
tmp([idx1 idx2], :) = strjust(tmp([idx1 idx2], :), 'right');
arg(:, iCol) = cellstr(tmp);
conv_str = [conv_str, ...
sprintf('%%-%ds%s', max(char_len(:, iCol)), ...
blanks(num_spaces))]; %#ok Don't bother ...
end
end
else
% Create array of max character lengths and blank pads
char_max = [num2cell(max(char_len, [], 1)); ...
repmat({blanks(num_spaces)}, 1, size(char_len, 2))];
conv_str = [' ', sprintf('%%-%ds%s', char_max{:})];
end
% Add carrige return at the end
conv_str = [conv_str(1 : end - num_spaces) '\n'];
%--------------------------------------------------------------------------
% Display in command window
%--------------------------------------------------------------------------
% Must transpose for FPRINTF to work
arg = arg';
% If arg is a single EMPTY cell/string/numeric element,
% then wrap it with {}
if length(arg) == 1
switch arg{1}
case {'{}', '''''', '[]'}
conv_str = ' {%s}\n';
end
end
try
% Wrap around TRY ... END in case the user quits out of MORE
fprintf(1, conv_str, arg{:});
if isequal(get(0,'FormatSpacing'),'loose')
disp(' ');
end
catch
% Do nothing
end
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
|
github
|
Abakumov/MLIB-master
|
interpret_las2.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/interpret_las2.m
| 6,780 |
utf_8
|
22b4f7f0fd397be4e2624ab5e5fb3130
|
function [wlog,aux]=interpret_las2(tlines,wrap)
% Interpret the lines of a file in LAS 3.0 format and create a well-log
% structure.
%
% Written by: E. Rietsch: December 19, 2006
% Last updated: February 7, 2007: Handle parameters without a preceding ~PARAMETER line
%
% [wlog,aux]=interpret_las2(tlines)
% INPUT
% tlines non-blank lines of the LAS 2.0 file (except for the first two lines
% OUTPUT
% wlog well log structure
% aux auxiliary information
global S4M L_WPLOG_REPEAT
aux=[];
L_WPLOG_REPEAT=true; % Used to avoid repeating a specific message
% Wrap info
comp=split_line(tlines{1});
if strcmp(comp{1},'WRAP')
if ~strcmp(strtrim(comp{2}),'NO')
disp('LAS file is wrapped.')
wrap=true;
else
wrap=false;
end
else
error(['Line ',tlines{1},' should have wrap information.'])
end
[dummy,filename]=fileparts(S4M.filename);
wlog=struct('type','well_log','tag','unspecified','name',filename, ...
'first',[],'last',[],'step',[],'units','','null',-999.25, ...
'from',S4M.filename,'curve_info',[],'curves',[]);
% Section-start lines
index=find(~cellfun(@isempty,strfind(tlines','~')));
index=[index,length(tlines)+1];
for ii=1:length(index)-1
tline=tlines{index(ii)};
switch tline(1:2)
case '~W'
wlog=well_section_no1(wlog,tlines(index(ii)+1:index(ii+1)-1));
case '~C'
wlog=curve_section_no3(wlog,tlines(index(ii)+1:index(ii+1)-1));
case '~P'
wlog=parameter_section_no2(wlog,tlines(index(ii)+1:index(ii+1)-1));
case '~A'
wlog=data_section_no4(wlog,tlines(index(ii)+1:index(ii+1)-1),wrap);
otherwise
% Disregard section
end
end
wlog=fix_las_file_log(wlog);
clear global L_WPLOG_REPEAT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=well_section_no1(wlog,tlines)
% Read well-section information
global L_WPLOG_REPEAT
for ii=1:length(tlines)
comp=split_line(tlines{ii});
comp{2}=strtrim(comp{2});
switch lower(comp{1})
case 'strt'
comp1=split_units_values(comp{2});
wlog.first=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'stop'
comp1=split_units_values(comp{2});
wlog.last=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'step'
comp1=split_units_values(comp{2});
wlog.step=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'null'
wlog.null=str2double(comp{2});
case 'comp'
if ~isempty(comp{2})
wlog.company=comp{2};
end
case 'well'
if ~isempty(comp{2})
wlog.wellname=comp{2};
end
case 'loc'
if ~isempty(comp{2})
wlog.location=comp{2};
end
case 'fld'
if ~isempty(comp{2})
wlog.field=comp{2};
end
case 'ctry'
if ~isempty(comp{2})
wlog.country=comp{2};
end
% For Canada
case 'prov'
if ~isempty(comp{2})
wlog.province=comp{2};
end
case 'uwi'
if ~isempty(comp{2})
wlog.wellid=comp{2};
end
case 'lic'
if ~isempty(comp{2})
wlog.license_number=comp{2};
end
% For US
case 'stat'
if ~isempty(comp{2})
wlog.state=comp{2};
end
case 'cnty'
if ~isempty(comp{2})
wlog.county=comp{2};
end
case 'api'
if ~isempty(comp{2})
wlog.api=comp{2};
end
% end of "For US"
case 'srvc'
if ~isempty(comp{2})
wlog.service=comp{2};
end
case 'date'
if ~isempty(comp{2})
wlog.date=comp{2};
end
otherwise
disp([' Unexpected keyword in ~WELL INFORMATION section: ',comp{1}])
if L_WPLOG_REPEAT
disp(' Assume that the ~PARAMETER INFORMATION line is missing.')
L_WPLOG_REPEAT=false;
end
wlog=parameter_section_no2(wlog,tlines(ii));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=parameter_section_no2(wlog,tlines)
% Read parameter section (or misplaced parameters)
nlines=length(tlines);
if ~isfield(wlog,'parameter_info')
wlog.parameter_info=cell(nlines,3);
ik=0;
else
ik=size(wlog.parameter_info,1);
end
for ii=1:nlines
comp=split_line(tlines{ii});
comp1=split_units_values(comp{2});
values=str2num(comp1{2}); %#ok Can be more than one value
if ~isempty(values)
ik=ik+1;
mnem=lower(strrep(comp{1},' ','_'));
units=unit_substitution(comp1{1}); % Create standardized units of measurement
wlog.parameter_info(ik,:)={mnem,units,comp{3}};
wlog.(mnem)=values;
end
end
if ik == 0
wlog=rmfield(wlog,'parameter_info');
else
wlog.parameter_info(ik+1:end,:)=[];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=curve_section_no3(wlog,tlines)
% Read curve-section information
global S4M
nlines=length(tlines);
wlog.curve_info=cell(nlines,3);
for ii=1:nlines
comp=split_line(tlines{ii});
comp1=split_units_values(comp{2});
if S4M.case_sensitive
mnem=strrep(comp{1},' ','_');
else
mnem=lower(strrep(comp{1},' ','_'));
end
units=unit_substitution(comp1{1}); % Create standardized units of measurement
wlog.curve_info(ii,:)={mnem,units,comp{3}};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=data_section_no4(wlog,tlines,wrap)
% Read data in data section
global S4M
nlines=length(tlines);
ncols=size(wlog.curve_info,1);
if wrap
curves=zeros(nlines*ncols,1,S4M.precision);
ia=1;
for ii=1:nlines
[temp,nnum]=sscanf(tlines{ii},'%g');
ie=ia+nnum-1;
curves(ia:ie)=temp;
ia=ie+1;
end
wlog.curves=reshape(curves(1:ie),ncols,[])';
else
curves=zeros(nlines,ncols,1,S4M.precision);
for ii=1:nlines
curves(ii,:)=sscanf(tlines{ii},'%g')';
end
wlog.curves=curves;
end
|
github
|
Abakumov/MLIB-master
|
wseismic_scrollbar_menu.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/wseismic_scrollbar_menu.m
| 5,153 |
utf_8
|
efb498e845f3406baca9e904d41f0181
|
function menu_handle=wseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% Function creates a menu button on the figure with handle "figure_handle" (or
% the current figure) that allows one to add scroll bars to a wiggle seismic plot
%
% Written by: E. Rietsch, August 22, 2005
% Last updated: November 5, 2005: Save axis limits before user querry
%
% menu_handle=wseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% seismic seismic dataset to be displayed; needed to provide limits for the scrollbar boxes
% plotdir plot direction
% OUTPUT
% menu_handle handle of the menu button created by this function
ntr=size(seismic.traces,2);
tmax=seismic.last-seismic.first;
tmin=min(3*seismic.step,tmax);
if tmin > tmax
tmin=tmax;
end
% Create menu button
menu_handle=uimenu(figure_handle,'Label','Add scrollbars','ForegroundColor','b');
set(menu_handle,'Callback',{@seismic_scrollbar,gca,menu_handle,ntr,tmin,tmax,plotdir});
if nargout == 0
clear menu_handle
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic_scrollbar(hObject,evdata,axis_handle,menu_handle,ntr,tmin,tmax,plotdir) %#ok
label=get(menu_handle,'Label');
if strcmp(label,'Add scrollbars')
set(menu_handle,'Label','Remove scrollbars');
else
reset_scroll_button(axis_handle,menu_handle)
return
end
zoom out
% Prompt user for time and trace range
prompt={'Enter the number of traces to display:','Enter the time range to display:'};
name='Scroll parameters';
numlines=1;
defaultanswer=mat2cellstrings([min(50,ntr),min(500,tmax)]);
ier1=true;
ier2=true;
% Save present axis limits
v=axis;
setappdata(menu_handle,'axislimits',v)
while any(ier1) || any(ier2)
answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
reset_scroll_button(axis_handle,menu_handle)
return
end
[ntraces,ier1]=check_numeric(answer{1},'Number of traces',{'minmax',[1,1]}, ...
{'bounds',1,ntr});
% keyboard
[timerange,ier2]=check_numeric(answer{2},'Time range',{'minmax',[1,1]}, ...
{'bounds',tmin,tmax});
end
% This reduces flickering when the axis is updated
set(gcf,'doublebuffer','on');
% Set appropriate axis limits and settings
% set(axis_handle,'xlim',[v(1),v(1)+ntraces],'ylim',[v(3),v(3)+timerange]);
% Generate constants for use in uicontrol initialization
pos=get(axis_handle,'position');
%xmin=round(v(1));
%xmax=round(v(2));
xmin=v(1);
xmax=v(2);
ymin=round(v(3));
ymax=round(v(4));
if ntr > 1
xtraces=ntraces*(xmax-xmin)/(ntr-1);
else
xtraces=ntraces;
end
if ntraces < ntr
ntraces=ntraces+1;
% Create a slider below the x-axis
xsliderpos=[pos(1), pos(2)-0.030, pos(3), 0.029];
sstep1=max(1/(ntr-ntraces+1),0.01);
if strcmp(plotdir,'l2r')
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmin, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
else
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmax-xtraces, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
end
set(hxslider,'Callback',{@scrollx,axis_handle,xtraces,xmin,xmax,plotdir})
set(gca,'XLim',[xmin,xmin+xtraces])
no_xscrollbar=false;
else
hxslider=1.1;
no_xscrollbar=true;
end
if timerange < tmax
ysliderpos=[pos(1)+pos(3)+0.003, pos(2), 0.018, pos(4)];
sstep2=min(1,timerange/(ymax-ymin));
hyslider=uicontrol('style','slider',...
'units','normalized','Position',ysliderpos,...
'min',ymin,'max',ymax-timerange,'value',ymax-timerange, ...
'SliderStep',[max(sstep2/10,8/(ymax-ymin)),sstep2]);
set(hyslider,'Callback',{@scrolly,axis_handle,timerange,ymin,ymax})
set(gca,'YLim',[ymin, ymin+timerange])
no_yscrollbar=false;
else
hyslider=1.1;
no_yscrollbar=true;
end
setappdata(menu_handle,'sliders',[hxslider,hyslider])
if no_xscrollbar && no_yscrollbar
set(menu_handle,'Label','Add scrollbars');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrollx(hObject,evdata,axis_handle,ntraces,xmin,xmax,plotdir) %#ok
if strcmp(plotdir,'l2r')
xlimits=get(gcbo,'value')+[0,ntraces];
else
xlimits=xmax-get(gcbo,'value')+[-ntraces,0]+xmin;
end
set(axis_handle,'XLim',xlimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrolly(hObject,evdata,axis_handle,timerange,ymin,ymax) %#ok
ylimits=ymax-get(gcbo,'value')+[-timerange,0]+ymin;
%ylimits=ylimits;
set(axis_handle,'YLim',ylimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function reset_scroll_button(axis_handle,menu_handle) %#ok
set(menu_handle,'Label','Add scrollbars');
sliders=getappdata(menu_handle,'sliders');
try
delete(sliders(1))
catch
end
try
delete(sliders(2))
catch
end
axislimits=getappdata(menu_handle,'axislimits');
axis(axis_handle,axislimits)
|
github
|
Abakumov/MLIB-master
|
create_menu_item4tracking.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/create_menu_item4tracking.m
| 2,430 |
utf_8
|
d3a3a13bcc81b9e941b34f6f8b59122a
|
function button_handle=create_menu_item4tracking(type_of_action,button_handle)
% Create a menu item to track cursor movements
%
% Written by: E. Rietsch: August 31, 2003
% Last updated: January 8, 2004
%
% button_handle=create_button4tracking(type_of_action)
% INPUT
% type_of_action cell array or string with the call-back function to use for cursor tracking
% presently options are:
% {@display_cursor_location_2d,gca}
% @display_cursor_location_3d
% 'g_display_cursor_location_patch'
userdata4button.on_off='off';
userdata4button.button_action=type_of_action;
figure_handle=gcf;
% set(figure_handle,'MenuBar','figure')
%button_handle=uimenu('Label','Tracking is off','Tag','tracking_button', ...
% 'ForeGroundColor',[0 0 1],'UserData',userdata4button);
item_handle=uimenu(button_handle,'Label','Turn tracking on','Tag','tracking_button', ...
'ForeGroundColor',[0 0 1]);
setappdata(item_handle,'UserData',userdata4button)
set(item_handle,'Callback',{@tracking,figure_handle})
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tracking(hObject,evdata,figure_handle) %#ok
% GUI tool
% Written by: E. Rietsch: August 31, 2003
% Last updated: July 15, 2009: make menu labels more descriptive
%
% tracking(hObject,evdata,figure_handle)
% INPUT
% hObject handle of button
% evdata reserved by Matlab
% figure_handle handle of figure window
% UPDATE HISTORY
% January 8, 2004: use function handle
% set(gcf,'MenuBar','none')
% state = uisuspend(gcf);
zoom off
if isempty (hObject) % Window has no "tracking" button
disp('No "tracking" button')
return
end
userdata4button=getappdata(hObject,'UserData');
if strcmp(userdata4button.on_off,'off')
userdata4button.on_off='on';
set(hObject,'Label','Turn tracking off');
set(figure_handle,'WindowButtonMotionFcn',userdata4button.button_action);
zoom off
else
userdata4button.on_off='off';
set(hObject,'Label','Turn tracking on');
set(figure_handle,'WindowButtonMotionFcn',[]);
hh=findobj(figure_handle,'Tag','cursor_tracking_data'); % Find and remove the display
delete(hh) % of the cursor tracking data
end
drawnow
setappdata(hObject,'UserData',userdata4button)
|
github
|
Abakumov/MLIB-master
|
cseismic_scrollbar_menu_item.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/cseismic_scrollbar_menu_item.m
| 5,115 |
utf_8
|
37458559768477864c62f7229ca84cad
|
function menu_handle=cseismic_scrollbar_menu_item(figure_handle,options_menu_handle,seismic,plotdir)
% Function creates a menu button on the figure with handle "figure_handle"
% that allows one to add scroll bars to a color seismic plot
%
% Written by: E. Rietsch, August 22, 2005
% Last updated: November 5, 2005: Save axis limits before user querry
%
% menu_handle=cseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% seismic seismic data set to be displayed; needed to provide limits for
% the scrollbar boxes
% plotdir plot direction
% OUTPUT
% menu_handle handle of the menu button created by this function
ntr=size(seismic.traces,2);
tmax=seismic.last-seismic.first;
tmin=3*seismic.step;
% Create menu button
menu_handle=uimenu(options_menu_handle,'Label','Add scrollbars','ForegroundColor','b');
set(menu_handle,'Callback',{@seismic_scrollbar,gca,menu_handle,ntr,tmin,tmax,plotdir});
if nargout == 0
clear menu_handle
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic_scrollbar(hObject,evdata,axis_handle,menu_handle,ntr,tmin,tmax,plotdir) %#ok
label=get(menu_handle,'Label');
if strcmp(label,'Add scrollbars')
set(menu_handle,'Label','Remove scrollbars');
else
reset_scroll_button(axis_handle,menu_handle)
set(menu_handle,'Label','Add scrollbars');
return
end
zoom out
% Prompt user for time and trace range
prompt={'Enter the number of traces to display:','Enter the time range to display:'};
name='Scroll parameters';
numlines=1;
defaultanswer=mat2cellstrings([min(50,ntr),min(500,tmax)]);
ier1=true;
ier2=true;
% Save present axis limits
v=axis;
setappdata(menu_handle,'axislimits',v)
while any(ier1) || any(ier2)
answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
reset_scroll_button(axis_handle,menu_handle)
return
end
[ntraces,ier1]=check_numeric(answer{1},'Number of traces',{'minmax',[1,1]}, ...
{'bounds',1,ntr});
[timerange,ier2]=check_numeric(answer{2},'Time range',{'minmax',[1,1]}, ...
{'bounds',tmin,tmax});
end
% This reduces flickering when the axis is updated
set(gcf,'doublebuffer','on');
% Set appropriate axis limits and settings
% set(axis_handle,'xlim',[v(1),v(1)+ntraces],'ylim',[v(3),v(3)+timerange]);
% Generate constants for use in uicontrol initialization
pos=get(axis_handle,'position');
dx=(v(2)-v(1))/ntr;
xmin=dx*round(2*v(1)/dx)/2;
xmax=dx*round(2*v(2)/dx)/2;
ymin=round(v(3));
ymax=round(v(4));
xtraces=ntraces*(xmax-xmin)/ntr;
if ntraces < ntr
% Create a slider below the x-axis
xsliderpos=[pos(1), pos(2)-0.030, pos(3), 0.029];
sstep1=max(1/(ntr-ntraces),0.01);
if strcmp(plotdir,'l2r')
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmin, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
else
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmax-xtraces, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
end
set(hxslider,'Callback',{@scrollx,axis_handle,xtraces,xmin,xmax,plotdir})
set(gca,'XLim',[xmin,xmin+xtraces])
no_xscrollbar=false;
else
hxslider=1.1;
no_xscrollbar=true;
end
if timerange < tmax
ysliderpos=[pos(1)+pos(3)+0.002, pos(2), 0.018, pos(4)];
sstep2=min(1,timerange/(ymax-ymin));
hyslider=uicontrol('style','slider',...
'units','normalized','Position',ysliderpos,...
'min',ymin,'max',ymax-timerange,'value',ymax-timerange, ...
'SliderStep',[max(sstep2/10,8/(ymax-ymin)),sstep2]);
set(hyslider,'Callback',{@scrolly,axis_handle,timerange,ymin,ymax})
set(gca,'YLim',[ymin, ymin+timerange])
no_yscrollbar=false;
else
hyslider=1.1;
no_yscrollbar=true;
end
setappdata(menu_handle,'sliders',[hxslider,hyslider])
if no_xscrollbar && no_yscrollbar
set(menu_handle,'Label','Add scrollbars');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrollx(hObject,evdata,axis_handle,ntraces,xmin,xmax,plotdir) %#ok
if strcmp(plotdir,'l2r')
xlimits=get(gcbo,'value')+[0,ntraces];
else
xlimits=xmax-get(gcbo,'value')+[-ntraces,0]+xmin;
end
set(axis_handle,'XLim',xlimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrolly(hObject,evdata,axis_handle,timerange,ymin,ymax) %#ok
ylimits=ymax-get(gcbo,'value')+[-timerange,0]+ymin;
%ylimits=ylimits;
set(axis_handle,'YLim',ylimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function reset_scroll_button(axis_handle,menu_handle)
set(menu_handle,'Label','Add scrollbars');
sliders=getappdata(menu_handle,'sliders');
try
delete(sliders(1))
catch
end
try
delete(sliders(2))
catch
end
axislimits=getappdata(menu_handle,'axislimits');
axis(axis_handle,axislimits)
|
github
|
Abakumov/MLIB-master
|
axis_label_location.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/axis_label_location.m
| 4,911 |
utf_8
|
52719f3f36281be2243593d021aefe38
|
function axis_label_location(handles,xll,yll)
% In a multi-plot figure created by "mysubplot" this function allows selection
% of the axes which should be annotated.
%
% Written by: E. Rietsch: March 19, 2009
% Last updated:
%
%
% INPUT
% handles matrix of handle values as output by function "mysubplot".
% if "handles" has "nh" rows and "mh" columns the the figure has
% "nh" rows and "mh" columns of subplots
% xll x-label location; possible values are:
% 'bottom' labels are along all top axes
% 'top' labels are along all bottom axes
% 'both' labels are along the top and the bottom axes
% 'talternate' labels are alternating between the top and the bottom
% axes,beginning with the top axis
% 'balternate' labels are alternating between the bottom and the top
% axes, beginning with the bottom axis
% yll y-label location; possible values are:
% 'left' labels are along all left axes
% 'right' labels are along all right axes
% 'both' labels are along the left and the right axes
% 'lalternate' labels are alternating between the left and the right
% axes,beginning with the left axis
% 'ralternate' labels are alternating between the right and the left
% axes, beginning with the left axis
%
%
% EXAMPLES
% lfigure
% handles=mysubplot([1,2],[1,1,1]);
% axis_label_location(handles,'both','lalternate')
%% Remove the axis labels from the "inner" subplots
[ny,nx]=size(handles);
set(handles(2:end-1,:),'XTickLabel',[])
delete_label(handles(2:end-1,:),'XLabel')
%delete_label(handles(2:end-1,:),'YLabel')
set(handles(:,2:end-1),'YTickLabel',[])
% delete_label(handles(:,2:end-1),'XLabel')
delete_label(handles(:,2:end-1),'YLabel')
%% Handle "outer" X-Axes
switch xll
case {'bottom'}
set(handles(end,:),'XAxisLocation','bottom')
if ny > 1
set(handles(1,:),'XTickLabel',[])
delete_label(handles(1,:),'XLabel')
end
case {'top'}
set(handles(1,:),'XAxisLocation','top')
if ny > 1
set(handles(end,:),'XTickLabel',[])
delete_label(handles(end,:),'XLabel')
end
case {'both'}
set(handles(end,:),'XAxisLocation','bottom')
set(handles(1,:),'XAxisLocation','top')
case 'talternate'
set(handles(1,1:2:end),'XAxisLocation','top')
set(handles(end,2:2:end),'XAxisLocation','bottom')
if ny > 1
set(handles(1,2:2:end),'XTickLabel',[])
delete_label(handles(1,2:2:end),'XLabel')
set(handles(end,1:2:end),'XTickLabel',[])
delete_label(handles(end,1:2:end),'XLabel')
end
case 'balternate'
set(handles(1,2:2:end),'XAxisLocation','top')
set(handles(end,1:2:end),'XAxisLocation','bottom')
if ny > 1
set(handles(1,1:2:end),'XTickLabel',[])
delete_label(handles(1,1:2:end),'XLabel')
set(handles(end,2:2:end),'XTickLabel',[])
delete_label(handles(end,2:2:end),'XLabel')
end
otherwise
error(['Unknown option for x-axis label: ',xll])
end
%% Handele "outer" Y-axes
switch yll
case {'left'}
set(handles(:,1),'YAxisLocation','left')
if nx > 1
set(handles(:,end),'YTickLabel',[])
delete_label(handles(:,end),'YLabel')
end
case {'right'}
set(handles(:,end),'YAxisLocation','right')
if nx > 1
set(handles(:,1),'YTickLabel',[])
delete_label(handles(:,1),'YLabel')
end
case {'both'}
set(handles(:,end),'YAxisLocation','right')
set(handles(:,1),'YAxisLocation','left')
case 'lalternate'
set(handles(2:2:end,end),'YAxisLocation','right')
set(handles(1:2:end,1),'YAxisLocation','left')
if nx > 1
set(handles(1:2:end,end),'YTickLabel',[])
delete_label(handles(1:2:end,end),'YLabel')
set(handles(2:2:end,1),'YTickLabel',[])
delete_label(handles(2:2:end,1),'YLabel')
end
case 'ralternate'
set(handles(1:2:end,end),'YAxisLocation','right')
set(handles(2:2:end,1),'YAxisLocation','left')
if nx > 1
set(handles(2:2:end,end),'YTickLabel',[])
delete_label(handles(2:2:end,end),'YLabel')
set(handles(1:2:end,1),'YTickLabel',[])
delete_label(handles(1:2:end,1),'YLabel')
end
otherwise
error(['Unknown option for y-axis label: ',yll])
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function delete_label(haxis,label)
hh=get(haxis,label);
if isempty(hh)
return
end
if iscell(hh)
hh=cell2num(hh);
end
set(hh,'String','')
|
github
|
Abakumov/MLIB-master
|
menu2pick_frequency_windows.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/menu2pick_frequency_windows.m
| 10,172 |
utf_8
|
8d3c03e75c86b2f261410434e502baf5
|
function MenuHandle=menu2pick_frequency_windows(figure_handle)
% Create menu button to pick rectangular windows; the spectrum of the data
% is posted to a second window. The callback function that does
% all this is also in this file ("g_ispectrum") and passed on to the
% "outside world" via a "function handle".
%
% Written by: E. Rietsch: November 23, 2003
% Last updated: February 8, 2006: Fix bug with non-normalized data;
% add box around spectrum plot
%
% MenuHandle=menu2pick_frequency_windows(figure_handle)
% INPUT
% figure_handle handle of the figure to which the menu button is
% to be attached; default: gcf
% OUTPUT
% MenuHandle handle of the menu item
global S4M
if nargin == 0
figure_handle=gcf;
end
% Create menu button
MenuHandle=uimenu(figure_handle,'Label','Pick windows','ForeGroundColor',[1 0 0]);
set(MenuHandle,'CallBack',@g_ispectrum,'Tag','Pick_window_menu')
if S4M.experience < 0
display_help('s_ispectrum')
end
% waitfor(MenuHandle) % Don't wait
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_ispectrum(varargin)
% Interactively select windows on a seismic data set and compute the spectra of
% the data in these windows
%
% Written by: E. Rietsch: November 23, 2003
% Last updated: November 27, 2003: Bug fix with window plot
% global S4M
SeisHandle=gcf;
userdata=get(SeisHandle,'Userdata');
param=userdata.param;
seismic=userdata.seismic;
ntr0=size(seismic.traces,2);
% Remove figure button functions
try
state = uisuspend(SeisHandle);
catch
end
% If button is pressed in Window check if it was over the Picking button
set(SeisHandle,'WindowButtonDownFcn','g_check_menu_button', ...
'CloseRequestFcn',@g_closerequest4ispectrum)
MenuHandle=findobj(SeisHandle,'Tag','Pick_window_menu');
arg='findobj(gcf,''Tag'',''Pick_window_menu'')';
set(MenuHandle,'Label','Done picking windows','CallBack',['delete(',arg,')'])
if isfield(seismic,'null')
null=1; % Set logical value null to true if there are NaNs in the seismic
else
null=0; % Set logical value null to false if there are no NaNs in the seismic
end
nspectra=length(param.colors);
book=cell(nspectra,4); % Book-keeping array
% color, handle of box, handle of spectrum, box coordinates
book(:,1)=param.colors';
index=1:nspectra;
fnyquist=500/seismic.step;
if param.frequencies{2} > fnyquist
param.frequencies{2}=fnyquist;
end
SpecHandle=lfigure;
if strcmpi(param.scale,'log')
axis([param.frequencies{1},param.frequencies{2},param.minamp,0])
else
axis([param.frequencies{1},param.frequencies{2},0,1])
end
% Shift figure position to make it visible below seismic window
msg=['This figure can be closed once the Button "',get(MenuHandle,'Label'), ...
'" in the corresponding seismic window (Figure ',num2str(SeisHandle),') has been pressed.'];
set(SpecHandle,'Position',get(SpecHandle,'Position')+[-40,40,0,0], ...
'CloseRequestFcn',{@closedlg,msg},'Tag',['Spectrum_4_',num2str(SeisHandle)])
%figure_export_menu(SpecHandle); % Create menu button to export figure as emf/eps file
if strcmpi(param.normalize,'yes')
axis manual
end
grid on
zoom
mytitle('Amplitude spectra of selected windows of seismic data set')
xlabel('Frequency (Hz)')
if strcmpi(param.scale,'linear')
atext='Amplitude (linear)';
else
atext='Amplitude (dB)';
end
ylabel(atext)
type='continue';
while ~strcmpi(type,'quit') && ishandle(MenuHandle)
if isempty(index)
warndlg(' Not enough colors to display additional spectrum')
end
figure(SeisHandle)
ia=index(1);
axis_handle=gca;
set(SeisHandle,'WindowButtonDownFcn',{@pick_or_delete_a_box,axis_handle})
waitfor(MenuHandle,'UserData')
if ishandle(MenuHandle)
set(MenuHandle,'UserData','wait')
else
break
end
userdata1=get(axis_handle,'UserData');
type=userdata1.type;
handle=userdata1.handle;
databox=userdata1.databox;
refresh
switch type
case 'pick' % A box has been picked
% Round coordinates of box to the nearest samples
if strcmpi(param.plottype,'color')
hvals=s_gh(seismic,param.annotation);
else
hvals=1:ntr0;
end
idxh=find(hvals >= databox(1) & hvals <= databox(2));
idxt1=round((min(databox(3:4))-seismic.first)/seismic.step)+1;
idxt2=round((max(databox(3:4))-seismic.first)/seismic.step)+1;
if isempty(idxh) || idxt2-idxt1 < 4
type='continue';
%delete(handle)
% keyboard
else
databox(1:2)=sort([hvals(idxh(1)),hvals(idxh(end))]);
databox(3:4)=([idxt1,idxt2]-1)*seismic.step+seismic.first;
handle=plot_box(databox,'r',param.linewidth);
book{ia,2}=handle;
book{ia,4}=databox;
index(1)=[];
ntr=length(idxh);
traces=seismic.traces(max([1,idxt1]):min([end,idxt2]),idxh);
if null
idx_null=find(isnan(traces));
if ~isempty(idx_null)
traces(idx_null)=0;
end
end
nsamp=size(traces,1);
% Apply a window to the traces
wind=mywindow(nsamp,param.window);
for ii=1:ntr
traces(:,ii)=traces(:,ii).*wind;
end
% traces=spdiags(wind,0,nsamp,nsamp)*traces;
ft=fft(traces,max([param.padding,nsamp]));
nfft=size(ft,1);
f=(0:2:nfft)*fnyquist/nfft;
amp=mean(abs(ft(1:length(f),:)),2);
if strcmpi(param.scale,'log')
amp=amp/max(amp);
amp(amp < 1.0e-5)=1.0e-5; % Constrain the possible values of the amplitude spectrum
amp=20*log10(amp/max(amp));
end
if strcmpi(param.scale,'linear') && strcmpi(param.normalize,'yes')
amp=amp/(max(amp)+eps);
end
color=book{ia,1};
if length(color) > 1
linestyle=color(2:end);
else
linestyle='-';
end
set(handle,'Color',color(1),'LineStyle',linestyle, ...
'LineWidth',param.linewidth,'EraseMode','none');
figure(SpecHandle)
v=axis;
if ia == 1
v(4)=max(amp);
else
v(4)=max(v(4),max(amp));
end
axis(v)
hl=line(f,amp,'Color',color(1),'LineStyle',linestyle, ...
'LineWidth',param.linewidth,'EraseMode','none');
book{ia,3}=hl;
end
case 'delete'
idx=find(cat(1,book{:,2}) == handle);
if isempty(idx)
disp(' No box that can be deleted has been selected.')
else
figure(SeisHandle)
delete(handle) % Delete box
refresh
figure(SpecHandle)
temp=book(idx,:);
delete(temp{3}) % Delete spectrum curve
refresh
book(idx,:)=[];
idx1=index(1)-1;
book=[book(1:idx1-1,:);temp;book(idx1:end,:)];
% book=[temp;book];
index=[idx1,index]; %#ok First value of "index" is next available row in bookkeeping array
end
case 'break'
% keyboard
otherwise
% Continue
end
end % End while
figure(SpecHandle)
set(SpecHandle,'CloseRequestFcn','closereq')
set(SeisHandle,'WindowButtonDownFcn',[])
hold off
ncurves=index(1)-1;
ltext1=cell(ncurves,1);
ltext2=cell(ncurves,1);
headervals=s_gh(seismic,param.annotation);
for ii=1:ncurves
if strcmpi(param.plottype,'wiggle_color')
firsttrace=num2str(headervals(min(book{ii,4}(1:2))));
lasttrace=num2str(headervals(max(book{ii,4}(1:2))));
else
firsttrace=num2str(min(book{ii,4}(1:2)));
lasttrace=num2str(max(book{ii,4}(1:2)));
end
ltext1(ii)={[strrep(param.annotation,'_','\_'),': ',firsttrace,'-', ...
lasttrace,';']};
ltext2(ii)={[' time: ',num2str(min(book{ii,4}(3:4))),'-', ...
num2str(max(book{ii,4}(3:4))),' ',seismic.units]};
end
ltext=[char(ltext1),char(ltext2)];
% Avoid error message if no spectrum curves have been created
try
legend(ltext,param.lloc)
catch
end
refresh
grid on
bgGray % Create a gray background
box on
% Return data to calling program
userdata=get(SeisHandle,'UserData');
SpecWindows=reshape([book{1:ncurves,4}],4,ncurves)';
userdata=struct('SpecWindows',SpecWindows,'exit',userdata.exit);
figure(SeisHandle)
try
uirestore(state);
catch
end
set(SeisHandle,'Userdata',userdata,'CloserequestFcn','closereq')
refresh
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_closerequest4ispectrum(varargin)
% Save "userdata" in case the close-figure button has been pressed
% global TABLE_FROM_ISPECTRUM
SeisHandle=gcf;
SpecHandle=findobj('Tag',['Spectrum_4_',num2str(SeisHandle)]);
set(SpecHandle,'CloseRequestFcn','closereq')
MenuHandle=findobj(SeisHandle,'Tag','Pick_window_menu');
delete(MenuHandle)
userdata=get(SeisHandle,'UserData');
userdata.exit=1;
% TABLE_FROM_ISPECTRUM.userdata=userdata;
% uiresume(SeisHandle)
set(SeisHandle,'CloserequestFcn','closereq','UserData',userdata)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pick_or_delete_a_box(varargin)
% Select a rectangular area/box in a figure or find the handle of an existing
% box (for deletion)
% Written by: E. Rietsch: November 23, 2003
% Last updated: August 27, 2004: add input arguments for use via a call-back function handle
%
% pick_or_delete_a_box(hObject,evdata,axis_handle)
% INPUT
% hObject used by Matlab
% evdata used by Matlab
% axis_handle axis handle
% OUTPUT
% userdata.type type of action ('pick' or 'delete', or 'continue')
% userdata.databox corners of box selected (if "type" is "pick", [] otherwise)
% userdata.handle handle of box selected (if "type" is "delete",[] otherwise)
axis_handle=varargin{3};
FigureHandle=gcf;
userdata=get(axis_handle,'UserData');
type=get(FigureHandle,'SelectionType');
set(FigureHandle,'WindowButtonDownFcn','')
if strcmp(type,'normal')
databox=gg_pickbox;
userdata.handle=[];
userdata.type='pick';
userdata.databox=databox;
elseif strcmp(type,'alt')
userdata.type='delete';
userdata.databox=[];
userdata.handle=gco;
if isempty(userdata.handle)
userdata.type='continue';
end
else
userdata.type='continue';
userdata.databox=[];
userdata.handle=[];
end
set(axis_handle,'UserData',userdata)
MenuHandle=findobj(FigureHandle,'Tag','Pick_window_menu');
set(MenuHandle,'UserData','proceed')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function closedlg(varargin)
% Message to display if the window close box of the spectral window is pushed.
msgdlg(varargin{3})
|
github
|
Abakumov/MLIB-master
|
progressbar.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/progressbar.m
| 8,257 |
utf_8
|
2e59acb2505884c1cc31640cdadefae0
|
function handle = progressbar( handle,increment,string,titlestr)
%
% progressbar - shows a progress bar dialog based on the function "waitbar"
%
% Format: handle = progressbar( handle,increment [,string,titlestr] )
%
% Input: handle - handle to current progress bar, [] for a new one
% increment - a fraction (0..1) to increment by.
% (-1) signals the function to remove the handle from
% the persistent list and close the progressbar
% string - a string to be replaced in the progress bar (optional)
% titlestr - a title for the dialog box (optional)
%
% Output: handle - a graphic handle of the dialog box
%
%
% NOTE: this function uses a persistant list of handles and their values.
% therefore, to delete a progressbar, please call the function with:
% progressbar( handle,-1 );
%
% an "abort" button is formed inside the progressbar, if the calling process
% uses the persistent function "gui_active". when the "abort" button is pressed,
% the Callback function "gui_active" changes it's value to zero, which enables
% the application to interactively stop execution
%
% Example: gui_active(1); % will add an abort button
% h = progressbar( [],0,'my test' );
% max_count = 1e+3;
% for idx = 1:max_count
% fprintf( '%d\n',idx )';
% h = progressbar( h,1/max_count );
% if ~gui_active
% break;
% end
% end
% progressbar( h,-1 );
%
persistent handle_list counter_list last_handle last_idx;
% initialize
% =============
call_flag = min( nargin,4 );
% analyze input and decide what to do
% ====================================
if isempty( handle ) % create a new dialog
counter_list(end+1) = 0;
last_idx = length( counter_list );
switch call_flag
case 2, last_handle = waitbar( increment,'Please Wait...' );
case 3, last_handle = waitbar( increment,string );
case 4, last_handle = waitbar( increment,string,'Name',titlestr );
end
handle_list(end+1) = last_handle;
handle = last_handle;
set(handle,'Name','Progress bar')
check_position( handle_list ); % so that the figures don't hide each other
if gui_active
add_button( last_handle ); % add the abort button if the state of the gui_active is set
end
elseif ( increment == -1 ) % delete correct handle from the list
last_handle = handle;
last_idx = find( handle_list == handle );
handle_list( last_idx ) = [];
counter_list( last_idx )= [];
if ishandle( last_handle ) % close the figure, if it's open
close( last_handle ); % since user can close it by him self
end
last_handle = [];
elseif (handle == last_handle) % update last dialog
counter_list(last_idx) = counter_list(last_idx) + increment;
if ishandle( handle ) % nobody killed my figure
switch call_flag
case 2, waitbar( counter_list(last_idx),handle );
case 3, waitbar( counter_list(last_idx),handle,string );
case 4, waitbar( counter_list(last_idx),handle,string,'Name',titlestr );
end
else % somebody killed my figure -> so I create it again
switch call_flag
case 2, handle = waitbar( counter_list(last_idx),'Please Wait...' );
case 3, handle = waitbar( counter_list(last_idx),string );
case 4, handle = waitbar( counter_list(last_idx),string,'Name',titlestr );
end
handle_list(last_idx) = handle;
last_handle = handle;
check_position( handle_list ); % so that the figures don't hide each other
if (gui_active)
add_button( last_handle ); % add the abort button if the state of the gui_active is set
end
end
else % find the handle inside the list
last_handle = handle;
last_idx = find( handle_list == handle );
if ~isempty( last_idx )
counter_list(last_idx) = counter_list(last_idx) + increment;
switch call_flag
case 2, waitbar( counter_list(last_idx),last_handle );
case 3, waitbar( counter_list(last_idx),last_handle,string );
case 4, waitbar( counter_list(last_idx),last_handle,string,'Name',titlestr );
end
end
end
% update display after all
% ==========================
try
% figure(handle)
drawnow('expose');
catch
end
% =======================================================================================
% Inner Function Implementation
% =======================================================================================
function add_button( fig_handle )
%
% adds the abort button to the waitbar%
% collect handles and set control units to pixels
axes_handle = get( fig_handle,'currentaxes' );
last_fig_units = get( fig_handle,'units' );
last_axes_units = get( axes_handle,'units' );
set( fig_handle,'units','pixels' );
set( axes_handle,'units','pixels' );
% read controls position
fig_position = get( fig_handle,'position' );
axes_position = get( axes_handle,'position' );
fig_width = fig_position(3);
% fig_height = fig_position(4);
axes_xcoord = axes_position(1);
axes_ycoord = axes_position(2);
axes_width = axes_position(3);
axes_height = axes_position(4);
% load the button icon and create the button
load( 'gauge_abort_icon' );
button_width = ButtonSize16x16(1)+2;
button_height = ButtonSize16x16(2)+2;
button_margin = 10;
button_xcoord = (fig_width + axes_width + axes_xcoord - button_width)/2 - button_margin;
button_ycoord = (axes_height - button_height)/2 + axes_ycoord;
uicontrol( 'Parent',fig_handle,'units','pixels',...
'Position',[ button_xcoord,button_ycoord,button_width,button_height ],...
'Callback','gui_active(0);progressbar(get(gcbo,''parent''),-1);close(get(gcbo,''parent''));',...
'CData',Icon16x16 );
% resize axis to accommodate the button, and restore axes and figure units back to previous
axes_position(3) = axes_width - button_width - button_margin;
set( axes_handle,'position',axes_position );
set( fig_handle,'units',last_fig_units );
set( axes_handle,'units',last_axes_units );
% ---------------------------------------------------------------------------------------
function check_position( handle_list )
%
% makes sure that the progressbar does not hide it's nested progressbars%
% process only if there is more than one progress bar on the screen
if (length(handle_list)>1)
y_increment = 70; % pixels
x_increment = 30; % pixels
% change units to pixels
screen_units = get( 0,'units' );
last_fig_units = get( handle_list(end-1),'units' );
cur_fig_units = get( handle_list(end),'units' );
set( 0,'units','pixels' );
set( handle_list(end-1),'units','pixels' );
set( handle_list(end),'units','pixels' );
% get positions, and calc new position for progress bar
screen_size = get( 0,'screensize' );
last_position = get( handle_list(end-1),'position' );
cur_position = get( handle_list(end),'position' );
cur_position(1) = last_position(1) + x_increment;
cur_position(2) = last_position(2) - y_increment;
% check that we don't go outside the screen
if (cur_position(1)+cur_position(3)>screen_size(3))
cur_position(1) = x_increment;
end
if (cur_position(2)<screen_size(1))
cur_position(2) = screen_size(4) - y_increment - cur_position(4);
end
% store new position and restore units
set( handle_list(end),'position',cur_position );
set( 0,'units',screen_units );
set( handle_list(end-1),'units',last_fig_units );
set( handle_list(end),'units',cur_fig_units );
end
|
github
|
Abakumov/MLIB-master
|
myimagemenu.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/myimagemenu.m
| 7,016 |
utf_8
|
2b0c5a6fa420b9dac2b5cb298b76ef93
|
function myimagemenu(figure_handle)
%IMAGEMENU adds a context menu to change image properties
% IMAGEMENU(handle) creates a context menu for all images with the parent
% handle that allows image properties to be easily changed.
% IMAGEMENU, without any input arguments, will create this context menu
% for all images that are found in the current figure.
% This allows users to easily change image properties, and is especially
% useful for compiled programs, as users do not have access to MATLAB's
% property editor.
%
% Last updated: January 23, 2008: Add colormap for PDFs
%
% EXAMPLE
% figure
% imagesc(peaks)
% axis image
% myimagemenu
if nargin == 0
% Use all images in current figure as default
figure_handle = gcf;
end
handle=findobj(figure_handle,'Tag',['image_menu',num2str(figure_handle)]);
if ~isempty(handle) % Menu button exists already
return
end
bh=uimenu('Label','Modify display','Separator','on','Tag',['image_menu',num2str(gcf)], ...
'ForeGroundColor',[0 0 1]);
%% handle = findobj(handle, 'type', 'image');
% Define the context menu
cmenu=bh;
% Define the context menu items
colormapmenu = uimenu(cmenu, 'Label', 'Colormap');
uimenu(cmenu, 'Label', 'Reverse current colormap', 'Callback', 'colormap(flipud(colormap))');
uimenu(cmenu, 'Label', 'Toggle colorbar on/off', 'Callback', @togglecolorbar);
if exist('pixval.m','file')
% Only show this to those who have it installed...help exist
uimenu(cmenu, 'Label', 'Toggle pixel values', 'Callback', 'pixval');
end
uimenu(cmenu, 'Label', 'Colormap length...', 'Callback', @colormaplength);
uimenu(cmenu, 'Label', '3D plot...', 'Callback', @call3d);
uimenu(cmenu, 'Label', 'Image limits...', 'Callback', @imagelimits);
uimenu(cmenu, 'Label', 'Title...', 'Callback', @titlecallback);
uimenu(cmenu, 'Label', 'X-axis label...', 'Callback', @xaxiscallback);
uimenu(cmenu, 'Label', 'Y-axis label...', 'Callback', @yaxiscallback);
% Define colormap choices
uimenu(colormapmenu, 'Label', 'Seismic', 'Callback', 'colormap(mycolormap(''seismic''))');
uimenu(colormapmenu, 'Label', 'Dark seismic', 'Callback', 'colormap(mycolormap(''dark_seismic''))');
uimenu(colormapmenu, 'Label', 'PDF', 'Callback', 'colormap(mycolormap(''pdf''))');
uimenu(colormapmenu, 'Label', 'Jet', 'Callback', 'colormap(jet)');
uimenu(colormapmenu, 'Label', 'Gray', 'Callback', 'colormap(gray)');
uimenu(colormapmenu, 'Label', 'Hot', 'Callback', 'colormap(hot)');
uimenu(colormapmenu, 'Label', 'Bone', 'Callback', 'colormap(bone)');
uimenu(colormapmenu, 'Label', 'Cool', 'Callback', 'colormap(cool)');
uimenu(colormapmenu, 'Label', 'Color cube', 'Callback', 'colormap(colorcube)');
uimenu(colormapmenu, 'Label', 'HSV', 'Callback', 'colormap(hsv)');
uimenu(colormapmenu, 'Label', 'Pink', 'Callback', 'colormap(pink)');
uimenu(colormapmenu, 'Label', 'Prism', 'Callback', 'colormap(prism)');
uimenu(colormapmenu, 'Label', 'VGA', 'Callback', 'colormap(vga),colorbar,colorbar'); % make sure that the colorbar, if it exists, is correct
uimenu(colormapmenu, 'Label', 'Spring', 'Callback', 'colormap(spring)');
uimenu(colormapmenu, 'Label', 'Summer', 'Callback', 'colormap(summer)');
uimenu(colormapmenu, 'Label', 'Autumn', 'Callback', 'colormap(autumn)');
uimenu(colormapmenu, 'Label', 'Winter', 'Callback', 'colormap(winter)');
% And apply menu to handle(s)
% set(handle, 'uicontextmenu', cmenu);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function togglecolorbar(varargin)
% Do we have a colorbar now?
phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
if isempty(phch)
colorbar
else
delete(phch{1})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function colormaplength(varargin)
cmap = colormap;
oldlength = length(cmap);
clength = cellstr(num2str(oldlength));
new = inputdlg({'Enter new colormap length:'},'New colormap length', 1, clength);
if isempty(new) || ~isnumeric_str(new{1})
return
end
newlength = str2double(new{1});
oldsteps = linspace(0, 1, oldlength)';
newsteps = linspace(0, 1, newlength)';
newmap = zeros(newlength, 3);
for ii=1:3
% Interpolate over RGB spaces of colormap
newmap(:,ii) = min(max(interp1(oldsteps, cmap(:,ii), newsteps), 0), 1);
end
colormap(newmap);
% And update the colorbar, if one exists
phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
for ii=1:length(phch)
phud = get(phch{ii},'userdata');
if isfield(phud,'PlotHandle')
if isequal(gca, phud.PlotHandle)
colorbar
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function imagelimits(varargin)
lims = get(gca, 'CLim');
oldlower = num2str(lims(1));
oldupper = num2str(lims(2));
new = inputdlg({'Enter new lower limit:', 'Enter new upper limit:'}, ...
'New image limits', 1, {oldlower, oldupper});
if isempty(new)
return
end
if ~isnan(str2double(new{1})) && ~isnan(str2double(new{2}))
set(gca, 'CLim', [str2double(new{1}) str2double(new{2})]);
end
% And update the colorbar, if one exists
phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
if ~isempty(phch)
colorbar
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function titlecallback(varargin)
global S4M
old = get(gca, 'title');
oldstring = get(old, 'string');
if ischar(oldstring)
oldstring = cellstr(oldstring);
end
new = inputdlg('Enter new title:', S4M.title, 1, oldstring);
if ~isempty(new)
set(old, 'string', new);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function xaxiscallback(varargin)
global S4M
old = get(gca, 'xlabel');
oldstring = get(old, 'string');
if ischar(oldstring)
oldstring = cellstr(oldstring);
end
new = inputdlg('Enter new X-axis label:', S4M.title, 1, oldstring);
if ~isempty(new)
set(old, 'string', new);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function yaxiscallback(varargin)
global S4M
old = get(gca, 'ylabel');
oldstring = get(old, 'string');
if ischar(oldstring)
oldstring = cellstr(oldstring);
end
new = inputdlg('Enter new Y-axis label:', S4M.title, 1, oldstring);
if ~isempty(new)
set(old, 'string', new);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Menu callback
function call3d(varargin)
ax = gca;
%temp = double(get(gco, 'CData'));
handle=findobj(ax,'Tag','image_displayed');
temp=get(handle,'CData');
forient=get(gcf,'PaperOrientation');
switch forient
case 'landscape'
newfig=lfigure;
case 'portrait'
newfig=pfigure;
end
if isempty(get(get(ax, 'Parent'), 'Name'))
set(newfig, 'Name','3D view');
else
set(newfig, 'Name', [get(get(ax, 'Parent'), 'Name') ', 3D view']);
end
surf(temp, 'LineStyle', 'none');
camlight;
xlabel('X distance [pixels]');
ylabel('Y distance [pixels]');
axis('tight');
box on
|
github
|
Abakumov/MLIB-master
|
gui_patience.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/gui_patience.m
| 4,230 |
utf_8
|
98e2588976a4a5a369ddcb0da880b013
|
function varargout = gui_patience(varargin)
% Create a message window; the message does not halt execution of the program
% Written by: E. Rietsch: October 2003
% Last updated: July 22, 2007: "mlint" compliant
%
% varargout = gui_patience(varargin)
% INPUT
% varargin(1) cell containing string with message to be displayed
% varargin(2) optional cell with the handle of a figure; the message is
% centered on this figure
% OUTPUT
% varargout handle of the message window
%
% EXAMPLE
% msg_handle=gui_patience({'Please be patient ...'})
%
% GUI_PATIENCE M-file for gui_patience.fig
% GUI_PATIENCE, by itself, creates a new GUI_PATIENCE or raises the existing
% singleton*.
%
% H = GUI_PATIENCE returns the handle to a new GUI_PATIENCE or the handle to
% the existing singleton*.
%
% GUI_PATIENCE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI_PATIENCE.M with the given input arguments.
%
% GUI_PATIENCE('Property','Value',...) creates a new GUI_PATIENCE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_patience_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_patience_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui_patience
% Last Modified by GUIDE v2.5 19-Oct-2003 13:06:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_patience_OpeningFcn, ...
'gui_OutputFcn', @gui_patience_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes just before gui_patience is made visible.
function gui_patience_OpeningFcn(hObject, eventdata, handles, varargin) %#ok
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui_patience (see VARARGIN)
% Choose default command line output for gui_patience
handles.output = hObject;
% global S4M
set(hObject,'WindowStyle','normal','Name','Patience')
if ~isempty(varargin)
set(handles.patience,'String',varargin{1});
end
if length(varargin) > 1
try
centerfig(hObject,varargin{2})
catch
end
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui_patience wait for user response (see UIRESUME)
% uiwait(handles.figure1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Outputs from this function are returned to the command line.
function varargout = gui_patience_OutputFcn(hObject, eventdata, handles) %#ok
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.figure1;
drawnow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes during object creation, after setting all properties.
function patience_CreateFcn(hObject, eventdata, handles) %#ok
% hObject handle to patience (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Do nothing
|
github
|
Abakumov/MLIB-master
|
interpret_las3.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/interpret_las3.m
| 19,064 |
utf_8
|
09656a12a74dd413916e580e1779a596
|
function [wlog,aux]=interpret_las3(tlines,param)
% Interpret the lines of a file in LAS 3.0 format and create a well-log
% structure. Called by "read_las_file".
%
% Written by: E. Rietsch: December 16, 2006
% Last updated: January 31, 2007: Write parameters only if they are not empty
%
% [wlog,aux]=interpret_las3(tlines)
% INPUT
% tlines non-blank lines of the LAS 3.0 file (except for the first two lines)
% param parameters passed on by the calling program "read_las_file"
% OUTPUT
% wlog well log structure
% aux auxiliary information (nothing yet)
global S4M L_WPLOG_REPEAT
aux=[];
L_WPLOG_REPEAT=true; % Used to avoid repeating a specific message
% Wrap info
comp=split_line(tlines{1});
if strcmp(comp{1},'WRAP')
if ~strcmp(strtrim(comp{2}),'NO')
error('Line wrapping is not allowed in LAS 3.0')
end
else
error(['Line ',tlines{1},' should have wrap information.'])
end
% Delimiter info
comp=split_line(tlines{2});
if strcmp(comp{1},'DLM')
delim=strtrim(comp{2});
bool=ismember(delim,{'SPACE','COMMA','TAB'});
if ~any(bool)
error(['Unknown delimiter "',delim,'"'])
end
else
disp([' Line ',tlines{2}])
disp(' should have delimiter information.')
error('Abnormal termination')
end
[dummy,filename]=fileparts(S4M.filename);
wlog=struct('type','well_log','tag','unspecified','name',filename, ...
'first',[],'last',[],'step',[],'units','','null',-999.25, ...
'from',fullfile(S4M.pathname,S4M.filename));
% Section-start lines
index=find(~cellfun(@isempty,strfind(tlines','~'))); % Requires Matlab version > 7.04
% index=find(~cellfun('isempty',strfind(tlines','~')));
index=[index,length(tlines)+1];
for ii=1:length(index)-1
tline=tlines{index(ii)};
idx=strfind(tline,'|');
if isempty(idx)
temp=tokens(tline,' ');
% association=[];
else
temp1=tokens(tline,'|');
temp=tokens(temp1{1},' ');
% association=strtrim(temp1{2});
end
% temp=split_units_values(tlines{index(ii)});
switch_parameter=upper(temp{1});
switch switch_parameter
case '~WELL'
wlog=well_section_no1(wlog,tlines(index(ii)+1:index(ii+1)-1));
case '~PARAMETER'
wlog=parameter_section_no9(wlog,tlines(index(ii)+1:index(ii+1)-1));
case '~CURVE'
wlog=curve_section_no3(wlog,tlines(index(ii)+1:index(ii+1)-1));
case {'~ASCII','~LOG'}
% if ~isempty(association) && strcmpi(association,'CURVE')
wlog=data_section_no4(wlog,tlines(index(ii)+1:index(ii+1)-1),delim);
% end
otherwise
wlog=section_analysis_no6(wlog,tlines(index(ii)+1:index(ii+1)-1), ...
delim,switch_parameter,param);
end
end
wlog=fix_las_file_log(wlog);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=well_section_no1(wlog,tlines)
% Read well-section information
global S4M L_WPLOG_REPEAT
for ii=1:length(tlines)
comp=split_line(tlines{ii});
comp{2}=strtrim(comp{2});
switch lower(comp{1})
case 'strt'
comp1=split_units_values(comp{2});
wlog.first=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'stop'
comp1=split_units_values(comp{2});
wlog.last=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'step'
comp1=split_units_values(comp{2});
wlog.step=str2double(comp1{2});
units=unit_substitution(comp1{1});
if isempty(wlog.units)
wlog.units=units;
elseif ~strcmp(units,wlog.units)
error(['Depth units are incompatible: ',wlog.units,' and ',units])
end
case 'null'
wlog.null=str2double(comp{2});
case 'comp'
if ~isempty(comp{2})
wlog.company=comp{2};
end
case 'well'
if ~isempty(comp{2})
wlog.wellname=comp{2};
end
case 'loc'
if ~isempty(comp{2})
wlog.location=comp{2};
end
case 'fld'
if ~isempty(comp{2})
wlog.field=comp{2};
end
case 'ctry'
if ~isempty(comp{2})
wlog.country=comp{2};
end
% For Canada
case 'prov'
if ~isempty(comp{2})
wlog.province=comp{2};
end
case 'uwi'
if ~isempty(comp{2})
wlog.wellid=comp{2};
end
case 'lic'
wlog.license_number=comp{2};
% For US
case 'stat'
if ~isempty(comp{2})
wlog.state=comp{2};
end
case 'cnty'
if ~isempty(comp{2})
wlog.county=comp{2};
end
case 'api'
if ~isempty(comp{2})
wlog.api=comp{2};
end
% end of "For US"
case 'srvc'
if ~isempty(comp{2})
wlog.service=comp{2};
end
case 'date'
if ~isempty(comp{2})
wlog.date=comp{2};
end
% Either
case 'lat'
comp1=split_units_values(comp{2});
if ~isempty(comp{2}) || ~isempty(comp{2})
wlog.latitude=[comp1{2},' ',comp1{1}];
end
case 'long'
comp1=split_units_values(comp{2});
if ~isempty(comp{2}) || ~isempty(comp{2})
wlog.longitude=[comp1{2},' ',comp1{1}];
end
% or
case 'x'
if ~isempty(comp{2})
wlog.x=comp{2};
end
case 'y'
if ~isempty(comp{2})
wlog.y=comp{2};
end
case 'hzcs'
if ~isempty(comp{2})
wlog.hor_coord_system=comp{2};
end
% end of "or"
case 'gdat'
comp1=split_units_values(comp{2});
if ~isempty(comp{2}) || ~isempty(comp{2})
wlog.geodetic_datum=strtrim([comp1{2},' ',comp1{1}]);
end
case 'utm'
if ~isempty(comp{2})
wlog.utm=comp{2};
end
otherwise
% warning(['Unexpected parameter: ',comp{1}])
disp([' Unexpected keyword in ~WELL INFORMATION section: ',comp{1}])
if L_WPLOG_REPEAT
disp(' Assume that the ~PARAMETER INFORMATION line is missing.')
L_WPLOG_REPEAT=false;
end
wlog=parameter_section_no9(wlog,tlines(ii));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [descr,fmt]=extract_format_no2(str)
% Extract the format from the description section
idx1=strfind(str,'{');
if ~isempty(idx1)
idx2=strfind(str,'}');
if ~isempty(idx2) && idx2 > idx1+1
fmt=strtrim(str(idx1+1:idx2-1));
descr=strtrim(str(1:idx1-1));
else
warning(warnid,['Error in description: ',str])
descr=strtrim(str);
fmt=[];
end
else
descr=strtrim(str);
fmt=[];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=curve_section_no3(wlog,tlines)
% Read curve-section information
nlines=length(tlines);
wlog.curve_info=cell(nlines,5);
for ii=1:nlines
comp=split_line(tlines{ii});
comp1=split_units_values(comp{2});
[descr,fmt]=extract_format_no2(comp{3});
% If no format has been defined set it depending on the units of measurement
if isempty(fmt)
if isempty(comp1{1})
fmt='S';
else
fmt='F';
end
end
mnem=fix_mnem_no5(comp{1}); % Remove blanks and brackets from mnemonics
units=unit_substitution(comp1{1}); % Create standardized units of measurement
wlog.curve_info(ii,:)={mnem,units,descr,fmt,comp1{2}};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=data_section_no4(wlog,tlines,delim)
% Read data in data section
fmt0=wlog.curve_info(:,4);
[wlog,curves,bool,nlines,ncols]=data_section_no10(wlog,tlines,delim,fmt0);
if all(bool) % In case there are no strings
wlog.curves=cellfun(@str2double,curves); % Requires Matlab version > 7.04
% wlog.curves=cellfun('str2double',curves);
else % In case there are strings
wlog.curves=zeros(nlines,ncols);
idx=find(bool);
lidx=length(idx);
wlog.row_label_info=wlog.curve_info(~bool,:);
% Make mnemonics for string columns lower-case
wlog.row_label_info(:,1)=lower(wlog.row_label_info(:,1));
wlog.curves(:,1:length(idx))=cellfun(@str2double,curves(:,idx)); % Requires Matlab version > 7.04
% wlog.curves(:,1:length(idx))=cellfun('str2double',curves(:,idx));
wlog.curve_info=[wlog.curve_info(bool,:);wlog.row_label_info];
wlog.row_labels=curves(:,~bool);
for ii=1:size(wlog.row_label_info,1)
temp=unique(wlog.row_labels(:,ii));
nlabels=length(temp);
wlog.row_label_codes.(wlog.row_label_info{ii,1})= ...
[temp,num2cell((1:nlabels)')];
for jj=1:nlabels
bool1=~cellfun(@isempty,strfind(wlog.row_labels(:,ii),temp{jj})); % Requires Matlab version > 7.04
% bool1=~cellfun('isempty',strfind(wlog.row_labels(:,ii),temp{jj}));
wlog.curves(bool1,lidx+ii)=jj;
end
end
wlog.row_label_info=wlog.row_label_info(:,1:3);
end
wlog.curve_info=wlog.curve_info(:,1:3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mnem=fix_mnem_no5(mnem)
% Remove blanks and bracketed indices from mnemonic of LAS file
% e.g. mnemonic[3] ==> mnemonic_3
% Find blanks and replace by underscores
mnem=strrep(mnem,' ','_');
% Find bracketed indices and replace by underscores followed by indices
idx1=strfind(mnem,'[');
if isempty(idx1)
return
else
num=mnem(idx1+1:end-1);
mnem=[mnem(1:idx1-1),'_',num];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=section_analysis_no6(wlog,tlines,delim,switch_parameter,param)
% Check selected less-conventional sections
comp=tokens(switch_parameter,'_');
section=lower(comp{1}(2:end));
if (~isempty(param.section) && ismember({section},param.section)) || ...
strcmpi(param.section,'all')
switch upper(comp{2})
case 'PARAMETER'
wlog=info4section_no7(wlog,tlines,section,'parameters');
case 'DEFINITION'
wlog=info4section_no7(wlog,tlines,section,'info');
case 'DATA'
wlog=data4section_no8(wlog,tlines,delim,section);
otherwise
% One should never get here
end
else
if length(comp) == 1 || strcmp(upper(comp{2}),'DATA')
disp([' Section "',section,'" ignored.'])
keyboard
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=info4section_no7(wlog,tlines,first_name,last_name)
% Read parameter-section information
field=[first_name,'_',last_name];
nlines=length(tlines);
wlog.(field)=cell(nlines,5);
for ii=1:nlines
comp=split_line(tlines{ii});
comp1=split_units_values(comp{2});
[descr,fmt]=extract_format_no2(comp{3});
% If no format has been defined set it depending on the units of measurement
if isempty(fmt)
if isempty(comp1{1})
fmt='S';
else
fmt='F';
end
end
mnem=fix_mnem_no5(comp{1}); % Remove blanks and brackets from mnemonics
units=unit_substitution(comp1{1}); % Create standardized units of measurement
wlog.(field)(ii,:)={mnem,units,descr,fmt,comp1{2}};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=data4section_no8(wlog,tlines,delim,first_name)
% Read data in data section
%label=[first_name,'_label']; % Field name for label
data=[first_name,'_data']; % Field name for data
label_info=[first_name,'_info']; % Field name for info
fmt0=wlog.(label_info)(:,4);
[wlog,curves,bool]=data_section_no10(wlog,tlines,delim,fmt0);
%{
nlines=length(tlines);
ncols=length(fmt0);
nerrors=0;
% Convert cell vector of lines into cell array of matrix elements
curves=cell(nlines,ncols);
% Set the delimiter
switch lower(delim)
case 'blank'
sep=' ';
% Remove consecutive blanks so that they are not interpreted as
% indicating missing data values
tlines=remove_consecutive_blanks(tlines);
case 'tab';
sep=sprintf('\t');
case 'comma'
sep=',';
otherwise
error([' Unknown delimiter :',delim])
end
for ii=1:nlines
temp=tokens(tlines{ii},sep);
ltemp=length(temp);
if ltemp == ncols
curves(ii,:)=temp;
elseif ltemp > ncols % Combine strings
index=find(~cellfun(@isempty,strfind(temp,'"'))); % Requires Matlab version > 7.04
% index=find(~cellfun('isempty',strfind(temp,'"')));
if ~mod(length(index),2) == 0
nerrors=nerrors+1;
if nerrors <= 10
disp([' Problem with a string in line ',num2str(ii),' of the data'])
disp(' String is not enclosed in double quotes.')
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
else
for jj=1:2:length(index)
temp1=cell2str(temp(index(jj):index(jj+1)),', ');
temp{index(jj)}=temp1(2:end-1);
temp(index(jj)+1:index(jj+1))=[];
end
end
if length(temp) ~= ncols
nerrors=nerrors+1;
if nerrors <= 10
disp([' Problem with a string in data line ',num2str(ii)])
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
else
curves(ii,:)=temp;
end
else
nerrors=nerrors+1;
if nerrors <= 10
disp([' There are fewer than ',num2str(ncols),' data values in line ',num2str(ii)])
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
end
end
% Find columns with strings
bool=true(1,ncols);
for ii=1:ncols
if strcmpi(fmt0{ii}(1),'S') || ...
(length(fmt0{ii}) > 1 && strcmpi(fmt0{ii}(1:2),'AS'))
bool(ii)=false;
end
end
%}
if all(bool) % In case there are no strings
wlog.(data)=cellfun(@str2double,curves); % Requires Matlab version > 7.04
% wlog.(data)=cellfun('str2double',curves);
else % In case there are strings
wlog.(data)=[num2cell(cellfun(@str2double,curves(:,bool))),curves(:,~bool)]; % Requires Matlab version > 7.04
% wlog.(data)=[num2cell(cellfun('str2double',curves(:,bool))),curves(:,~bool)];
end
wlog.(label_info)=wlog.(label_info)(:,1:3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=parameter_section_no9(wlog,tlines)
% Read parameter-section information pf LAS 3.0 file
nlines=length(tlines);
wlog.parameter_info=cell(nlines,3);
ik=0;
for ii=1:nlines
comp=split_line(tlines{ii});
if isempty(comp{4}) % No vertical bar
comp1=split_units_values(comp{2});
values=str2num(comp1{2}); %#ok More than one numeric value is possible
if ~isempty(values)
[descr,fmt]=extract_format_no2(comp{3});
% If no format has been defined set it depending on the units of measurement
if isempty(fmt)
if isempty(comp1{1})
fmt='S';
else
fmt='F';
end
end
mnem=lower(fix_mnem_no5(comp{1})); % Remove blanks and brackets from mnemonics
units=unit_substitution(comp1{1}); % Create standardized units of measurement
if ~strcmpi(fmt(1),'S')
ik=ik+1;
wlog.parameter_info(ik,:)={mnem,units,descr};
wlog.(mnem)=values;
else
% Disregard parameters that have no numeric values
end
end
else
% Disregard parameter definitions that refer to different runs
end
end
if ik > 0
wlog.parameter_info=wlog.parameter_info(1:ik,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [wlog,curves,bool,nlines,ncols]=data_section_no10(wlog,tlines,delim,fmt0)
% Used in "data_section_no4" and in "data4section_no8"
nlines=length(tlines);
ncols=length(fmt0);
nerrors=0;
% Convert cell vector of lines into cell array of matrix elements
curves=cell(nlines,ncols);
% Set the delimiter
switch lower(delim)
case 'blank'
sep=' ';
% Remove consecutive blanks so that they are not interpreted as
% indicating missing data values
tlines=remove_consecutive_blanks(tlines);
case 'tab';
sep=sprintf('\t');
case 'comma'
sep=',';
otherwise
error([' Unknown delimiter :',delim])
end
for ii=1:nlines
temp=tokens(tlines{ii},sep);
ltemp=length(temp);
if ltemp == ncols
curves(ii,:)=temp;
elseif ltemp > ncols % Combine strings
index=find(~cellfun(@isempty,strfind(temp,'"'))); % Requires Matlab version > 7.04
% index=find(~cellfun('isempty',strfind(temp,'"')));
if ~mod(length(index),2) == 0
nerrors=nerrors+1;
if nerrors <= 10
disp([' Problem with a string in line ',num2str(ii),' of the data'])
disp(' String is not enclosed in double quotes.')
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
else
for jj=1:2:length(index)
temp1=cell2str(temp(index(jj):index(jj+1)),', ');
temp{index(jj)}=temp1(2:end-1);
temp(index(jj)+1:index(jj+1))=[];
end
end
if length(temp) ~= ncols
nerrors=nerrors+1;
if nerrors <= 10
disp([' Problem with a string in data line ',num2str(ii)])
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
else
curves(ii,:)=temp;
end
else
nerrors=nerrors+1;
if nerrors <= 10
disp([' There are fewer than ',num2str(ncols),' data values in line ',num2str(ii)])
disp(tlines{ii})
if nerrors == 10
disp(' Any additional errors are not displayed')
end
end
end
end
% Find columns with strings
bool=true(1,ncols);
for ii=1:ncols
if strcmpi(fmt0{ii}(1),'S') || ...
(length(fmt0{ii}) > 1 && strcmpi(fmt0{ii}(1:2),'AS'))
bool(ii)=false;
end
end
|
github
|
Abakumov/MLIB-master
|
cseismic_scrollbar_menu.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/cseismic_scrollbar_menu.m
| 5,079 |
utf_8
|
b80249f4639f58be73e45931e5c3f316
|
function menu_handle=cseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% Function creates a menu button on the figure with handle "figure_handle"
% that allows one to add scroll bars to a color seismic plot
%
% Written by: E. R., August 22, 2005
% Last updated: November 5, 2005: Save axis limits before user querry
%
% menu_handle=cseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% seismic seismic data set to be displayed; needed to provide limits for
% the scrollbar boxes
% plotdir plot direction
% OUTPUT
% menu_handle handle of the menu button created by this function
ntr=size(seismic.traces,2);
tmax=seismic.last-seismic.first;
tmin=3*seismic.step;
% Create menu button
menu_handle=uimenu(figure_handle,'Label','Add scrollbars','ForegroundColor','b');
set(menu_handle,'Callback',{@seismic_scrollbar,gca,menu_handle,ntr,tmin,tmax,plotdir});
if nargout == 0
clear menu_handle
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic_scrollbar(hObject,evdata,axis_handle,menu_handle,ntr,tmin,tmax,plotdir) %#ok
label=get(menu_handle,'Label');
if strcmp(label,'Add scrollbars')
set(menu_handle,'Label','Remove scrollbars');
else
reset_scroll_button(axis_handle,menu_handle)
set(menu_handle,'Label','Add scrollbars');
return
end
zoom out
% Prompt user for time and trace range
prompt={'Enter the number of traces to display:','Enter the time range to display:'};
name='Scroll parameters';
numlines=1;
defaultanswer=mat2cellstrings([min(50,ntr),min(500,tmax)]);
ier1=true;
ier2=true;
% Save present axis limits
v=axis;
setappdata(menu_handle,'axislimits',v)
while any(ier1) || any(ier2)
answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
reset_scroll_button(axis_handle,menu_handle)
return
end
[ntraces,ier1]=check_numeric(answer{1},'Number of traces',{'minmax',[1,1]}, ...
{'bounds',1,ntr});
[timerange,ier2]=check_numeric(answer{2},'Time range',{'minmax',[1,1]}, ...
{'bounds',tmin,tmax});
end
% This reduces flickering when the axis is updated
set(gcf,'doublebuffer','on');
% Set appropriate axis limits and settings
% set(axis_handle,'xlim',[v(1),v(1)+ntraces],'ylim',[v(3),v(3)+timerange]);
% Generate constants for use in uicontrol initialization
pos=get(axis_handle,'position');
dx=(v(2)-v(1))/ntr;
xmin=dx*round(2*v(1)/dx)/2;
xmax=dx*round(2*v(2)/dx)/2;
ymin=round(v(3));
ymax=round(v(4));
xtraces=ntraces*(xmax-xmin)/ntr;
if ntraces < ntr
% Create a slider below the x-axis
xsliderpos=[pos(1), pos(2)-0.030, pos(3), 0.029];
sstep1=max(1/(ntr-ntraces),0.01);
if strcmp(plotdir,'l2r')
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmin, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
else
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmax-xtraces, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
end
set(hxslider,'Callback',{@scrollx,axis_handle,xtraces,xmin,xmax,plotdir})
set(gca,'XLim',[xmin,xmin+xtraces])
no_xscrollbar=false;
else
hxslider=1.1;
no_xscrollbar=true;
end
if timerange < tmax
ysliderpos=[pos(1)+pos(3)+0.002, pos(2), 0.018, pos(4)];
sstep2=min(1,timerange/(ymax-ymin));
hyslider=uicontrol('style','slider',...
'units','normalized','Position',ysliderpos,...
'min',ymin,'max',ymax-timerange,'value',ymax-timerange, ...
'SliderStep',[max(sstep2/10,8/(ymax-ymin)),sstep2]);
set(hyslider,'Callback',{@scrolly,axis_handle,timerange,ymin,ymax})
set(gca,'YLim',[ymin, ymin+timerange])
no_yscrollbar=false;
else
hyslider=1.1;
no_yscrollbar=true;
end
setappdata(menu_handle,'sliders',[hxslider,hyslider])
if no_xscrollbar && no_yscrollbar
set(menu_handle,'Label','Add scrollbars');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrollx(hObject,evdata,axis_handle,ntraces,xmin,xmax,plotdir) %#ok
if strcmp(plotdir,'l2r')
xlimits=get(gcbo,'value')+[0,ntraces];
else
xlimits=xmax-get(gcbo,'value')+[-ntraces,0]+xmin;
end
set(axis_handle,'XLim',xlimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrolly(hObject,evdata,axis_handle,timerange,ymin,ymax) %#ok
ylimits=ymax-get(gcbo,'value')+[-timerange,0]+ymin;
%ylimits=ylimits;
set(axis_handle,'YLim',ylimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function reset_scroll_button(axis_handle,menu_handle)
set(menu_handle,'Label','Add scrollbars');
sliders=getappdata(menu_handle,'sliders');
try
delete(sliders(1))
catch
end
try
delete(sliders(2))
catch
end
axislimits=getappdata(menu_handle,'axislimits');
axis(axis_handle,axislimits)
|
github
|
Abakumov/MLIB-master
|
histoplot1.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/histoplot1.m
| 7,021 |
utf_8
|
de1fa709891c0c1193430cb181c83b32
|
function aux=histoplot1(x,edges,varargin)
% Histogram plot (1-D)
%
% Written by: E. Rietsch: September 19, 2003
% Last updated: April 10, 2008: Generalize plotting of percentile lines
%
% aux=histoplot1(x,edges,varargin)
% INPUT
% x column vector of samples
% edges either the vector of edges for "x"
% or the number of bins (positive integer)
% or the bin size [negative; bin size, then, is abs(edges)].
% In the second case the first bin starts at the smallest sample of
% "x" and the last bin ends at the largest sample of "x";
% in the third case the first bin starts at the smallest sample of
% "x" - bin size and the last bin ends at the largest sample
% of "x" + bin size
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'xinfo' three-element cell array; all elements are strings; first is a
% mnemonic (for cursor tracking), second units of measurement,
% the third string is the x-axis label
% Default: {'xinfo',{'x','n/a','x'}}
% 'yinfo' three-element cell array; all elements are strings; first is a
% mnemonic (for cursor tracking), second units of measurement,
% the third string is the x-axis label
% Default: {'yinfo',{'counts','n/a','Counts'}}
% 'style' possible values are: 'line' (line representation of histogram)
% and 'bar' (bar representation of histogram)
% Default: {'style','line'}
% 'linewidth' only used if "style" is 'line'; width of line
% Default: {'linewidth',3}
% 'percentiles' percentile locations that should be marked by vertical
% lines; 1 or 3 percentile locations are supported.
% No percentile lines if empty.
% Default: {'percentiles',[10,50,90]}
% 'colors' line color
% Default: {'colors','r'}
% 'scale' scale bars to represent percent
% Default: {'scale','no'}
% 'width' specifies the width of the bars. Values > 1, produce
% overlapped bars (only used if keyword "style" is 'bar').
% Default: {'width',1}
% OUTPUT
% aux structure with fields 'handle' (handle of histogram curve) and
% 'edges' (edges of histogram bins)
% 'nn' (histogram values; e.g. "mystairs(edges,nn)")
% 'percentile_handles (if percentiles are plotted)
%
% EXAMPLE
% x=randn(10000,1);
% lfigure
% histoplot1(x,11)
% lfigure
% histoplot1(x,(-4.25:0.5:4.25),{'style','bar'})
% UPDATE HISTORY
% August 31, 2007: add keyword 'width', bug fix in bar plot
global S4M
% Set defaults of input parameters
param.xinfo={'x','n/a','x'};
param.yinfo=[];
param.style='line';
param.linewidth=3;
param.colors='r';
param.percentiles=[10,50,90];
param.scale='no';
param.width=1;
% Replace defaults bu actual input paramters
param=assign_input(param,varargin);
if length(param.xinfo) == 1
param.xinfo=param.xinfo{1};
end
if isempty(param.yinfo)
switch param.scale
case 'yes'
param.yinfo={'counts','n/a','%'};
case 'no'
param.yinfo={'counts','n/a','Sample count'};
otherwise
error(['Unknown scale option: ',param.scale])
end
else
if length(param.yinfo) == 1
param.yinfo=param.yinfo{1};
end
end
% userdata=get(gca,'UserData');
if length(edges) == 1
if edges > 0
edges=linspace(min(x(:)),max(x(:))*(1+2*eps),edges+1)';
else
edges=equal_bins_from_samples(min(x(:)),max(x(:)),-edges);
end
end
% Compute histogram
x=x(:);
nn=histc(x,edges);
if strcmpi(param.scale,'yes')
nn=nn*100/sum(nn);
end
if strcmpi(param.style,'bar')
hs=bar(centers_from_edges(edges),nn(1:end-1),param.width,param.colors);
if S4M.matlab_version < 7.2
% Get rid of asterisks along the x-axis
line_handle=findobj(gca,'Type','line'); % Use the "findobj" function to
% get a handle to the line object
delete(line_handle); % Delete the line object
clear line_handle; % Clear the handle
% reference variable
end
lhs=length(hs);
if lhs > 1
for ii=1:length(hs)
set(hs(ii),'FaceColor',get_color(ii))
end
else
set(hs,'FaceColor',param.colors)
end
else
ntr=size(nn,2);
if ntr == 1
hs=mystairs(edges,nn(1:end-1));
set(hs,'LineWidth',param.linewidth,'Color',param.colors)
else
for ii=1:ntr
hs=mystairs(edges,nn(:,ii));
set(hs,'LineWidth',param.linewidth,'Color',get_color(ii))
hold on
end
end
end
grid on
xlabel(info2label(param.xinfo));
ylabel(info2label(param.yinfo));
bgGray % Create gray background
% Implement cursor tracking
initiate_2d_tracking(param.xinfo,param.yinfo)
% Save handles for output (if requested)
if nargout == 1
aux.handle=hs;
aux.edges=edges;
aux.nn=nn;
end
% Plot percentile lines (if requested)
if ~isempty(param.percentiles)
if iscell(param.percentiles)
param.percentiles=cell2mat(param.percentiles);
end
param.percentiles=sort(param.percentiles);
loc=percentiles_from_samples1d(x,param.percentiles);
if strcmp(param.style,'bar')
handles=plot_percentile_lines_no1(loc,param.colors,4,[]);
handles1=plot_percentile_lines_no1(loc,'white',1.6,[]);
else
handles=plot_percentile_lines_no1(loc,param.colors,2,[]);
end
if nargout == 1
aux.percentile_handles=handles;
if exist('handles1','var')
aux.percentile_handles1=handles1;
end
% aux.percentile_handles1=handles1;
aux.percentiles=param.percentiles;
aux.percentile_locations=loc;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles=plot_percentile_lines_no1(loc,color,linewidth,linestyles)
nloc=length(loc);
handles=zeros(nloc,1);
if mod(nloc,2) == 1 % odd
mloc=(nloc+1)/2;
temp=mygrid(loc(mloc),'v',color,linewidth,get_linestyle(1,linestyles));
handles(1)=temp.handles;
for ii=1:mloc-1
temp=mygrid(loc(mloc+ii),'v',color,linewidth,get_linestyle(ii+1,linestyles));
handles(mloc+ii)=temp.handles;
temp=mygrid(loc(mloc-ii),'v',color,linewidth,get_linestyle(ii+1,linestyles));
handles(mloc-ii)=temp.handles;
end
else % even
for ii=1:nloc
temp=mygrid(loc(ii),'v',color,linewidth,get_linestyle(ii+1,linestyles));
handles(ii)=temp.handles;
end
end
|
github
|
Abakumov/MLIB-master
|
read_traces_of_segy_file.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/read_traces_of_segy_file.m
| 7,306 |
utf_8
|
ae9bef05ec52cc2dce0ab876d9b823dc
|
function [seismic,headers]=read_traces_of_segy_file(fid,seismic,param,parameters,max_no_of_traces)
% Read traces of the open SEG-Y file with file ID "fid". The file must have
% been opened with function "open_segy_file4reading". This function also
% provides the input arguments for this function.
% For internal use in "read_segy_file" and "read_segy_file_traces".
%
% Written by: E. Rietsch: January 7, 2007
% Last updated: April 5, 2009: Account for single-precision memory requirements
%
% [seismic,headers]=read_traces_of_segy_file(fid,seismic,param,parameters,max_no_of_traces)
% INPUT
% fid file identifier of the SEG-file
% seismic
% param
% parameters
% max_no_of_traces maximum number of traces to read
% OUTPUT
% seismic input seismic dataset with headers and traces read from file
% UPDATE HISTORY
% November 7, 2008: Fix typo in function name
% November 19, 2008: Fix typo on line 37 (Ravi)
param.ntraces=max_no_of_traces;
% Reserve space for traces and headers
[ntraces,isall,param]=calculate_space_requirements_no8(param);
% Read headers and trace values
if isall % All requested traces fit into memory
[seismic.traces,headers]=read_headers_and_traces_no9(fid, ...
parameters.idx4times,ntraces, ...
parameters.indices,parameters.true4four,param,parameters.constraint_info);
elseif ischar(param.traces) % Possibly not enough memory for all traces; but
% logical constraints on traces to read may allow
% one to read all requested traces
[seismic.traces,headers]=read_headers_and_traces_no9(fid,parameters.idx4times, ... % Ravi
ntraces,indices,true4four,param,constraint_info);
if size(seismic.traces,2) == ntraces
mywarning('It is possible that not all requested seismic traces have been read.')
end
% fclose(fid);
else
disp(' Insufficient memory to read all requested traces.')
disp([' At most ',num2str(ntraces),' can be read.'])
if ~ispc
disp('Check if the memory for traces (keyword "max_mem") can be increased.')
end
fclose(fid);
error('Abnormal termination.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ntraces,isall,param]=calculate_space_requirements_no8(param)
% Compute the amount of space required to store headers and traces
global S4M
if ~isempty(param.max_mem)
param.max_mem=fix(param.max_mem*131072);
else
if ispc
switch S4M.precision
case 'double'
param.max_mem=fix(memblock/8); % Greatest memory block available
case 'single'
param.max_mem=fix(memblock/4); % Greatest memory block available
otherwise
error(['Unknown precision: ',S4M.precision])
end
else
param.max_mem=4.0e9;
end
end
if isempty(param.traces) || ischar(param.traces)
if param.ntraces*param.nsamp <= param.max_mem
ntraces=param.ntraces;
isall=true;
else
ntraces=fix(param.max_mem/param.nsamp);
if ntraces == 0
error(' Not enough memeory for even a single trace.')
end
isall=false;
end
elseif isnumeric(param.traces)
param.traces=param.traces(param.traces > 0 & param.traces <= param.ntraces);
ntraces=length(param.traces);
if ntraces*param.nsamp <= param.max_mem
isall=true;
else
ntraces=fix(param.max_mem/param.nsamp);
isall=false;
end
else
error('Illegal parameter for keyword "traces".')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [traces,headers]=read_headers_and_traces_no9(fid,idx4times,ntraces, ...
indices,true4four,param,constraint_info)
% Read headers and traces
% INPUT
% fid file identifier
% idx4times index of the time samples to keep
% ntraces maximum number of traces to read
% param input parameters for read_segy_file
% OUTPUT
% traces matrix with traces read
% headers integer matrix with headers saved
headers=zeros(param.nheaders,ntraces,'int32');
precision=param.precision;
iloc=ftell(fid);
if strcmpi(param.format,'ibm')
traces=zeros(param.nsamp,ntraces,'uint32');
else
traces=zeros(param.nsamp,ntraces,'single');
end
% No trace constaints; read all traces
if isempty(param.traces)
for ii=1:ntraces
hh4=fread(fid,60,'int32');
fseek(fid,iloc,'bof');
hh2=fread(fid,120,'int16');
if isempty(hh2) % End of file reached
traces(:,ii:end)=[];
headers(:,ii:end)=[];
break
else
headers(true4four,ii)=hh4(indices(true4four));
end
headers(~true4four,ii)=hh2(indices(~true4four));
temp=fread(fid,param.no_samples,precision);
traces(:,ii)=temp(idx4times);
iloc=ftell(fid);
end
% Traces to read are specified via trace numbers
elseif isnumeric(param.traces)
inc=240+4*param.no_samples;
iloc0=iloc;
for ii=1:ntraces
iloc=iloc0+(param.traces(ii)-1)*inc;
fseek(fid,iloc,'bof');
hh4=fread(fid,60,'int32');
fseek(fid,iloc,'bof');
hh2=fread(fid,120,'int16');
headers(true4four,ii)=hh4(indices(true4four));
headers(~true4four,ii)=hh2(indices(~true4four));
temp=fread(fid,param.no_samples,precision);
traces(:,ii)=temp(idx4times);
end
% Traces to read are defined via a logical expression
else
ik=0;
temp_headers=zeros(param.nheaders,1,'int32');
for ii=1:param.ntraces
hh4=fread(fid,60,'int32');
fseek(fid,iloc,'bof');
hh2=fread(fid,120,'int16');
temp_headers(true4four)=hh4(indices(true4four));
temp_headers(~true4four)=hh2(indices(~true4four));
temp=fread(fid,param.no_samples,precision);
if requested_header_no11(temp_headers,constraint_info,ii,param.traces)
ik=ik+1;
if ik > ntraces
disp(' At least one more trace meets trace constraints but cannot be stored because')
disp(' of memory limitation.')
mywarning('Trace reading terminated prematurely.')
break
end
traces(:,ik)=temp(idx4times);
headers(:,ik)=temp_headers;
end
iloc=ftell(fid);
end
headers(:,ik+1:end)=[];
traces(:,ik+1:end)=[];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bool=requested_header_no11(headers,constraint_info,trace_no, ...
expression) %#ok input arguments "headers" and
% "trace_no" may be needed in "expression"
% Output logical variable. "bool" is true if the header value satisfied the
% constraint specified in param.traces
nheaders=size(constraint_info,1);
if constraint_info{nheaders,2} == 0
nheaders=nheaders-1;
end
for ii=1:nheaders
eval([constraint_info{ii,1},'=headers(',constraint_info{ii,2},');']);
end
try
bool=eval(expression);
catch
disp(' Logical expresession for trace selection:')
disp([' ',expression])
disp(' has errors. Misspelled headers, unknown functions and/or a bad syntax may be at fault.')
ple % Print last error
myerror(' Abnormal terminantion')
end
|
github
|
Abakumov/MLIB-master
|
finalize_seismic_dataset.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/finalize_seismic_dataset.m
| 2,939 |
utf_8
|
1e51b66c8719f9fa1c644d61a0d1a826
|
function seismic=finalize_seismic_dataset(seismic,headers,param,parameters)
% Called from "read_segy_file"
global S4M
if S4M.history
seismic=s_history(seismic,'add',seismic.from);
end
% Convert to IEEE format if necesssary
if strcmpi(param.format,'ibm')
if strcmpi(S4M.precision,'single')
seismic.traces=ibm2single(seismic.traces);
else
seismic.traces=ibm2double(seismic.traces);
end
end
if isempty(seismic.traces)
msgdlg([' Alert: No seismic traces read from file ',seismic.from])
end
if seismic.aux_per_record == 0
seismic=rmfield(seismic,'aux_per_record');
end
seismic.null=[];
% Use requested precision
if strcmpi(S4M.precision,'single')
seismic=single(seismic); % Convert other numeric fields to single-precision
else
seismic=double(seismic);
end
% Remove default headers that are all zeros; convert headers from
% integers to single-precision floats (if possible)
[seismic.header_info,seismic.headers,lagindex]= ...
fix_headers_no10(headers,parameters.header_info);
% Remove fields "headers" and "header_info" if they are empty
if isempty(seismic.header_info) || isempty(seismic.headers)
seismic=rmfield(seismic,{'header_info','headers'});
end
% Apply lag if it is not zero and should not be ignored
if ~isempty(lagindex) && ~param.ignoreshift
disp('Seismic data shifted since header "lag" is not identically zero.')
disp(['Lag varies from ',num2str(min(seismic.headers(lagindex,:))),' to ', ...
num2str(max(seismic.headers(lagindex,:)))])
seismic=s_shift(seismic,{'shifts',seismic.headers(lagindex,:)});
end
seismic.fp_format_of_segy_file=param.format;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [header_info,headers,lagindex]=fix_headers_no10(headers,header_info)
% Remove headers that are read by default if they are all zero; user-specified
% headers are kept
global S4M
% Remove header mnemonics that contain only zeros
nh=size(headers,1);
index=find(~cell2num(header_info(:,6)));
bool=false(nh,1);
for ii=length(index):-1:1
bool(ii)=all(headers(ii,:) == 0);
end
header_info(bool,:)=[];
header_info(:,4:end)=[];
headers(bool,:)=[];
% Check if header "lag" still exists
lagindex=find(ismember(header_info(:,1),'lag'));
% Convert from integer to float
if strcmpi(S4M.precision,'single')
% Convert header from int32 to single (if possible without loss)
bool=any(headers ~= int32(single(headers)),2);
if any(bool)
% mnems=header_info(bool,1);
disp([' Headers: ',cell2str(header_info(bool,1),', ')])
disp(' cannot be converted to single precision without loss of accuracy.')
alert('All headers have been saved in double precision.')
headers=double(headers);
else
headers=single(headers);
end
else
headers=double(headers);
end
|
github
|
Abakumov/MLIB-master
|
remove_consecutive_blanks.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/remove_consecutive_blanks.m
| 1,231 |
utf_8
|
2d4f2ace3ea0c01a0f2f717f17ec0525
|
function str=remove_consecutive_blanks(str)
% Remove consecutive blanks in the input string (or a cell vector of strings)
% and replace them by a single blank.
% Also remove any leading and trailing blanks.
%
% Written by: E. Rietsch: December 19, 2006
% Last updated:
%
% str=remove_consecutive_blanks(str)
% INPUT
% str string or cell vector of strings
% OUTPUT
% str input string (or cell vector) with consecutive blanks replaced
% by a single blank
%
% EXAMPLES
% str=remove_consecutive_blanks(' 1 2 3 5 7 ')
% cstr=remove_consecutive_blanks({' 1 2 3 5 7 ','a r ggg h kkk u '})
if iscell(str)
for ii=1:length(str)
str{ii}=rcb(strtrim(str{ii}));
end
else
str=rcb(strtrim(str));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Nested function
function str=rcb(str)
lstr0=length(str);
str=strrep(str,' ',' ');
lstr=length(str);
while lstr < lstr0 && lstr > 0
lstr0=lstr;
str=strrep(str,' ',' ');
lstr=length(str);
end
end % End of nested function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end % End of function
|
github
|
Abakumov/MLIB-master
|
wseismic_scrollbar_menu_item.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/wseismic_scrollbar_menu_item.m
| 5,179 |
utf_8
|
4dac21bb80442d7d124af2e9668a2dac
|
function menu_handle=wseismic_scrollbar_menu(figure_handle,options_menu_handle,seismic,plotdir)
% Function creates a menu button on the figure with handle "figure_handle" (or
% the current figure) that allows one to add scroll bars to a wiggle seismic plot
%
% Written by: E. Rietsch, August 22, 2005
% Last updated: November 5, 2005: Save axis limits before user querry
%
% menu_handle=wseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% seismic seismic dataset to be displayed; needed to provide limits for the scrollbar boxes
% plotdir plot direction
% OUTPUT
% menu_handle handle of the menu button created by this function
ntr=size(seismic.traces,2);
tmax=seismic.last-seismic.first;
tmin=min(3*seismic.step,tmax);
if tmin > tmax
tmin=tmax;
end
% Create menu button
menu_handle=uimenu(options_menu_handle,'Label','Add scrollbars','ForegroundColor','b');
set(menu_handle,'Callback',{@seismic_scrollbar,gca,menu_handle,ntr,tmin,tmax,plotdir});
if nargout == 0
clear menu_handle
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic_scrollbar(hObject,evdata,axis_handle,menu_handle,ntr,tmin,tmax,plotdir) %#ok
label=get(menu_handle,'Label');
if strcmp(label,'Add scrollbars')
set(menu_handle,'Label','Remove scrollbars');
else
reset_scroll_button(axis_handle,menu_handle)
return
end
zoom out
% Prompt user for time and trace range
prompt={'Enter the number of traces to display:','Enter the time range to display:'};
name='Scroll parameters';
numlines=1;
defaultanswer=mat2cellstrings([min(50,ntr),min(500,tmax)]);
ier1=true;
ier2=true;
% Save present axis limits
v=axis;
setappdata(menu_handle,'axislimits',v)
while any(ier1) || any(ier2)
answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
reset_scroll_button(axis_handle,menu_handle)
return
end
[ntraces,ier1]=check_numeric(answer{1},'Number of traces',{'minmax',[1,1]}, ...
{'bounds',1,ntr});
% keyboard
[timerange,ier2]=check_numeric(answer{2},'Time range',{'minmax',[1,1]}, ...
{'bounds',tmin,tmax});
end
% This reduces flickering when the axis is updated
set(gcf,'doublebuffer','on');
% Set appropriate axis limits and settings
% set(axis_handle,'xlim',[v(1),v(1)+ntraces],'ylim',[v(3),v(3)+timerange]);
% Generate constants for use in uicontrol initialization
pos=get(axis_handle,'position');
%xmin=round(v(1));
%xmax=round(v(2));
xmin=v(1);
xmax=v(2);
ymin=round(v(3));
ymax=round(v(4));
if ntr > 1
xtraces=ntraces*(xmax-xmin)/(ntr-1);
else
xtraces=ntraces;
end
if ntraces < ntr
ntraces=ntraces+1;
% Create a slider below the x-axis
xsliderpos=[pos(1), pos(2)-0.030, pos(3), 0.029];
sstep1=max(1/(ntr-ntraces+1),0.01);
if strcmp(plotdir,'l2r')
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmin, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
else
hxslider=uicontrol('style','slider',...
'units','normalized','Position',xsliderpos,...
'min',xmin,'max',xmax-xtraces,'value',xmax-xtraces, ...
'SliderStep',[sstep1,min(1,10*sstep1)]);
end
set(hxslider,'Callback',{@scrollx,axis_handle,xtraces,xmin,xmax,plotdir})
set(gca,'XLim',[xmin,xmin+xtraces])
no_xscrollbar=false;
else
hxslider=1.1;
no_xscrollbar=true;
end
if timerange < tmax
ysliderpos=[pos(1)+pos(3)+0.003, pos(2), 0.018, pos(4)];
sstep2=min(1,timerange/(ymax-ymin));
hyslider=uicontrol('style','slider',...
'units','normalized','Position',ysliderpos,...
'min',ymin,'max',ymax-timerange,'value',ymax-timerange, ...
'SliderStep',[max(sstep2/10,8/(ymax-ymin)),sstep2]);
set(hyslider,'Callback',{@scrolly,axis_handle,timerange,ymin,ymax})
set(gca,'YLim',[ymin, ymin+timerange])
no_yscrollbar=false;
else
hyslider=1.1;
no_yscrollbar=true;
end
setappdata(menu_handle,'sliders',[hxslider,hyslider])
if no_xscrollbar && no_yscrollbar
set(menu_handle,'Label','Add scrollbars');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrollx(hObject,evdata,axis_handle,ntraces,xmin,xmax,plotdir) %#ok
if strcmp(plotdir,'l2r')
xlimits=get(gcbo,'value')+[0,ntraces];
else
xlimits=xmax-get(gcbo,'value')+[-ntraces,0]+xmin;
end
set(axis_handle,'XLim',xlimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scrolly(hObject,evdata,axis_handle,timerange,ymin,ymax) %#ok
ylimits=ymax-get(gcbo,'value')+[-timerange,0]+ymin;
%ylimits=ylimits;
set(axis_handle,'YLim',ylimits)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function reset_scroll_button(axis_handle,menu_handle) %#ok
set(menu_handle,'Label','Add scrollbars');
sliders=getappdata(menu_handle,'sliders');
try
delete(sliders(1))
catch
end
try
delete(sliders(2))
catch
end
axislimits=getappdata(menu_handle,'axislimits');
axis(axis_handle,axislimits)
|
github
|
Abakumov/MLIB-master
|
curve_indices.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/curve_indices.m
| 2,714 |
utf_8
|
f29cf2b0f2baba31d2c3a3127b8e5158
|
function indices=curve_indices(wlog,mnems,abort)
% Function outputs the column indices of curves in log structure "wlog".
% For any mnemonic in "mnem" for which there is no curve in "wlog" the
% corresponding value of "indices" is set to zero.
% See also: curve_index1
%
% Written by: E. Rietsch: May 2000
% Last updated: November 21, 2007: rewrite; drop second output argument
%
% indices=curve_indices(wlog,mnem)
% INPUT
% wlog log structure whose curve(s) are requested
% mnems curve mnemonic or cell array of curve mnemonics
% abort optional parameter indicating if function should terminate abnormally
% if one or more mnemonics are not found
% abort = 0 ==> do not terminate abnormally
% abort = 1 ==> do not terminate abnormally, but write an error message
% abort = 2 ==> terminate abnormally and write error message
% Default: abort=1
% OUTPUT
% indices row vector of indices of the curves with mnemonics "mnems";
% the length of "indices" is equal to the number of mnemonics "mnem".
% if a mnemonic has not been found the corresponding index value is
% set to zero. If all requested mnemonics have been found then
% any(indices==0) == false.
%
% UPDATE HISTORY
global S4M
if nargin < 3
abort = 1;
end
% Check for uniqueness of the curve mnemonics
curvemnems=wlog.curve_info(:,1);
if ~S4M.case_sensitive
curvemnems=lower(curvemnems);
mnems=lower(mnems);
end
if length(unique(curvemnems)) ~= length(curvemnems)
disp([' The curve mnemonics of "',wlog.name,'" are not unique.'])
error('Abnormal termination.')
end
bool=ismember(mnems,curvemnems);
if all(bool) % All requested mnemonics found
[dummy,ia,ib]=intersect(curvemnems,mnems);
indices=ia(ib); %#ok First output argument is not required
return
else % Not all mnemonics found
if abort < 2
indices=zeros(1,length(mnems));
indices(bool)=find(ismember(curvemnems,mnems(bool)));
if abort == 0
return
else
display_no1(wlog,mnems,~bool)
end
else
display_no1(wlog,mnems,~bool)
error('Abnormal termination.')
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function display_no1(wlog,mnems,bool)
global S4M
temp=mnems(bool);
if length(temp) == 1
disp([' Curve with mnemonic "',cell2str(temp,'", "'),'" does not exist.'])
else
disp([' Curves with mnemonics "',cell2str(temp,'", "'),'" do not exist.'])
end
disp(' The following curve mnemonics exist: ')
if S4M.case_sensitive
disp([' ',cell2str(wlog.curve_info(:,1),',')]);
else
disp([' ',lower(cell2str(wlog.curve_info(:,1),','))]);
end
|
github
|
Abakumov/MLIB-master
|
menu2edit_seismic.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/menu2edit_seismic.m
| 4,719 |
utf_8
|
960cbdba8513dec32b6a295c48ff823b
|
function menu2edit_seismic(figure_handle,axis_handle)
% Create a menu button that allows one to select plot parameters for wiggle plot
% Written by: E. R.: November 20, 2003
% Last updated: September 3, 2004; button legend in red
%
% menu2edit_seismic(figure_handle,axis_handle)
% INPUT
% figure_handle handle of the figure which needs to be replotted
% axis_handle handle of the axis with the seismic data
if nargin == 1
axis_handle=gca;
end
if nargin == 0
figure_handle=gcf;
axis_handle=gca;
end
% Create menu botton
menu_handle=uimenu(figure_handle,'Label','Plot parameters','ForegroundColor','b');
% Create submenu items
uimenu(menu_handle,'Label','New layout', ...
'CallBack',{@g_change_seismic_plot_parameters,figure_handle,axis_handle});
uimenu(menu_handle,'Label','Peak-fill color', ...
'CallBack',{@peak_fill_color,figure_handle,axis_handle});
uimenu(menu_handle,'Label','Trough-fill color', ...
'CallBack',{@trough_fill_color,figure_handle,axis_handle});
uimenu(menu_handle,'Label','Wiggle color', ...
'CallBack',{@wiggle_color,axis_handle});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_change_seismic_plot_parameters(obj,eventdata,figure_handle,axis_handle) %#ok
% Call-back function creating a window to select plot parameters for wiggle plot
% Written by; E. R.: November 20, 2003
% Last updated:
%
% g_change_seismic_plot_parameters(figure_handle)
% INPUT
% figure_handle handle of the figure which needs to be replotted
global PARAMETERS4FUNCTION
% figure_handle=gcf;
figure(figure_handle) % Make figure current
userdata=get(figure_handle,'UserData');
param=userdata.param;
handles=gui_4_seismic_plot_parameters(param);
delete(handles.figure1) % Delete GUI for parameter selection
if handles.ok
userdata4axis=get(axis_handle,'UserData');
delete(userdata4axis.trace_handles.hpeak)
delete(userdata4axis.trace_handles.htrough)
delete(userdata4axis.trace_handles.hwiggle)
PARAMETERS4FUNCTION.s_iplot.default=handles.param;
PARAMETERS4FUNCTION.s_iplot.default.figure='old';
% userdata=get(figure_handle,'UserData');
userdata.param=handles.param;
set(figure_handle,'UserData',userdata)
try
s_iplot(userdata.seismic)
catch
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [color,ok]=select_colors_for_wiggle_trace(title,default)
% Interactively select a color
ok=true;
colors={'r','g','b','y','k','m','c',[0.6,0.6,0.6],[0 0 0]};
%colors={[1 0 0],[0 1 0],[0 0 1],[1 1 0],[0 0 0],[1 0 1],[0 1 1],[0.5,0.5,0.5],[1 1 1]};
labels={'red','green','blue','yellow','black','magenta','cyan','gray','no color'};
default=find(ismember(labels,default));
if isempty(default)
error(['Default color "',default,'" is not available'])
end
index=gui4colors(title,labels,colors,default);
if isempty(index)
ok=false;
color=[];
elseif index == 9
color='none';
else
color=colors{index};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function peak_fill_color(obj,eventdata,figure_handle,axis_handle) %#ok
% Change color of peak-fill
%figure_handle=gcf;
userdata=get(figure_handle,'UserData');
param=userdata.param;
[color,ok]=select_colors_for_wiggle_trace({'Select color for wiggle peaks'},'black');
if ok
userdata4axis=get(axis_handle,'UserData');
if strcmpi(param.direction,'l2r')
set(userdata4axis.trace_handles.hpeak,'FaceColor',color);
else
set(userdata4axis.trace_handles.htrough,'FaceColor',color);
end
refresh
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trough_fill_color(obj,eventdata,figure_handle,axis_handle) %#ok
% Change color of trough-fill
% figure_handle=gcf;
userdata=get(figure_handle,'UserData');
param=userdata.param;
[color,ok]=select_colors_for_wiggle_trace({'Select color for wiggle troughs'},'no color');
if ok
userdata4axis=get(axis_handle,'UserData');
if strcmpi(param.direction,'r2l')
set(userdata4axis.trace_handles.hpeak,'FaceColor',color);
else
set(userdata4axis.trace_handles.htrough,'FaceColor',color);
end
refresh
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wiggle_color(obj,eventdata,axis_handle) %#ok
% Change color of wiggle
[color,ok]=select_colors_for_wiggle_trace({'Select color for wiggles'},'black');
if ok
userdata4axis=get(axis_handle,'UserData');
if strcmp(color,'none')
set(userdata4axis.trace_handles.hwiggle,'LineStyle','none');
else
set(userdata4axis.trace_handles.hwiggle,'Color',color,'LineStyle','-');
end
refresh
end
|
github
|
Abakumov/MLIB-master
|
interpf.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/interpf.m
| 2,722 |
utf_8
|
4b2f6c5ea8500cae5108876e00df75b4
|
function ynew=interpf(yold,dxold,dxnew)
% Function interpolates in the frequency domain;
% appends data to mitigate "edge effects" prior to FFT, and removes them afterwards
% assumes that "dxold" is integer multiple of "dxnew" or vice versa
% Written by: E. Rietsch: February 14, 2001
% Last updated: February 24, 2001: Complete overhaul of function
%
% ynew=interpf(yold,dxold,dxnew)
% INPUT
% yold original data (can be matrix)
% dxold original sample interval
% dxnew new sample interval
% OUTPUT
% ynew resampled data
[nold,ntr]=size(yold);
temp=[yold;yold(end,:)*0.5;zeros(nold-2,ntr);yold(1,:)*0.5];
if dxold > dxnew
frac=dxold/dxnew;
if abs(round(frac)-frac) > 1.0e6*eps
disp([' "interpf" requires that the old sample interval (',num2str(dxold),') is an'])
disp([' integer multiple of the new sample interval (',num2str(dxnew),') or vice versa'])
error(' Abnormal termination')
else
frac=round(frac);
end
ynew=interp_periodic(temp,frac,1);
nnew=nold*frac;
elseif dxold < dxnew
frac=dxnew/dxold;
if abs(round(frac)-frac) > 1.0e6*eps
disp([' "interpf" requires that the new sample interval (',num2str(dxnew),') is an'])
disp([' integer multiple of the old sample interval (',num2str(dxold),') or vice versa'])
error(' Abnormal termination')
else
frac=round(frac);
end
ynew=interp_periodic(temp,1,frac);
nnew=fix(nold/frac);
else
ynew=yold;
nnew=nold;
end
ynew=ynew(1:nnew,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ynew=interp_periodic(yold,dxold,dxnew)
% Function interpolates in the frequency domain
%
% ynew=interp_periodic(yold,dxold,dxnew)
% INPUT
% yold original data (can be matrix)
% dxold original sample interval
% dxnew new sample interval
% OUTPUT
% ynew resampled data
[nold,ntr]=size(yold);
if dxold > dxnew
if mod(dxold,dxnew) == 0
xnew=0:dxnew:nold*dxold-dxnew;
else
xnew=0:dxnew:nold*dxold-dxnew;
end
nnew=length(xnew);
fyold=fft(yold);
fynew=zeros(nnew,ntr);
if ~mod(nold,2)
nh=nold/2+1;
fyold(nh)=fyold(nh)*0.5;
else
nh=(nold+1)/2;
end
fynew(1:nh,:)=fyold(1:nh,:);
fynew(end-nh+2:end,:)=fyold(end-nh+2:end,:);
ynew=real(ifft(fynew))*(dxold/dxnew);
elseif dxold == dxnew
ynew=yold;
else % dxold < dxnew
xnew=0:dxnew:nold*dxold*(1-1.0e6*eps);
nnew=length(xnew);
yold=fft(yold);
ynew=zeros(nnew,ntr);
if ~mod(nnew,2)
nh=nnew/2+1;
yold(end-nh+2)=yold(end-nh+2)*2;
else
nh=(nnew+1)/2;
end
ynew(1:nh,:)=yold(1:nh,:);
ynew(end-nh+2:end,:)=yold(end-nh+2:end,:);
ynew=real(ifft(ynew))*(dxold/dxnew);
end
|
github
|
Abakumov/MLIB-master
|
mylistdlg.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/mylistdlg.m
| 6,623 |
utf_8
|
01328284249b1d5992d4f2b218c69058
|
function [idx,ok]=mylistdlg(strings,varargin)
% Open a list for interactive selection of items; based on Matlab function
% "listdlg"
%
% Written by: E. Rietsch: August 4, 2003
% Last updated: February 10, 2004: change dimensions of dialog box
%
% [idx,ok]=mylistdlg(strings,varargin)
% INPUT
% strings cell vector of strings with the items of the list
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'promptstring' string matrix or cell array of strings which appears
% as text above the list box.
% Default: {promptstring','Select one or more curves:'}
% 'selectionmode' string; can be 'single' or 'multiple';
% Default: {'selectionmode','multiple'}
% 'minmax' minimum and maximum number of items to select; ignore when
% 'selectionmode' is 'single'.
% Default: {'minmax',1,length(strings)]}
% 'name' String for the figure's title.
% Default: {'name',S4M.name}
% 'initialvalue' vector of indices of which items of the list box
% are initially selected;
% Default: {'initialvalue',1} unless the previous call to
% "mylistdlg" used the same cell vector "strings";
% in that case the previously chosen selection is used.
% 'previous' string or cell array with the names of functions
% to be checked for preset values
% Default: {'previous',[]} no presets (or rather the first
% item on the list)
% Example: {'previous','l_plot','l_plot1'}
% OUTPUT
% idx row index vector; the list entries chosen are "strings(idx)". This
% will be [] when OK is 0.
% ok "ok" is 1 if you push the OK button, or 0 if you push the Cancel
% button or close the figure.
global S4M
global S4M_LISTDIALOG % Global structure used to save selection of items
% S4M_LISTDIALOG is a structure matrix with 3 fields:
% 'function','index','strings' to store the name of
% the function to which it relates, the strings selected
% and their positions in the list
% Set defaults for input arguments
param.initialvalue=[];
param.minmax=[1,length(strings)];
param.name=S4M.name;
param.previous=[];
param.promptstring={'Select one or more curves:'};
param.selectionmode='multiple';
param.listsize='adapt';
% Decode and assign input arguments
param=assign_input(param,varargin);
try
param.promptstring=param.promptstring{1};
catch
% keyboard
end
promptstring=param.promptstring;
if isempty(param.listsize)
param.listsize=[160,300];
elseif strcmp(param.listsize,'adapt')
if ischar(strings)
[m,n]=size(strings);
else
n=max(cellfun('length',strings));
m=length(strings);
end
if ischar(promptstring)
nn=length(promptstring);
else
nn=max(cellfun('length',promptstring));
end
n=max([n,nn,12]);
m=min(m,20);
param.listsize=[7*n+5,max(20*m+10,50)];
end
%lprompt=length(promptstring)
if iscell(param.minmax)
param.minmax=[param.minmax{1},param.minmax{2}];
end
if ~isempty(param.previous)
if ~iscell(param.previous)
param.previous={param.previous};
end
end
if isempty(param.initialvalue)
initialvalue=mylistdlg_no1(strings,param.previous); %#ok Used in "eval".
else
initialvalue=param.initialvalue; %#ok Used in "eval".
end
if iscell(param.minmax)
param.minmax=[param.minmax{1},param.minmax{2}];
end
if ~isempty(param.previous)
if ~iscell(param.previous)
param.previous={param.previous};
end
end
if isempty(param.initialvalue)
initialvalue=mylistdlg_no1(strings,param.previous);
else
initialvalue=param.initialvalue; %#ok Used in "eval".
end
ierr=true;
while(ierr)
[idx,ok] = listdlg('PromptString',promptstring,...
'SelectionMode',param.selectionmode,...
'Name',param.name,...
'InitialValue',initialvalue, ...
'ListString',strings, ...
'ListSize',param.listsize);
if ~ok
return
end
if strcmpi(param.selectionmode,'single') || ...
(length(idx) >= param.minmax(1) && length(idx) <= param.minmax(2))
ierr=false;
else
uiwait(msgbox(['You must select ',num2str(param.minmax(1)),' to ', ...
num2str(param.minmax(2)),' items from the list'],param.name,'warn'));
end
end
% Save selected strings and their location in the cell vector "strings"
% in global structure vector "S4M_LISTDIALOG"
if ~isempty(param.previous)
nlist=length(S4M_LISTDIALOG);
old=cell(nlist,1);
for ii=1:nlist
old{ii}=S4M_LISTDIALOG(ii).function;
end
idx1=find(ismember(old,param.previous{1}));
if idx1 > 0
S4M_LISTDIALOG(idx1).indices=idx;
S4M_LISTDIALOG(idx1).strings=strings(idx);
else
S4M_LISTDIALOG(nlist+1).function=param.previous{1};
S4M_LISTDIALOG(nlist+1).indices=idx;
S4M_LISTDIALOG(nlist+1).strings=strings(idx);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function initialvalue=mylistdlg_no1(strings,previous)
% Extract initial selection of list items from a previous use
%
% INPUT
% strings strings in the current list
% previous cell array with relevant function names in the order of their relevance
% OUTPUT
% initialvalue index vector; "strings(initialvalue)" are preselected
global S4M_LISTDIALOG % Global structure used to save selection of items
initialvalue=1; % Default initial value
nlist=length(S4M_LISTDIALOG);
if nlist > 0
if iscell(previous)
nprevious=length(previous);
else
nprevious=length(previous);
if nprevious > 0
nprevious=1;
previous={previous};
end
end
old=cell(nlist,1);
for ii=1:nlist
old{ii}=S4M_LISTDIALOG(ii).function;
end
for ii=1:nprevious
idx=find(ismember(old,previous{ii}));
if idx > 0
oldindex=S4M_LISTDIALOG(idx).indices;
oldstrings=S4M_LISTDIALOG(idx).strings;
if length(strings) >= max(oldindex)
idx1=find(ismember(strings(oldindex),oldstrings));
if length(idx1) == length(oldindex)
initialvalue=oldindex;
break
end
end
end
end
end
|
github
|
Abakumov/MLIB-master
|
gg_pickbox.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/gg_pickbox.m
| 2,104 |
utf_8
|
a95234c4b56d2bad63895bc1379180dd
|
function pos=gg_pickbox(axis_handle)
% Function to draw a rubberband line and return the start and end points
%
% pos=gg_pickbox(axis_handle)
% INPUT
% axis_handle handle of current axes
% field field in userdata in whoch to store the rectangle coordinates
if nargin == 0
axis_handle=gca;
end
figure_handle=gcf;
userdata=get(figure_handle,'UserData'); % Save user data associated with figure handle
dblbuff=get(figure_handle,'DoubleBuffer');
hold on;
p1=get(axis_handle,'CurrentPoint'); % Get starting point
p1=p1(1,1:2); % Extract x and y
lh=plot(p1(1),p1(2),'+:','LineWidth',2); % Plot starting point
udata.p1=p1;
udata.ah=axis_handle;
udata.lh=lh;
udata.object2delete=lh;
set(figure_handle,'UserData',udata,'WindowButtonMotionFcn','wbmf','DoubleBuffer','on');
set(figure_handle,'WindowButtonUpFcn',{@delete_fig_object,figure_handle})
waitfor(lh)
%waitforbuttonpress;
p2=get(axis_handle,'Currentpoint'); % Get end point
%keyboard
pos=[p1(1),p2(1,1),p1(2),p2(1,2)];
% Restore user data and handles associated with figure
set(figure_handle,'Userdata',userdata,'WindowButtonMotionFcn','', ...
'DoubleBuffer',dblbuff);
% delete(lh); % Delete box
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wbmf
% Window motion callback function
utemp=get(gcf,'UserData');
ptemp=get(utemp.ah,'CurrentPoint');
ptemp=ptemp(1,1:2);
set(utemp.object2delete,'XData',[utemp.p1(1),ptemp(1),ptemp(1),utemp.p1(1),utemp.p1(1)], ...
'YData',[utemp.p1(2),utemp.p1(2),ptemp(2),ptemp(2),utemp.p1(2)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function delete_fig_object(hObject,evdata,figure_handle) %#ok
% Delete the graphics object that is saved in figure user data structure and
% has the field name "object2delete"
% Written by: E. Rietsch: November 27, 2003
% Last updated:
% figure_handle=gcf;
userdata=get(figure_handle,'UserData');
if isfield(userdata,'object2delete')
delete(userdata.object2delete)
set(figure_handle,'WindowButtonMotionFcn',[])
set(figure_handle,'WindowButtonUpFcn',[])
end
|
github
|
Abakumov/MLIB-master
|
figure_export_menu.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/figure_export_menu.m
| 3,867 |
utf_8
|
c2bee1c0758987651931370375975ea7
|
function menu_handle=figure_export_menu(figure_handle)
% Creates a menu button on the figure with handle "figure_handle" (or
% the current figure) that allows one to save the figure as a "emf" (Enhanced
% Windows Meta File) for PowerPoint or "eps" (Encapsulated PostScript) for
% LaTeX, or as a JPEG file; does nothing if the menu button already exists.
%
% Written by: E. Rietsch: November 16, 2003
% Last updated: August 31, 2007: check if figure export menu already exists
%
% menu_handle=figure_export_menu(figure_handle)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% Default: gcf
%
% EXAMPLE
% figure
% plot(1:11)
% figure_export_menu
persistent fig_no
if nargin == 0
figure_handle=gcf;
end
if isempty(fig_no)
fig_no=1;
else
fig_no=fig_no+1;
end
% Check is a figure-export menu button already exists and return if it does
if ~isempty(findobj(figure_handle,'tag','figure_export_menu'))
disp('Figure-export menu menu exists.')
menu_handle=[];
return
end
% Create menu botton
menu_handle=uimenu(figure_handle,'Label','Save plot','ForegroundColor','b','Tag','figure_export_menu');
% Create submenu items
uimenu(menu_handle,'Label','EMF (for PowerPoint)', ...
'CallBack',{@g_fig2pp,figure_handle,0});
uimenu(menu_handle,'Label','JPEG', ...
'CallBack',{@g_fig2jpg,figure_handle,0});
uimenu(menu_handle,'Label','EPS (for LaTeX)', ...
'CallBack',{@g_fig2eps,fig_no,figure_handle});
if nargout == 0
clear menu_handle
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_fig2pp(hObject,eventdata,figure_handle,reverse) %#ok first two arguments are place holders
% Version of "fig2pp" to be called by a menu callback
% Written by: E. Rietsch: November 16, 2003
% Last updated: May 8, 2004: made subfunction
%
% g_fig2pp(hObject,eventdata,figure_handle,reverse)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% reverse Reverse the figure background and axis colors and adjust graphs
% (see "whitebg")
% S4M.invert_hardcopy must be set to 'off' to have an effect
% (See figure property 'InvertHardcopy')
fig2pp(figure_handle,reverse);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_fig2jpg(hObject,eventdata,figure_handle,reverse) %#ok first two arguments are place holders
% Version of "fig2pp" to be called by a menu callback
% Written by: E. Rietsch: November 16, 2003
% Last updated: May 8, 2004: made subfunction
%
% g_fig2pp(hObject,eventdata,figure_handle,reverse)
% INPUT
% figure_handle handle of the figure to which to attach the menu button
% reverse Reverse the figure background and axis colors and adjust graphs
% (see "whitebg")
% S4M.invert_hardcopy must be set to 'off' to have an effect
% (See figure property 'InvertHardcopy')
fig2jpg(figure_handle,reverse);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g_fig2eps(hObject,eventdata,repfig,figno) %#ok first two arguments are place holders
% Export figure for use in LaTeX documents
% Written by: E. Rietsch: March 4, 2003
% Last updated: March 19, 2004: use fig2eps which uses report
% directory in "S4M.eps_directory"
%
% g_fig2eps(hObject,eventdata,repfig,figno)
% INPUT
% repfig unique figure number for report (required)
% figno number of figure to export
% Default: figno=gcf
if ischar(repfig)
repfig=str2double(repfig);
end
if nargin == 0
error(' Figure number in report is required')
end
if nargin == 1
figno=gcf;
end
fig2eps(repfig,figno)
|
github
|
Abakumov/MLIB-master
|
assign_input.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/assign_input.m
| 4,666 |
utf_8
|
8229f64e41f3b662d7ce0c878a564f25
|
function param=assign_input(param,arguments,fcn)
% Input argument "arguments" is a cell array; each cell contains a cell array
% whose first entry is a string representing a keyword; the other entries
% represent parameters.
% This function matches these keywords to fields of the structure "param" and
% replaces the values of these fields with the corresponding paramters
% Used to replace defaults of input arguments with actual arguments.
%
% The actual input arguments can also be provided via the global
% variable "PARAMETERS4FUNCTION"
%
% Experimental: for SeisLab-type arguments
%
% Written by: E. Rietsch: July 11,2008
% Last updated: January 18, 2009: bug fix
%
% param=assign_input(param,arguments,fcn)
% INPUT
% param structure with default values of the input arguments
% arguments cell array, each element of "arguments" is a cell array
% whose first element is a field name of "param"
% fcn string with the name of the function calling "assign_input";
% optional
% OUTPUT
% param input structure updated with values in "arguments"
%
% UPDATE HISTORY
%
global PARAMETERS4FUNCTION S4M
larguments=length(arguments);
kw=cell(larguments,1);
parameters=cell(length(arguments),1);
for ii=1:larguments
temp=arguments{ii};
kw(ii)=temp(1);
parameters{ii}=temp(2:end);
end
if S4M.case_sensitive
keywords=fieldnames(param);
else
keywords=lower(fieldnames(param));
kw=lower(kw); % Keywords specified
end
% Check if arguments are supplied via global variable "PARAMETERS4FUNCTION.fcn.default"
if nargin > 2
if isfield(PARAMETERS4FUNCTION,fcn)
temp=PARAMETERS4FUNCTION.(fcn);
if isfield(temp,'default') && ~isempty(temp.default)
defaults=temp.default;
fields=fieldnames(defaults);
bool=ismember(fields,keywords);
if ~all(bool)
disp(['Parameters specified via "PARAMETERS4FUNCTION.',fcn,'.default":'])
disps(cell2str(fields,', '))
fields=fields(~bool);
disp('Parameters that are not keywords of function:')
disps(cell2str(fields,', '))
disp('Possible keywords are: ')
disps(cell2str(keywords,', '))
temp.default=[];
% Set "PARAMETERS4FUNCTION.functionname.default" to the empty matrix to prevent
% it from being used again in another function
PARAMETERS4FUNCTION.(fcn)=temp;
error(['Not all fields of "PARAMETERS4FUNCTION.',fcn,'.default" are keywords'])
end
for ii=1:length(fields)
param.(fields{ii})=temp.default.(fields{ii});
end
% Set "PARAMETERS4FUNCTION.functionname.default" to the empty matrix to prevent
% it from being used again in another function
temp.default=[];
PARAMETERS4FUNCTION.(fcn)=temp;
end
end
end
% Use input arguments of the function calling "atualInputArguments"
largs=length(arguments);
% if rem(largs,2) > 0
% error('Number of keyword-controlled input arguments must be even.')
% end
% Check if the keywords specified, "kw", are the ones actually
% expected, "keywords"; expand them if required
ier=false;
for ii=length(kw):-1:1;
kw{ii}=kw_no1(keywords,kw{ii});
if isempty(kw{ii})
ier=true;
else
temp=parameters{ii};
if length(temp) == 1
param.(kw{ii})=temp{1};
else
param.(kw{ii})=temp;
end
end
end
if ier
temp=dbstack;
[dummy,funct]=fileparts(temp(2).name);
error(['There is a problem with the input arguments of function "',funct,'".'])
end
if nargin > 2
temp1.actual=param;
PARAMETERS4FUNCTION.(fcn)=temp1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function kw=kw_no1(keywords,kw)
global S4M
idx=find(ismember(keywords,kw));
if length(idx) == 1
return
end
% Handle case of keyword expansion (if allowed)
if isempty(idx) && S4M.keyword_expansion
starts=strmatch(kw,keywords); % Find all the keywords which begin with "kw".
if length(starts) == 1
kw=keywords{starts};
elseif length(starts) > 1
disp([' Keyword "',kw,'" is not a unique abbreviation. Possible expansions are:'])
disps(cell2str(keywords(starts),', '))
kw='';
else
disp([' Keyword "',kw,'" is not one of those expected and cannot be expanded to match one.'])
disp(' Valid keywords are:')
disps(cell2str(keywords,', '))
kw='';
end
else
disp([' Keyword "',kw,'" is not one of those expected. Valid keywords are:'])
disps(cell2str(keywords,', '))
kw='';
end
|
github
|
Abakumov/MLIB-master
|
create_help_button.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/create_help_button.m
| 1,516 |
utf_8
|
9f8121e3569b3562d0a82507d0ed7bd5
|
function create_help_button(funct)
% Create a menu button that displays instructions found in a text file
% with name ['help4',funct,'.txt'] in subdirectory "HelpFiles" in
% directory S4M.mymatlab
%
% Written by: E. Rietsch: December 16, 2005
% Last updated:
%
% create_help_button(funct)
% INPUT
% funct string with name of function that creates the plot for which the
% button is intended
global S4M
% Check if a help file exists
filename=fullfile(S4M.helpfiles,['help4',funct,'.txt']);
fid=fopen(filename);
if fid < 0
alert(['Help file for "',funct,'" has not been found. No help button created.'])
return
end
label='Need help?';
% Read help file
help_info=get_help_file(fid);
% Determine the number of sub-menus (if any)
fields=fieldnames(help_info);
if length(fields) == 1 % No submenus
temp=help_info.(fields{1});
uimenu('Label',label,'Tag','help_display', ...
'ForeGroundColor',[1 0 0],'CallBack',{@myhelpdlg,temp(2:end)});
else % Submenus
menu_handle=uimenu('Label',label,'Tag','help_display', ...
'ForeGroundColor',[1 0 0]);
for ii=1:length(fields)
% temp=getfield(help_info,fields{ii});
temp=help_info.(fields{ii});
uimenu(menu_handle,'Label',temp{1},'ForeGroundColor',[1 0 0],{@myhelpdlg,temp(2:end)});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function myhelpdlg(varargin)
global S4M
helpdlg(varargin{3},S4M.name)
|
github
|
Abakumov/MLIB-master
|
open_segy_file4reading.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/private/open_segy_file4reading.m
| 25,438 |
utf_8
|
7242f0726c26ff4ac62f472821af34b4
|
function [fid,seismic,param,parameters,text_header,binary_header] = ...
open_segy_file4reading(filename,varargin)
% Function opens an SEG-Y file, reads the textual header and the binary file
% header and outputs the file ID, a preliminary seismic data structure
% with empty fields "header" and "traces".
% In addition, it outputs parameters that allow function "read_segy_file_traces"
% to read consecutive traces.
%
% Written by: E. Rietsch: January 6, 2007
% Last updated: February 27, 2008: bug fix in error message
%
% [fid,seismic,param,parameters,text_header,binary_header] = ...
% open_segy_file4reading(filename,varargin)
% INPUT (all input arguments are optional)
% filename name of the file to read
% if the name is omitted, empty, or a file with this name is not found
% a file selector box will pop up to allow interactive file selection
% varargin Variable number of arguments. Each argument is a cell array whose first
% element is a keyword and whose other elements can be strings, numeric
% values, or other cell arrays
% Possible keywords are:
% format floating point format to use; this cell array has the form
% {'format',fp-format} where fp_format is one of the three strings:
% 'ibm' IBM floating point format (standard and default)
% 'ieee' IEEE format, big endian (Sun, SGI, etc.)
% 'header' The binary header bytes 25-26 are used to determine the format
% Default: {'format','header'};
% headers header values to be read from binary trace header; this cell array has
% the form {'headers',{mnem1,first,bytes,units,dimension,description}, ...
% {mnem2,first,bytes,units,dimension,description},...} where
% "mnem1", "mnem2", ... denote header mnemonics (such as CDP, OFFSET),
% "first" denotes the first byte in the binary header,
% "bytes" denotes the number of bytes occupied by the mnemonic (2 or 4),
% "units" denotes the units of measurement for the header value, and
% "description" is a description of the header value.
% Example:
% {'headers',{'ILINE_NO',181,4,'n/a','CDP number'}, ...
% {'OFFSET',37,4,'m','Source-receiver distance'}}
% See below for a list of headers retrieved by default.
% Default: {'headers',{}}
% times times to output; this cell array has the form
% {'times',first,last}, {'times',[first,last]}, or {'times',[]}
% In the first two forma all samples with times between (and
% including) first and last (in ms) are output. In the last case
% all samples are output.
% Default: {'times',[]}
% traces select traces to output; this cell array has the form
% {'traces',expression}; the variable "expression" is used to
% determine which traces to output. "expression" can be an index
% vector specifying the traces to output
% Examples: {'traces',1:2:100}
% {'traces',[2,5,7:10,22]}
% Alternatively, it can be a string with a logical expression involving
% trace headers such as '10 <= cdp && 100 >= cdp'
% Examples: {'traces','cdp == 100 && offset > 100'}
% {'traces','14000 < cdp && (14660 >= cdp || 14680 <= cdp)'};
% The variables in the logical relationships must be headers of the
% data set; Use of functions "fix", "mod", and "round" are permitted; all
% other function names will be interpreted as headers and likely cause an
% error; the case of the headers in an expression does not matter.
% Default: {'traces',[]}
% ignoreshift By default this function reads byte locations 109-110 (see
% header "lag" below) and applies the shift to the seismic data;
% This behavior can be overwritten by setting this parameter to true;
% Default: {'ignoreshift',false}
% max_mem maximum amount of contiguous memory in megabytes (MB) bytes available
% to store seismic traces;
% Default: {'max_mem',[]}
% This means the maximum size is determined internally.
%
% Headers retrieved by default are (any one of these headers is removed if it turns out to
% be identically zero):
% ds_seqno Trace sequence number within line (1-4)
% ffid Original Field record number (9-12)
% o_trace_no Trace sequence number within original field record (13-16)
% source Energy source point number (17-20)
% cdp CDP ensemble number (21-24)
% seq_cdp Trace sequence number within CDP ensemble (25-28)
% trc_type Trace ID (1=live,2=dead,3=dummy,4=time break,...) (29-30)
% offset Distance from source point to receiver group (37-40)
% rec_elev Receiver elevation (41-44);
% sou_elev Surface elevation at source (45-48)
% depth Source depth below surface (49-52)
% sou_h2od Water depth at source (61-64)
% rec_h2od Water depth at receiver group (65-68)
% sou_x X coordinate of source (73-76)
% sou_y Y coordinate of source (77-80)
% rec_x X coordinate of receiver (81-84)
% rec_y Y coordinate of receiver (85-88)
% lag Lag time between shot and recording start in ms (109-110)
% (the value of lag is added to the start time of the
% seismic; hence it can be used to simulate non-zero start
% time of the data)
% see also parameter "ignoreshift", above.
% cdp_x X coordinate of CDP (181-184)
% cdp_y Y coordinate of CDP (185-189)
% iline_no In-line number (189-192)
% xline_no Cross-line number (193-196)
% The numbers in parentheses at the end of the line denote the location
% of the corresponding bytes in the SEG-Y trace header
%
% OUTPUT
% seismic Seismic structure
% seismic.type 'seismic' (type of structure)
% seismic.name file name without exyension
% seismic.from Full name of the SEG-Y file
% seismic.traces Array of seismic traces
% seismic.first Start time of seismic (in ms)
% seismic.last End time of seismic (in ms)
% seismic.step Sample interval of seismic (in ms)
% seismic.units Time units used (ms)
% seismic headers Matrix with header mnemonics (one row
% per header)
% seismic.header_info Three-column cell array with header info
% (one row per header)
% seismic.null []
% seismic.line_number Line number (5-8)
% seismic.reel_number Reel number (9-12)
% seismic.cdp_fold CDP fold
% seismic.traces_per_record Data traces per record (13-14)
% seismic.aux_per_record Auxiliary traces per record (15-16)
% seismic.history A four element cell array. The first element
% is the start date/time of the program that
% invoked this function; the second element is
% the start date/time this function was executed;
% and the last cell contains the name if the file
% that was read
% Example:
% seismic.offset contains the offset for each trace
% seismic.header_info.cdp two-element cell array {'m','Offset'}
% the first element represents the units of measurement, the
% second is a description of the header
%
% ebcdic_header EBCDIC reel header converted to ASCII
% binary_header Binary reel header
% UPDARE HISTORY
% July 15, 2007: bug fix in trace constraints
global ABORTED
% Set default output arguments
run_presets_if_needed
% Set default for input parameters
param.format='header';
param.headers={};
param.ignoreshift=false;
param.debug=false;
%param.precision='single';
param.times=[];
param.traces=[];
param.header_precision='single';
param.max_mem=[];
if nargin == 0
filename='';
else
% Replace defaults by actual input arguments
param=assign_input(param,varargin,'open_segy_file4reading');
if ~ismember(lower(param.format),{'ieee','ibm','header'})
disp([' Unknown trace format: ',param.format])
disp(' Allowed formats are ''header'', ''ieee'', and ''ibm''.')
drawnow
error('Abnormal termination.')
end
if ~isempty(param.times)
param=check_time_range_no0(param); % Check if the time range is specified correctly
end
end
% Open SEG-Y file and get file ID
fid=open_segy_file_no1(filename);
if fid < 0
seismic=[];
text_header=[];
binary_header=[];
parameters=[];
return
end
% Read textual file header
text_header=read_textual_file_header_no2(fid);
% Read binary file header
binary_header=read_binary_file_header_no3(fid);
% Check FP format and save it and units of measurement for distance in
% structure "param"
param=check_file_headers_no4(binary_header,param);
if ABORTED
seismic=[];
return
end
% Create seismic structure and index of the time samples to retain
[seismic,parameters.idx4times]=create_seismic_structure_no5(binary_header,param);
% Collect info about the headers to read from binary trace header block
[parameters.header_info,parameters.indices,parameters.true4four, ...
parameters.constraint_info,param]=select_trace_headers2read_no6(param);
if ABORTED
seismic=[];
return
end
param.nsamp=length(parameters.idx4times);
param.nheaders=length(parameters.indices);
param.no_samples=binary_header(8);
% Get number of traces
param.ntraces=get_no_of_traces_no7(seismic.from,binary_header(8));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function param=check_time_range_no0(param)
% Check the compatibility of the time range specified
if ~isempty(param.times)
if iscell(param.times)
param.times=cell2num(param.times);
end
if length(param.times) == 1
param.times=[param.times,param.times];
elseif length(param.times) == 2
if param.times(2) < param.times(1)
error('Start time of time range is greater than end time.')
end
if param.times(1) < 0
error('Start time of time range is less than 0.')
end
else
error('Range of times to read must be specified by a start time and an end time.')
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function fid=open_segy_file_no1(filename)
% Open SEG=Y file and return file ID
% INPUT
% filenane filename; can be empty
% mformat machine format (see Matlab function "fopen"
% OUPTUT
% fid file ID
mformat='ieee-be';
% Open the file
if ~isempty(filename)
fid=fopen(filename,'r',mformat);
if fid == -1
if ~isdeployed
disp(['... unable to find file ',filename])
end
else
filename2S4M(filename)
end
else
fid=-1;
end
if fid==-1 % Open file selector window
[filename,ierr]=get_filename4r('sgy');
if ierr
return
end
fid=fopen(filename,'r',mformat);
if fid < 0
error(['File "',filename,'" could not be opened.'])
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function text_header=read_textual_file_header_no2(fid)
% Read EBCDIC header and output it as ASCII
% INPUT
% fid File ID
% OUTPUT
% text_header EBCDIC header as ASCII
global ABORTED S4M
% Read EBCDIC reel header 1
% text_header=fread(fid,3200,'uchar'); % Linux problem
text_header=fread(fid,3200,'uchar');
if isempty(text_header)
if S4M.deployed
errordlg('EBCDIC header is empty; requested file is either empty or not an SEG-Y file.', ...
S4M.name)
ABORTED=true;
return
else
error('EBCDIC header is empty; requested file is either empty or not an SEG-Y file.')
end
end
ABORTED=false;
text_header=char(ebcdic2ascii(reshape(text_header,80,40)'));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function binary_header=read_binary_file_header_no3(fid)
% Read binary header and initiate the seismic dataset
% INPUT
% fid file ID
% OUTPUT
% binary_header binary header (two-byte variables and four-byte variables
% are stored together in one vector
% Read binary file header
bh=fread(fid,400,'uchar');
two_bytes=bh(1:2:399)*256+bh(2:2:400);
four_bytes=((bh(1:4:9)*256+bh(2:4:10))*256+bh(3:4:11))*256+bh(4:4:12);
binary_header=[four_bytes(1:3);two_bytes(7:200)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function param=check_file_headers_no4(binary_header,param)
% Check binary-format code and output format and units of measurement in
% structure param
% INPUT
% binary_header binary header
% param structure with input parameters for "read_segy_file"
% OUTPUT
% param input structure "param" with theo new fields: "format" and "units"
global ABORTED
% Check format
if binary_header(10) == 1
if strcmpi(param.format,'header') || strcmpi(param.format,'ibm')
% param.fmt='ibm';
param.format='ibm';
else
disp('IEEE format requested')
mywarning(['Data apparently stored as 32-bit IBM floating point numbers; ' ...
'data sample format code = ',num2str(binary_header(10))]);
end
param.precision='uint32=>uint32';
elseif binary_header(10) == 5
if strcmpi(param.format,'header') || strcmpi(param.format,'ieee')
% param.fmt='ieee-be';
param.format='ieee-be';
else
display('IBM format requested')
mywarning(['Data apparently stored as 32-bit IEEE big-endian floating point numbers; ' ...
'data sample format code = ',num2str(binary_header(10))]);
end
param.precision='single';
else
if param.debug
disp(['Data in unsupported format; ' ...
'data sample format code = ',num2str(binary_header(10))]);
param.precision='single';
else
myerror(['Data in unsupported format; ' ...
'data sample format code = ',num2str(binary_header(10))]);
ABORTED=true;
fclose(fid)
return
end
end
% Extract units of measurement for distances
if binary_header(25) == 1
param.units='m';
elseif binary_header(25) == 2
param.units='ft';
else
param.units='unknown';
end
ABORTED=false;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [seismic,idx4times]=create_seismic_structure_no5(binary_header,param)
% Create the fields of the seismic structure and populate them as far as possible
% INPUT
% binary_header binary header
% param structure with input parameters for "read_segy_file"
% OUTPUT
% seismic seismic structure
% idx4time index of time samples to keep
global S4M
step=binary_header(6)/1000;
no_samples=binary_header(8);
last=step*(no_samples-1);
% Compute indices of time range
if ~isempty(param.times) % Compute index vector for time samples
ita=ceil(param.times(1)/step);
param.times(1)=ita*step;
param.times(2)=min(last,param.times(2));
ite=fix(param.times(2)/step);
param.times(2)=ite*step;
idx4times=ita+1:ite+1;
else
param.times=[0,last];
idx4times=(1:no_samples)'; % Keep all time samples
end
% Create seismic structure
seismic.type='seismic';
seismic.tag='unspecified';
[dummy,seismic.name]=fileparts(S4M.filename); %#ok First output variable is not required
seismic.from=fullfile(S4M.pathname,S4M.filename);
seismic.line_number=binary_header(2);
seismic.reel_number=binary_header(3);
seismic.traces_per_record=binary_header(4);
seismic.aux_per_record=binary_header(5);
if binary_header(11) ~= 0
seismic.cdp_fold=binary_header(11);
end
seismic.first=param.times(1);
seismic.last=param.times(2);
seismic.step=step;
seismic.units='ms';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [header_info,indices,true4four,constraint_info,param]=select_trace_headers2read_no6(param)
% Create a cell array with ibformation about the headers that are to be read
% their bit location and length
% INPUT
% param input parameters of read_segy_file (plus ome parameters
% acquired along the way
% OUTPUT
% header_info
% The 7 columns of header_info are:
% mnemonic, units, description, first byte, No. of bytes,
% bool ("true" if user-requested), and index.
% If the 240-byte header is read into a 60 element array then the index
% defines in which element a 4-byte header is: for a 4-byte header word
% starting at byte 13 index=4 (index=(start_byte-1)/4+1)
% The index for a two-byte header is similarly defined.
% indices vector of header indices
% true4four boolean vector true if index is for a four-byte header.
global S4M
constraint_info=[];
if isempty(param.headers)
nh1=0;
elseif iscell(param.headers{1})
nh1=length(param.headers); % User-requested headers
else
param.headers={param.headers};
nh1=1;
end
% Select standard headers and add user-defined headers
% Descriptions for standard binary trace headers
nh0=22; % Default headers
nh=nh0+nh1; % Total number of headers
header_info=cell(nh,7);
header_info(1:nh0,6)=deal({false});
header_info(1:nh0,3)=[...
{'Trace sequence number within line'}; ... % 4-byte headers
{'Original Field record number'}; ...
{'Trace sequence number within original field record'}; ...
{'Energy source point number'}; ...
{'CDP number'}; ...
{'Trace sequence number within CDP ensemble'}; ...
{'Offset'}; ...
{'Source depth below surface'}; ...
{'Water depth at source'}; ...
{'Water depth at receiver group'}; ...
{'X coordinate of source'}; ...
{'Y coordinate of source'}; ...
{'Surface elevation at source'}; ...
{'X coordinate of receiver'}; ...
{'Y coordinate of receiver'}; ...
{'Receiver elevation'}; ...
{'X-coordinate of CDP'}; ...
{'Y-coordinate of CDP'}; ...
{'In-line number'}; ...
{'Cross-line number'}; ...
{'Trace type (1=live,2=dead,3=dummy,...)'}; ... % 2-byte headers
{'Lag time between shot and recording start'}; ...
];
header_info(1:nh0,[1,4,5]) = { ... % 4-byte headers
'ds_seqno', 1,4; ...
'ffid', 9,4; ...
'o_trace_no', 13,4; ...
'source', 17,4; ...
'cdp', 21,4; ...
'seq_cdp', 25,4; ...
'offset', 37,4; ...
'depth', 49,4; ...
'sou_h2od', 61,4; ...
'rec_h2od', 65,4; ...
'sou_x', 73,4; ...
'sou_y', 77,4; ...
'sou_elev', 45,4; ...
'rec_x', 81,4; ...
'rec_y', 85,4; ...
'rec_elev', 41,4; ...
'cdp_x', 181,4; ...
'cdp_y', 185,4; ...
'iline_no', 189,4; ...
'xline_no', 193,4; ...
'trc_type', 29,2; ... % 2-byte headers
'lag', 109,2};
header_info(1:nh0,2)=deal({'n/a'});
header_info(7:16,2)={param.units};
header_info(22,2)={'ms'};
if nh1 > 0
% nh=length(param.headers);
% nh=nh1;
% Defaults for some commonly requested headers
defaults.iline_no={'n/a','In-line number'};
defaults.xline_no={'n/a','Cross-line number'};
defaults.cdp_x={param.units,'X-coordinate of CDP'};
defaults.cdp_y={param.units,'Y-coordinate of CDP'};
defaults.rec_x={param.units,'X-coordinate of receiver'};
defaults.rec_y={param.units,'Y-coordinate of receiver'};
defaults.sou_x={param.units,'X-coordinate of source'};
defaults.sou_y={param.units,'Y-coordinate of source'};
% Handle header supplided by users
header_info(nh0+1:nh,6)=deal({true});
for ii=nh0+1:nh
nhii=length(param.headers{ii-nh0});
if nhii == 5
header_info(ii,[1,4,5,2,3])=param.headers{ii-nh0};
if isempty(header_info{ii,2});
header_info{ii,2}='n/a';
end
if isempty(header_info{ii,3});
header_info{ii,3}=header_info{ii,1};
end
elseif nhii == 3
header_info(ii,[1,4,5])=param.headers{ii-nh0};
if any(ismember(fieldnames(defaults),lower(header_info{ii,1})))
header_info(ii,2:3)=defaults.(lower(header_info{ii,1}));
else
header_info{ii,2}='n/a';
header_info{ii,3}=header_info{ii,1};
end
else
error('The description of an additional header to be read must be a cell vector with 3 or 5 entries.')
end
end
ierr=false;
for jj=nh0+1:nh
if mod(header_info{jj,4},header_info{jj,5}) ~= 1
disp(['First byte for header ',header_info{jj,1}, ' is wrong.'])
ierr=true;
end
end
if ierr
error('Abnormal termination.')
end
end
% Keep unique headers
[dummy,index]=myunique(header_info(:,1)); %#ok First output argument is not required
header_info=header_info(index,:);
nh=length(index);
indices=zeros(nh,1);
true4four=true(nh,1);
for ii=1:nh
indices(ii)=(header_info{ii,4}-1)/header_info{ii,5}+1;
header_info{ii,7}=indices(ii);
true4four(ii)=header_info{ii,5} == 4;
end
% If traces are selected via constraints on headers then
% create a cell array with header names and associate locations
% in the "headers" matrix
if ~isempty(param.traces) && ischar(param.traces)
% Find headers in constraint string
expression=param.traces;
words=symvar(expression);
if ~S4M.case_sensitive
% Change expression
for ii=1:length(words)
expression=strrep(expression,words{ii},lower(words{ii}));
end
param.traces=expression;
words=lower(words);
headers=lower(header_info(:,1));
else
headers=header_info(:,1);
end
words=unique(words);
index=find(ismember(headers,words));
bool=ismember('trace_no',words);
if ~bool && isempty(index)
disp([' No headers found in trace constraint "',expression,'".'])
myerror(' Reading of SEG-Y file terminated abnormally.')
else
constraint_info=cell(length(index)+bool,2);
for ii=1:length(index)
constraint_info(ii,:)=[headers(index(ii)),{num2str(index(ii))}];
end
if bool
constraint_info(end,:)={'trace_no',0};
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ntr=get_no_of_traces_no7(filename,nsamples)
% Use number of bytes to compute number of traces
ll=dir(filename);
nbytes=ll.bytes;
ntr=0.25*(nbytes-3600)/(nsamples+60);
if ~isnearinteger(ntr)
mywarning(['Number of bytes in file "',filename,'", (',num2str(nbytes), ...
'), is not compatible with constant-length traces'])
ntr=fix(ntr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ascii=ebcdic2ascii(ebcdic)
% Function converts EBCDIC string to ASCII
% see http://www.room42.com/store/computer_center/code_tables.shtml
%
% Written by: E. Rietsch: Feb. 20, 2000
% Last updated:
%
% ascii=ebcdic2ascii(ebcdic)
% INPUT
% ebcdic EBCDIC string
% OUTPUT
% ascii ASCII string
pointer= ...
[ 0 16 32 46 32 38 45 46 46 46 46 46 123 125 92 48
1 17 33 46 46 46 47 46 97 106 126 46 65 74 46 49
2 18 34 50 46 46 46 46 98 107 115 46 66 75 83 50
3 19 35 51 46 46 46 46 99 108 116 46 67 76 84 51
4 20 36 52 46 46 46 46 100 109 117 46 68 77 85 52
5 21 37 53 46 46 46 46 101 110 118 46 69 78 86 53
6 22 38 54 46 46 46 46 102 111 119 46 70 79 87 54
7 23 39 55 46 46 46 46 103 112 120 46 71 80 88 55
8 24 40 56 46 46 46 46 104 113 121 46 72 81 89 56
9 25 41 57 46 46 46 46 105 114 122 46 73 82 90 57
10 26 42 58 46 33 124 58 46 46 46 46 46 46 46 46
11 27 43 59 46 36 44 35 46 46 46 46 46 46 46 46
12 28 44 60 60 42 37 64 46 46 46 46 46 46 46 46
13 29 45 61 40 41 95 39 46 46 91 93 46 46 46 46
14 30 46 46 43 59 62 61 46 46 46 46 46 46 46 46
15 31 47 63 124 94 63 34 46 46 46 46 46 46 46 46];
pointer=reshape(pointer,1,256);
ascii=pointer(ebcdic+1);
|
github
|
Abakumov/MLIB-master
|
moperation.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/@struct/moperation.m
| 11,298 |
utf_8
|
54b781cd586b9f66f1c73265482cf1f6
|
function ds=moperation(i1,i2,operator)
% Function multiplies a constant or matrix elementwise with traces
% of a seismic dataset
%
% Written by: E. Rietsch: December 7, 2006
% Last updated:
%
% ds=moperation(i1,i2,operator)
% INPUT
% i1 first operand
% i2 second operand
% At least one of the two operands is a dataset.
% operation string defining operation to perform. Possible values are:
% '+', '-', '*', '/', '^'
% OUTPUT
% ds result of the operation
try
if isstruct(i1)
type=i1.type;
else
type=i2.type;
end
catch
error(['Operation "',operator,'" is not defined for these two objects'])
end
switch type
case 'seismic'
ds=moperation4seismic(i1,i2,operator);
case 'pdf'
ds=moperation4pdf(i1,i2,operator);
otherwise
error(['Operation "',operator,'" is not defined for these two arguments'])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=moperation4pdf(i1,i2,operator)
% Perform the operation defined by input argument "operator" to the first two
% input arguments
%
% Written by: E. Rietsch: July 12, 2006
% Last updated: September 16, 2006: Add handling of PDF's
%
% ds=moperation4pdf(i1,i2,operator)
% INPUT
% i1 first operand
% i2 second operand
% At least one of the two operands is a PDF.
% operation string defining operation to perform. Possible values are:
% '+', '-', '*', '/', '^'
% OUTPUT
% ds result of the operation
if istype(i1,'pdf') % First input argument is a PDF
if isnumeric(i2) % and second input dataset is numeric
ds=i1;
if numel(i2) == 1
switch operator
case '+'
ds.pdf=i1.pdf+i2;
case '-'
ds.pdf=i1.pdf-i2;
case '*'
ds.pdf=i1.pdf*i2;
case '/'
ds.pdf=i1.pdf/i2;
case '^'
ds.pdf=i1.pdf.^i2;
otherwise
disp([' Unknown operator "',operator,'".'])
error(' Abnormal termination.')
end
else
disp([' The operator "',operator, ...
'" is not defined for these arguments (PDF and vector or matrix).'])
error(' Abnormal termination.')
end
elseif istype(i2,'pdf') % Both input datasets are PDF's
ds=pd_operation(i1,i2,operator);
else
disp([' The operator "',operator,'" is not defined for these arguments.'])
error(' Abnormal termination.')
end
elseif istype(i2,'pdf') && ... % Second input dataset is a PDF
isnumeric(i1) % and first input dataset is numeric
ds=i2;
if numel(i1) == 1
switch operator
case '+'
ds.pdf=i1+ds.pdf;
case '-'
ds.pdf=i1-ds.pdf;
case '*'
ds.pdf=i1*ds.pdf;
case '/'
ds.pdf=i1./ds.pdf;
case '^'
ds.pdf=i1.^ds.pdf;
otherwise
disp([' Unknown operator "',operator,'".'])
error(' Abnormal termination.')
end
else
error(['Operator "',operator, ...
'" is not defined for these argument (vector or matrix and PDF).'])
end
else
error(['The operator "',operator,'" is not defined for these arguments.'])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=moperation4seismic(i1,i2,operator)
% Perform the operation defined by input argument "operator" to the first two
% input arguments
%
% Written by: E. Rietsch: December 7, 2006
% Last updated:
%
% ds=moperation4seismic(i1,i2,operator)
% INPUT
% i1 first operand
% i2 second operand
% At least one of the two operands is a seismic dataset.
% operation string defining operation to perform. Possible values are:
% '+', '-', '*', '/', '^'
% OUTPUT
% ds result of the operation
switch operator
case '+'
ds=plus_no1(i1,i2);
case '-'
ds=minus_no2(i1,i2);
case '*'
ds=times_no3(i1,i2);
case '/'
ds=mrdivide_no4(i1,i2);
case '^'
ds=power_no5(i1,i2);
otherwise
disp([' Unknown operator "',operator,'".'])
error(' Abnormal termination.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=plus_no1(i1,i2)
% Function adds a constant or matrix to traces of seismic dataset
% Written by: E. Rietsch: September 11, 2005
% Last updated:
if isstruct(i1) && strcmp(i1.type,'seismic') && isnumeric(i2)
ds=i1;
sz=size(i2);
[nsamp,ntr]=size(i1.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=ds.traces+i2;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:)+i2;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii)+i2;
end
else
error('Operator "+" is not defined for this size of summand.')
end
end
elseif isstruct(i2) && strcmp(i2.type,'seismic') && isnumeric(i1)
ds=i2;
sz=size(i1);
[nsamp,ntr]=size(i2.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=ds.traces+i1;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:)+i1;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii)+i1;
end
else
error('Operator "+" is not defined for this size of summand.')
end
end
else
error('Operator "+" is not defined for these arguments.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=minus_no2(i1,i2)
% Function adds a constant or matrix to traces of seismic dataset
% Written by: E. Rietsch: September 11, 2005
% Last updated:
if isstruct(i1) && strcmp(i1.type,'seismic') && isnumeric(i2)
ds=i1;
sz=size(i2);
[nsamp,ntr]=size(i1.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=ds.traces-i2;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:)-i2;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii)-i2;
end
else
error('Operator "-" is not defined for this size of subtrahend.')
end
end
elseif isstruct(i2) && strcmp(i2.type,'seismic') && isnumeric(i1)
ds=i2;
sz=size(i1);
[nsamp,ntr]=size(i2.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=i1-ds.traces;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=i1-ds.traces(ii,:);
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=i1-ds.traces(:,ii);
end
else
error('Operator "-" is not defined for this size of subtrahend.')
end
end
else
error('Operator "-" is not defined for these arguments.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=times_no3(i1,i2)
% Function multiplies a constant or matrix elementwise with traces
% of a seismic dataset
%
% Written by: E. Rietsch: September 11, 2005
% Last updated:
if isstruct(i1) && strcmp(i1.type,'seismic') && isnumeric(i2)
ds=i1;
sz=size(i2);
[nsamp,ntr]=size(i1.traces);
if numel(i2) == 1
ds.traces=ds.traces.*i2;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:).*i2;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii).*i2;
end
elseif all(sz == [nsamp,ntr])
ds.traces=ds.traces.*i2;
else
error('The operator "*" is not defined for this size of matrix.')
end
end
elseif isstruct(i2) && strcmp(i2.type,'seismic') && isnumeric(i1)
ds=i2;
sz=size(i1);
[nsamp,ntr]=size(i2.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=ds.traces.*i1;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:).*i1;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii).*i1;
end
elseif all(sz == [nsamp,ntr])
ds.traces=ds.traces.*i1;
else
error('Operator "*" is not defined for this size of matrix.')
end
end
else
error('The operator "*" is not defined for these two arguments.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=mrdivide_no4(i1,i2)
% Function multiplies a constant or matrix elementwise with traces
% of a seismic dataset
%
% Written by: E. Rietsch: September 11, 2005
% Last updated:
if isstruct(i1) && strcmp(i1.type,'seismic') && isnumeric(i2)
ds=i1;
sz=size(i2);
[nsamp,ntr]=size(i1.traces);
if numel(i2) == 1
ds.traces=ds.traces./i2;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=ds.traces(ii,:)./i2;
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=ds.traces(:,ii)./i2;
end
elseif all(sz == [nsamp,ntr])
ds.traces=ds.traces./i2;
else
error('The operator "/" is not defined for this size of matrix.')
end
end
elseif isstruct(i2) && strcmp(i2.type,'seismic') && isnumeric(i1)
ds=i2;
sz=size(i1);
[nsamp,ntr]=size(i2.traces);
if prod(sz) == 1 || all(sz == [nsamp,ntr])
ds.traces=i1./ds.traces;
else
if all(sz == [1,ntr])
for ii=1:nsamp
ds.traces(ii,:)=i1./ds.traces(ii,:);
end
elseif all(sz == [nsamp,1])
for ii=1:ntr
ds.traces(:,ii)=i1./ds.traces(:,ii);
end
elseif all(sz == [nsamp,ntr])
ds.traces=i1./ds.traces;
else
error('Operator "*" is not defined for this size of matrix.')
end
end
else
error('The operator "*" is not defined for these two arguments.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=power_no5(i1,i2)
% Function takes the power of the traces of a seismic dataset
%
% Written by: E. Rietsch: September 11, 2005
% Last updated:
if isstruct(i1) && isnumeric(i2) && numel(i2) == 1
ds=i1;
ds.traces=ds.traces.^i2;
elseif isstruct(i2) && isnumeric(i1) && numel(i1) == 1
ds=i2;
ds.traces=i1.^ds.traces;
else
error('Operator ".^" is not defined for these arguments.')
end
|
github
|
Abakumov/MLIB-master
|
uoperation.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/@struct/uoperation.m
| 2,202 |
utf_8
|
02037835badbe268b7a2e07f3b9a1b92
|
function ds=uoperation(ds,operator)
% Function performs a unary operation on a dataset
%
% Written by: E. Rietsch: December 7, 2006
% Last updated:
%
% ds=uoperation(i1,operator)
% INPUT
% i1 operand
% At least one of the two operands is a dataset.
% operator string defining operation to perform. Possible values are:
% '+', '-'
% OUTPUT
% ds result of the operation
if ~isfield(ds,'type')
error(['Operation "',operator,'" is not defined for this structure.'])
end
switch ds.type
case 'seismic'
ds=uoperation4seismic(ds,operator);
case 'pdf'
ds=uoperation4pdf(ds,operator);
otherwise
error(['The operator "',operator,'" is not defined for this structure.'])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=uoperation4seismic(ds,operator)
% Perform the operation defined by input argument "operator" to the
% input argument
%
% Written by: E. Rietsch: July 12, 2006
% Last updated:
%
% ds=uoperation4pdf(ds,operator)
% INPUT
% ds seismic dataset
% operation string defining operation to perform. Possible values are:
% '+', '-'
% OUTPUT
% ds result of the operation
switch operator
case '+'
% Do nothing
case '-'
ds.traces=-ds.traces;
otherwise
disp([' Unknown operator "',operator,'".'])
error(' Abnormal termination.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=uoperation4pdf(ds,operator)
% Perform the operation defined by input argument "operator" to the
% input argument
%
% Written by: E. Rietsch: July 12, 2006
% Last updated: September 16, 2006: Add handling of PDF's
%
% ds=uoperation4pdf(i1,i2,operator)
% INPUT
% ds PDF
% operation string defining operation to perform. Possible values are:
% '+', '-',
% OUTPUT
% ds result of the operation
switch operator
case '+'
% Do nothing
case '-'
ds.pdf=-ds.pdf;
try
ds.cdf=-ds.cdf;
catch
% Do nothing
end
otherwise
disp([' Unknown operator "',operator,'".'])
error(' Abnormal termination.')
end
|
github
|
Abakumov/MLIB-master
|
showcell.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Other/showcell.m
| 15,711 |
utf_8
|
7cf9c7a0321ab88200801279b1c0b63a
|
function showcell(varargin)
%SHOWCELL Displays cell array with long strings in the command window.
% SHOWCELL(A) displays the contents of a cell array A in the command
% window. It will format the display so that long strings will display
% appropriately. A can be a cell array of numbers, strings, and/or other
% objects.
%
% Typically, if a cell array contains long strings, it will not display
% the text:
%
% >> A
%
% A =
%
% [3] 'this is a text.' 'hello'
% [4] 'More text' [ 32]
% [6] [1x54 char] [ 53]
%
% SHOWCELL will display it properly:
%
% >> showcell(A)
% [ 3] 'this is a text.' 'hello'
% [ 4] 'More text' [32]
% [ 6] 'This is a very long text that may not show up properly' [53]
%
% Acceptable numbers are of class DOUBLE, SINGLE, LOGICAL, UINT8, UINT16,
% UINT32, UINT64, INT8, INT16, INT32, INT64. Elements other than CHAR or
% numbers are displayed as the size and name of the object,
% e.g. [1x1 struct]
%
% SHOWCELL(A,'option1',value1,...) specifies optional arguments passed
% in in pairs. Valid options are (abbreviated names accepted):
%
% 'spacing' - column spacing. Default is 4 spaces.
% 'numformat' - number of digits OR format string (see SPRINTF) for
% numerical values. Default is 5 digits.
%
% Example:
% showcell(A, 'spacing', 5);
% showcell(A, 'numformat', 3);
% showcell(A, 'n', '%0.4f');
% showcell(A, 'sp', 2, 'nu', 6);
%
% See also DISP, DISPLAY
%
%
% VERSIONS:
% v1.0 - first version
% v1.1 - add quotes around strings (Jan 2006)
% v1.2 - accepts uint8, uint16, uint32, uint64, int8, int16, int32,
% int64, single, double, logical for numeric values.
% v2.0 - each column does not have to be of the same class. the cell
% elements can be of any class. (Jan 2006)
% v2.1 - fixed problems with displaying empty cell elements. (Jan 2006)
% v2.2 - fixed displaying an empty cell {}. Remove MORE function, since
% this can be achieved externally by calling MORE. (Jan 2006)
% v2.3 - now displays multi-dimension cells (Feb 10, 2006)
%
% Jiro Doke
% June 2004
%-----------------------------------------------------------------------
% Check cell array
%-----------------------------------------------------------------------
if ~nargin
return;
end
arg = varargin{1};
if ~iscell(arg)
error('This is not a cell array.');
end
%-----------------------------------------------------------------------
% Parse optional arguments
%-----------------------------------------------------------------------
% Default values
num_spaces = 4;
num_digits = 5;
% Possible optional arguments
optSpacing = 'spacing ';
optNumformat = 'numformat';
if nargin > 1
vars = varargin(2 : end);
if mod(length(vars) , 2)
error('The optional arguments must come in pairs.');
end
for id = 1 : 2 : length(vars)
% Get number of characters provided for optional arguments
% Accepts abbreviated option names
varC = min([length(vars{id}), 9]);
switch lower(vars{id})
case optSpacing(1 : varC) % SPACING
if isnumeric(vars{id + 1})
num_spaces = round(vars{id + 1});
else
error('Bad value for SPACING. Must be an integer');
end
case optNumformat(1 : varC) % NUMFORMAT
if isnumeric(vars{id + 1})
num_digits = round(vars{id + 1});
else
num_digits = vars{id + 1};
end
otherwise
error('Unknown option.');
end
end
end
%-----------------------------------------------------------------------
% Deal with multi-dimension cells
%-----------------------------------------------------------------------
isLoose = isequal(get(0,'FormatSpacing'),'loose');
if ndims(arg) > 2
sz = size(arg);
id = cell(ndims(arg) - 2, 1);
else
sz = [0 0 1];
end
for ii = 1:prod(sz(3:end))
if exist('id', 'var')
[id{:}] = ind2sub(sz(3:end), ii); %#ok
str = ['(:,:', sprintf(',%d', id{:}), ')'];
this_arg = arg(:, :, id{:});
else
this_arg = arg;
str = '';
end
if ~isempty(inputname(1))
if isLoose
disp(' ');
fprintf('%s%s =\n', inputname(1), str);
disp(' ');
else
fprintf('%s%s =\n', inputname(1), str);
end
end
if isequal(size(this_arg), [0 0])
disp(' {}');
if isLoose
disp(' ');
end %
elseif ismember(0, size(this_arg))
fprintf(' Empty cell array: %d-by-%d\n', size(this_arg));
if isLoose
disp(' ')
end %
else
showcellEngine(this_arg, num_spaces, num_digits);
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
% showcellEngine
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function showcellEngine(arg, num_spaces, num_digits)
%-----------------------------------------------------------------------
% Determine class of cell elements
%-----------------------------------------------------------------------
cellArg = arg(:);
isNumChar = false(length(cellArg), 12);
isNumChar(:, 1) = cellfun('isclass', cellArg, 'char' );
isNumChar(:, 2) = cellfun('isclass', cellArg, 'double' );
isNumChar(:, 3) = cellfun('isclass', cellArg, 'single' );
isNumChar(:, 4) = cellfun('isclass', cellArg, 'uint8' );
isNumChar(:, 5) = cellfun('isclass', cellArg, 'uint16' );
isNumChar(:, 6) = cellfun('isclass', cellArg, 'uint32' );
isNumChar(:, 7) = cellfun('isclass', cellArg, 'uint64' );
isNumChar(:, 8) = cellfun('isclass', cellArg, 'int8' );
isNumChar(:, 9) = cellfun('isclass', cellArg, 'int16' );
isNumChar(:, 10) = cellfun('isclass', cellArg, 'int32' );
isNumChar(:, 11) = cellfun('isclass', cellArg, 'int64' );
isNumChar(:, 12) = cellfun('isclass', cellArg, 'logical');
% Number of elements in cell element
numElmt = cellfun('prodofsize', cellArg);
% Remove number cells with vectors (more than a scalar)
isNumChar(:, 2:end) = isNumChar(:, 2:end) & repmat(numElmt <= 1, 1, 11);
% Number elements
isNum = ~~sum(isNumChar(:, 2:end), 2);
% Cell elements
cellElements = cellfun('isclass', cellArg, 'cell');
% Empty elements
emptyElements = cellfun('isempty', cellArg);
emptyCells = emptyElements & cellElements;
emptyNums = emptyElements & isNum;
% All other objects (including objects with more than one element)
isObj = xor(emptyCells, ~sum(isNumChar, 2));
% Discard empty number elements. These will be processed separately.
isNumChar(isNumChar & repmat(emptyNums, 1, size(isNumChar, 2))) = false;
%-----------------------------------------------------------------------
% Deal with empty elements
%-----------------------------------------------------------------------
if any(emptyCells)
cellArg(emptyCells) = {'{}'};
end
if any(emptyNums)
cellArg(emptyNums) = {'[]'};
end
%-----------------------------------------------------------------------
% Deal with numeric elements
%-----------------------------------------------------------------------
numID = logical(sum(isNumChar(:, 2:end), 2));
if ~isempty(find(numID,1))
TOdouble = repmat(NaN, length(cellArg), 1);
% Convert the numeric/logical values to double
useIDX = find(sum(isNumChar(:, 2:end)));
% Only parse through valid types
for iType = useIDX + 1
TOdouble(isNumChar(:, iType), 1) = ...
double([cellArg{isNumChar(:, iType)}]');
end
TOdouble(~numID) = [];
% Convert DOUBLE to strings and put brackets around them
try
tmp = strcat({'['}, num2str(TOdouble, num_digits), {']'});
catch % ME
% getReport(ME)
error('Abnormal termination')
end
cellArg(numID) = tmp;
end
%-----------------------------------------------------------------------
% Deal with string elements
%-----------------------------------------------------------------------
% Put single quotes around the strings
stringCell = strcat({''''}, cellArg(isNumChar(:, 1)), {''''});
cellArg(isNumChar(:, 1)) = stringCell;
%-----------------------------------------------------------------------
% Deal with elements other than string or numeric
%-----------------------------------------------------------------------
objID = find(isObj);
objCell = cell(length(objID), 1);
for iObj = 1:length(objID)
sz = size(cellArg{objID(iObj)});
cl = class(cellArg{objID(iObj)});
% Display size and class type, wrapped by brackets
switch cl
case 'cell'
if length(sz) < 4
objCell{iObj} = ['{', sprintf('%dx', sz(1:end-1)), ...
num2str(sz(end)), sprintf(' %s}', cl)];
else
objCell{iObj} = sprintf('{%d-D %s}', length(sz), cl);
end
otherwise
if length(sz) < 4
objCell{iObj} = ['[', sprintf('%dx', sz(1:end-1)), ...
num2str(sz(end)), sprintf(' %s]', cl)];
else
objCell{iObj} = sprintf('[%d-D %s]', length(sz), cl);
end
end
end
cellArg(isObj) = objCell;
% Reconstruct the original size
arg = reshape(cellArg, size(arg));
%-----------------------------------------------------------------------
% Create FPRINTF format string based on length of strings
%--------------------------------------------------------------------------
char_len = cellfun('length', arg); %
if 0 % Change this to 1 in order to right justify numeric elements.
% This will be slightly slower.
conv_str = ' ';
for iCol = 1:size(arg, 2);
if length(unique(char_len(:, iCol))) == 1
conv_str = [conv_str, ...
sprintf('%%-%ds%s', unique(char_len(:, iCol)), ...
blanks(num_spaces))]; %#ok Don't bother ...
else
tmp = char(arg(:, iCol));
idx1 = strfind(tmp(:, 1)', '[');
idx2 = strfind(tmp(:, 1)', '{');
tmp([idx1 idx2], :) = strjust(tmp([idx1 idx2], :), 'right');
arg(:, iCol) = cellstr(tmp);
conv_str = [conv_str, ...
sprintf('%%-%ds%s', max(char_len(:, iCol)), ...
blanks(num_spaces))]; %#ok Don't bother ...
end
end
else
% Create array of max character lengths and blank pads
char_max = [num2cell(max(char_len, [], 1)); ...
repmat({blanks(num_spaces)}, 1, size(char_len, 2))];
conv_str = [' ', sprintf('%%-%ds%s', char_max{:})];
end
% Add carrige return at the end
conv_str = [conv_str(1 : end - num_spaces) '\n'];
%--------------------------------------------------------------------------
% Display in command window
%--------------------------------------------------------------------------
% Must transpose for FPRINTF to work
arg = arg';
% If arg is a single EMPTY cell/string/numeric element,
% then wrap it with {}
if length(arg) == 1
switch arg{1}
case {'{}', '''''', '[]'}
conv_str = ' {%s}\n';
end
end
try
% Wrap around TRY ... END in case the user quits out of MORE
fprintf(1, conv_str, arg{:});
if isequal(get(0,'FormatSpacing'),'loose')
disp(' ');
end
catch
% Do nothing
end
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
|
github
|
Abakumov/MLIB-master
|
advexpfig.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Other/advexpfig.m
| 7,202 |
utf_8
|
308b54048af84e282ec73b1536c774ab
|
function [result,msg] = advexpfig(fh,fName,format,varargin)
% ADVEXPFIG Exports a figure into a file (all internal formats are
% supported as well as some formats generated indirectly using an
% intermediary eps format.
%
% [result,msg] = ADVAXPFIG(fh,fName,format,varargin)
% Creates an output from the figure fg.
%
% - fh: figure handle to export
% - fName: name of the file to create (if the extension is not
% given it will be appended automatically according to
% the format used)
% - format: output format: all formats that are available for the
% print command (e.g.:'-dbmpmono', '-dbmp16m',... ; see
% the help of the print function) plus some additional
% "indirect" formats which uses eps format as the
% intermediary format:
% 'jpg<-eps', 'pdf<-eps', 'png<-eps', 'tiff<-eps'
% The cons of these intermediary formats are that figures
% have nicer look while the resulting figures have sizes
% dictated by the bounding box from the intermediary eps
% figure and not by the paper size.
% This is especialy suited for LaTeX users for example to
% use these figure when creating documents,... But, to
% use these intermediary formats, GhostScript must be
% installed (se the 'gs' parameter in varargin) as well
% as the EPS2XXX function must be available.
% - varargin: (optional) property-value pairs of additional
% switches/settings (note that they must come in PAIRS):
% 'ui': can be 'on' (default) if ui objects are to be
% exported as well or 'off' if not
% 'w': changed width of the figure in cm (e.g. 15)
% 'h': changed height of the figure in cm (e.g. 9)
% 'res': resolution in dpi; given as a number;
% defaults to whatever is set to be default
% in the Matlab's print function
% 'colored': 1 or 0; applicable to indirect formats only
% 'renderer': '-painters', '-opengl, '-zbuffer'; if not
% used, the current renderer is used
% 'gs': path to the GhostScript executable; used
% for the formats generated indirectly;
% defaults to 'gswin32c.exe' in win32 and to
% 'gs' in other platforms; if the executable
% is not in the system's path, the full path
% should be given
%
% - result: (optional); -1: errors, no file created; 0: file(s) created but
% there were warnings; 1: OK (no errors or warnings)
% - msg: (optional); resulting status on file being processed (confirmation string , error
% string or warning string)
%
% Examples:
% advexpfig(gcf,'test.eps','-deps2c','w',15,'h',9)
%
% Notes: for formats generated indirectly this function uses the function
% EPS2XXX. If result and msg are given, no error is raised as this
% variables holds the status.
%
% See also: EPS2XXX
%
% Primoz Cermelj, 07.10.2004
% (c) Primoz Cermelj, [email protected]
% Last revision: 24.11.2005
%--------------------------------------------------------------------------
if nargin < 3
error('Not enough parametrs given (at least 3 required)');
end
if ~ischar(format)
error('Format must be given as a string');
end
[w,h,gs,colored,optStr] = setoptions(varargin);
units = get(fh,'Units');
paperMode = get(fh,'PaperPositionMode');
set(fh,'PaperPositionMode','auto');
set(fh,'Units','centimeters');
pos = get(fh,'Position');
oldPos = pos;
newPos = pos;
% Change the size of the figure
if ~isempty(w)
newPos(3) = w;
end
if ~isempty(h)
newPos(4) = h;
end
set(fh,'Position',newPos);
% Set the intermediary file name and format if required
if format(1) ~= '-'
% intermediary format
if colored
gformat = '-deps2c'; %#ok Used in "eval"
else
gformat = '-deps2'; %#ok Used in "eval"
end
[pathstr,sourceName,ext] = fileparts(fName);
if isempty(ext)
ext = '.eps~';
else
ext = [ext '~'];
end
if isempty(pathstr)
pathstr = cd;
end
fName = fullfile(pathstr,[sourceName ext]);
intermediary = 1;
switch lower(format)
case 'jpg<-eps'
iformat = 'jpeg';
case 'pdf<-eps'
iformat = 'pdf';
case 'png<-eps'
iformat = 'png';
case 'tiff<-eps'
iformat = 'tiff';
otherwise
error(['Unknown intermediary format: ' format]);
end
else
gformat = format; %#ok Used in "eval"
intermediary = 0;
end
% Print the figure to a file
eval(['print(fh,fName,gformat', optStr, ')']);
% Restore the original figure
set(fh,'Position',oldPos);
set(fh,'Units',units);
set(fh,'PaperPositionMode',paperMode);
result = 1;
msg = '';
% If intermediary format is used, convert the figure appropriately
if intermediary
[res,resMsg] = eps2xxx(fName,cellstr(iformat),gs);
% Delete the intermediary-format file
if exist(fName,'file')
delete(fName);
end
result = res;
msg = resMsg;
if ~nargout
if res < 0 % error
error(['File not created :' resMsg]);
end
if res == 0 % warning
warning(['Warning :' resMsg]); %#ok
end
end
end
%-----------------------------------------------------------------
function [w,h,gs,colored,optStr] = setoptions(varargin)
% Gets the w, h, gs string and the options string from the varargin
% parameters.
%Defaults
w = [];
h = [];
gs = [];
optStr = '';
colored = 0;
if isempty(varargin{:})
return
end
% Get the options from the varargin
n = length(varargin{:});
if mod(n,2)~= 0
error('Additional parameters must be given in property-value pairs');
end
for ii=1:2:n-1
prop = varargin{:}{ii};
value = varargin{:}{ii+1};
if ~ischar(prop)
error('Property name must be given as a string');
end
switch lower(prop)
case 'ui'
if strcmpi(value,'off')
optStr = [optStr ',''-noui''']; %#ok
end
case 'w'
w = value;
case 'h'
h = value;
case 'res'
optStr = [optStr ',''' '-r' num2str(value) '''']; %#ok
case 'renderer'
if ~isempty(value)
optStr = [optStr ',''' value '''']; %#ok
end
case 'gs'
gs = value;
case 'colored'
colored = value > 0;
otherwise
error('Wrong property given')
end
end
|
github
|
Abakumov/MLIB-master
|
FSM2DVTI.m
|
.m
|
MLIB-master/FSM/FSM2DVTI.m
| 13,546 |
utf_8
|
f050076dbf1ed753cb28fd6f7eab8983
|
%% Main function
function out = FSM2DVTI(G, S, alpha, betta, gamma, delta, epsilon)
% Find minimum values
alpmin = min(min(alpha));
betmin = min(min(betta));
delmin = min(min(delta));
gammin = min(min(gamma));
epsmin = min(min(epsilon));
% Definition of elastic parameters
[Gnx, Gnz] = size(alpha);
A33 = ones(Gnx+2, Gnz+2)*alpmin^2;
A44 = ones(Gnx+2, Gnz+2)*betmin^2;
A11 = ones(Gnx+2, Gnz+2)*alpmin^2*(1+2*epsmin);
A66 = ones(Gnx+2, Gnz+2)*betmin^2*(1+2*gammin);
A13 = ones(Gnx+2, Gnz+2)*(alpmin^2 - betmin^2)*sqrt(1 + 2*delmin/(1-(betmin^2/alpmin^2))) - betmin^2;
for i=1:Gnx
for j=1:Gnz
alp2 = alpha(i,j)^2;
bet2 = betta(i,j)^2;
del = delta(i,j);
gam = gamma(i,j);
eps = epsilon(i,j);
A33(i+1, j+1) = alp2;
A44(i+1, j+1) = bet2;
A11(i+1, j+1) = alp2*(1+2*eps);
A66(i+1, j+1) = bet2*(1+2*gam);
A13(i+1, j+1) = (alp2 - bet2)*sqrt(1 + 2*del/(1-(bet2/alp2))) - bet2;
end
end
% Initialize times in source zone manually
tti = initialize_VTI_qP(G,S,A11,A33,A13,A44);
% Update times with FSM algorithm
out = fsmalgorithm_VTI_qP(G,A11,A33,A13,A44,tti);
%% Initialization
function tti = initialize_VTI_qP(G,S,A11,A33,A13,A44)
tmax = 1.e20;
tti = ones(size(A11))*tmax;
Gox=G(1); Goz=G(3);
Gnx=G(4); Gnz=G(6);
Gdx=G(7); Gdz=G(9);
Gmx = Gox + (Gnx-1)*Gdx;
Gmz = Goz + (Gnz-1)*Gdz;
if(S(1)<Gox || S(1)>Gmx || S(2)<Goz || S(2)>Gmz)
disp('Shot coordinates out of range');
end
Gsx = x2grid(S(1),Gox,Gdx,Gnx);
Gsz = x2grid(S(2),Goz,Gdz,Gnz);
tti(Gsx+1, Gsz+1)=0; % +1 due to general shift
for i=-5:1:5
for j=-5:1:5
indx = max(1, Gsx+1+i);
indx = min(Gnx+2, indx);
indz = max(1, Gsz+1+j);
indz = min(Gnz+2, indz);
a11 = A11(Gsx+1, Gsz+1);
a33 = A33(Gsx+1, Gsz+1);
a13 = A13(Gsx+1, Gsz+1);
a44 = A44(Gsx+1, Gsz+1);
x = max(Gox, Gox + (Gsx+i-1)*Gdx);
x = min(Gmx, x);
z = max(Goz, Goz + (Gsz+j-1)*Gdz);
z = min(Gmz, z);
dx = x - S(1);
dz = z - S(2);
dist = sqrt(dx.^2 + dz.^2);
if dist == 0
tti(indx, indz)=0;
else
ST = dx/dist;
Vg = GetVg(a11,a33,a13,a44,ST);
tti(indx, indz)=dist/Vg;
end
end
end
%% General FSM solver
function tvltm = fsmalgorithm_VTI_qP(G,A11,A33,A13,A44,tti)
step = G(7);
tmax = 1.e20;
[sx, sz] = size(tti);
xmin=2; xmax=sx-1;
zmin=2; zmax=sz-1;
sq1 = sqrt(2)/2;
sq2 = sqrt(2);
tr(1,:) = [-1.0, -1.0, 0.0, -1.0, sq2, 1.0, sq1, sq1, 0.0, 1.0];
tr(2,:) = [ 0.0, -1.0, 1.0, -1.0, 1.0, sq2, 0.0, 1.0, -sq1, sq1];
tr(3,:) = [ 1.0, -1.0, 1.0, 0.0, sq2, 1.0, -sq1, sq1, -1.0, 0.0];
tr(4,:) = [ 1.0, 0.0, 1.0, 1.0, 1.0, sq2, -1.0, 0.0, -sq1, -sq1];
tr(5,:) = [ 1.0, 1.0, 0.0, 1.0, sq2, 1.0, -sq1, -sq1, 0.0, -1.0];
tr(6,:) = [ 0.0, 1.0, -1.0, 1.0, 1.0, sq2, 0.0, -1.0, sq1, -sq1];
tr(7,:) = [-1.0, 1.0, -1.0, 0.0, sq2, 1.0, sq1, -sq1, 1.0, 0.0];
tr(8,:) = [-1.0, 0.0, -1.0, -1.0, 1.0, sq2, 1.0, 0.0, sq1, sq1];
for iter=1:2
for i=xmin:xmax
for j=zmin:zmax
a11 = A11(i,j);
a33 = A33(i,j);
a13 = A13(i,j);
a44 = A44(i,j);
K = GetK(a11,a33,a13,a44);
for triang = 1:8
Ta = tti(i+tr(triang, 1), j+tr(triang, 2));
Tb = tti(i+tr(triang, 3), j+tr(triang, 4));
b = tr(triang, 5)*step;
a = tr(triang, 6)*step;
N = tr(triang, 7:10);
TC = GetTC(Ta, Tb, a, b, N, K);
for r = 1:4
TCr = TC(r);
if (TCr<tmax)
Vg = CheckVg(Ta, Tb, a, b, N, K, TCr);
if Vg==0
TC(r) = tmax;
end
end
end
TCn = min(real(TC));
Vga = GetVg(a11,a33,a13,a44,N(1)); % N(1) = n11 = sin(theta)
TCa = Ta + b/Vga;
Vgb = GetVg(a11,a33,a13,a44,N(3)); % N(3) = n21 = sin(theta)
TCb = Tb + a/Vgb;
TCo = tti(i,j);
tti(i, j) = min([TCn, TCa, TCb, TCo]);
end
end
end
%2
for i=xmin:xmax
for j=zmax:-1:zmin
a11 = A11(i,j);
a33 = A33(i,j);
a13 = A13(i,j);
a44 = A44(i,j);
K = GetK(a11,a33,a13,a44);
for triang = 1:8
Ta = tti(i+tr(triang, 1), j+tr(triang, 2));
Tb = tti(i+tr(triang, 3), j+tr(triang, 4));
b = tr(triang, 5)*step;
a = tr(triang, 6)*step;
N = tr(triang, 7:10);
TC = GetTC(Ta, Tb, a, b, N, K);
for r = 1:4
TCr = TC(r);
if (TCr<tmax)
Vg = CheckVg(Ta, Tb, a, b, N, K, TCr);
if Vg==0
TC(r) = tmax;
end
end
end
TCn = min(real(TC));
Vga = GetVg(a11,a33,a13,a44,N(1)); % N(1) = n11 = sin(theta)
TCa = Ta + b/Vga;
Vgb = GetVg(a11,a33,a13,a44,N(3)); % N(3) = n21 = sin(theta)
TCb = Tb + a/Vgb;
TCo = tti(i,j);
tti(i, j) = min([TCn, TCa, TCb, TCo]);
end
end
end
% 3
for i=xmax:-1:xmin
for j=zmin:zmax
a11 = A11(i,j);
a33 = A33(i,j);
a13 = A13(i,j);
a44 = A44(i,j);
K = GetK(a11,a33,a13,a44);
for triang = 1:8
Ta = tti(i+tr(triang, 1), j+tr(triang, 2));
Tb = tti(i+tr(triang, 3), j+tr(triang, 4));
b = tr(triang, 5)*step;
a = tr(triang, 6)*step;
N = tr(triang, 7:10);
TC = GetTC(Ta, Tb, a, b, N, K);
for r = 1:4
TCr = TC(r);
if (TCr<tmax)
Vg = CheckVg(Ta, Tb, a, b, N, K, TCr);
if Vg==0
TC(r) = tmax;
end
end
end
TCn = min(real(TC));
Vga = GetVg(a11,a33,a13,a44,N(1)); % N(1) = n11 = sin(theta)
TCa = Ta + b/Vga;
Vgb = GetVg(a11,a33,a13,a44,N(3)); % N(3) = n21 = sin(theta)
TCb = Tb + a/Vgb;
TCo = tti(i,j);
tti(i, j) = min([TCn, TCa, TCb, TCo]);
end
end
end
%4
for i=xmax:-1:xmin
for j=zmax:-1:zmin
a11 = A11(i,j);
a33 = A33(i,j);
a13 = A13(i,j);
a44 = A44(i,j);
K = GetK(a11,a33,a13,a44);
for triang = 1:8
Ta = tti(i+tr(triang, 1), j+tr(triang, 2));
Tb = tti(i+tr(triang, 3), j+tr(triang, 4));
b = tr(triang, 5)*step;
a = tr(triang, 6)*step;
N = tr(triang, 7:10);
TC = GetTC(Ta, Tb, a, b, N, K);
for r = 1:4
TCr = TC(r);
if (TCr<tmax)
Vg = CheckVg(Ta, Tb, a, b, N, K, TCr);
if Vg==0
TC(r) = tmax;
end
end
end
TCn = min(real(TC));
Vga = GetVg(a11,a33,a13,a44,N(1)); % N(1) = n11 = sin(theta)
TCa = Ta + b/Vga;
Vgb = GetVg(a11,a33,a13,a44,N(3)); % N(3) = n21 = sin(theta)
TCb = Tb + a/Vgb;
TCo = tti(i,j);
tti(i, j) = min([TCn, TCa, TCb, TCo]);
end
end
end
end
tvltm = tti(2:end-1, 2:end-1);
%% Define coefficients
function K = GetK(A11,A33,A13,A44)
K = zeros(5, 1);
K(1) = -A11*A44;
K(2) = -A33*A44;
K(3) = -A11*A33 - A44^2 + (A13+A44)^2;
K(4) = A11 + A44;
K(5) = A33 + A44;
%% Find roots of Hamiltonian
function TC = GetTC(Ta, Tb, a, b, N, K)
cosg = sqrt(2)/2;
tmax = 1.e20;
W = zeros(5, 1);
n11 = N(1); n12 = N(2); n21 = N(3); n22 = N(4);
k1 = K(1); k2 = K(2); k3 = K(3); k4 = K(4); k5 = K(5);
p11 = 2*(n11 - n21*cosg); % 2 == 1/sin^2(gamma)
p12 = 2*(n21 - n11*cosg);
p21 = 2*(n12 - n22*cosg);
p22 = 2*(n22 - n12*cosg);
g1 = p11/b + p12/a;
g2 = -(p11/b*Ta + p12/a*Tb);
g3 = p21/b + p22/a;
g4 = -(p21/b*Ta + p22/a*Tb);
W(1) = g1*g1*g1*g1*k1 + g3*g3*g3*g3*k2 + g1*g1*g3*g3*k3;
W(2) = 4*g1*g1*g1*g2*k1 + 4*g3*g3*g3*g4*k2 + (2*g1*g1*g3*g4 + 2*g1*g2*g3*g3)*k3;
W(3) = 6*g1*g1*g2*g2*k1 + 6*g3*g3*g4*g4*k2 + ( g1*g1*g4*g4 + 4*g1*g2*g3*g4 + g2*g2*g3*g3)*k3 + g1*g1*k4 + g3*g3*k5;
W(4) = 4*g1*g2*g2*g2*k1 + 4*g3*g4*g4*g4*k2 + (2*g1*g2*g4*g4 + 2*g2*g2*g3*g4)*k3 + 2*g1*g2*k4 + 2*g3*g4*k5;
W(5) = g2*g2*g2*g2*k1 + g4*g4*g4*g4*k2 + g2*g2*g4*g4*k3 + g2*g2*k4 + g4*g4*k5 - 1;
%disp(['W(1) =' num2str(W(1)), ' W(2) =' num2str(W(2)) ' W(3) =' num2str(W(3)), ' W(4) =' num2str(W(4)), ' W(5) =' num2str(W(5))])
TC = roots(W);
Tm = min(Ta, Tb);
for i=1:4
iTC = imag(TC(i));
rTC = real(TC(i));
if (iTC~=0 || rTC<Tm)
TC(i) = tmax;
end
end
%% Check group velocity
function Vg = CheckVg(Ta, Tb, a, b, N, K, Tc)
Vg=0;
cosg = sqrt(2)/2;
n11 = N(1); n12 = N(2); n21 = N(3); n22 = N(4);
k1 = K(1); k2 = K(2); k3 = K(3); k4 = K(4); k5 = K(5);
p11 = 2*(n11 - n21*cosg); % 2 == 1/sin^2(gamma)
p12 = 2*(n21 - n11*cosg);
p21 = 2*(n12 - n22*cosg);
p22 = 2*(n22 - n12*cosg);
g1 = p11/b + p12/a;
g2 = -(p11/b*Ta + p12/a*Tb);
g3 = p21/b + p22/a;
g4 = -(p21/b*Ta + p22/a*Tb);
p1 = g1*Tc + g2;
p3 = g3*Tc + g4;
V(1) = 4*k1*p1^3 + 2*k3*p1*p3^2 + 2*k4*p1;
V(2) = 4*k2*p3^3 + 2*k3*p1^2*p3 + 2*k5*p3;
V = V/norm(V);
if (min(n11, n21) < V(1) && max(n11, n21)> V(1) && min(n12, n22) < V(2) && max(n12, n22) > V(2))
Vg=1;
end
%% Find group velocity with group angle
function Vg = GetVg(a11,a33,a13,a44,ST)
if abs(ST) == 0 || abs(ST) == 1;
% phase and group velocities coinside in horizontal and vertical
% directions, we can use formula for phase velocity
D = sqrt( (a33-a44)^2 + 2*(2*(a13+a44)^2 - (a33-a44)*(a11+a33-2*a44))*ST.^2 ...
+ ((a11+a33-2*a44)^2 - 4*(a13+a44)^2)*ST.^4);
Vg = sqrt(0.5*(a33 + a44 + (a11 - a33)*ST.^2 + D)); % in this case group == phase
else
% See script "Analize Relationship between phase and group velocity"
% See paper of Vladimir Grechka (2013), Ray-direction velocities in VTI
% media, Geophysics, V. 78, N. 1, pp. F1-F5
STini = ST;
psi = asin(STini);
PSI = tan(psi);
% Thomsen parameters
eps = (a11-a33)/(2*a33);
del = ((a13+a44)^2 - (a33-a44)^2)/(2*a33*(a33-a44));
% F matrix, formulas A1-A6 in paper
F11 = 1;
F12 = -a33 -a44;
F13 = a33*a44;
F21 = -a11 - a44;
F22 = 2*a33*((eps-del)*a33 + (1+del)*a44);
F31 = a11*a44;
% M matrix, formulas B1-B10 in paper
A = F12^2 - 4*F11*F13;
B = F21^2 - 4*F11*F31;
M = zeros(7,3);
M(1,3) = - A*F13;
M(2,2) = A*F22;
M(3,1) = F11*F22^2 + F13*F21^2 - F12*F21*F22;
M(3,3) = 4*F11*F13*F22 - 2*F12*F13*F21;
M(4,2) = 2*(F12^2*F31 + F13*(F21^2-4*F11*F31)-F11*F22^2);
M(5,1) = 4*F11*F22*F31 - 2*F12*F21*F31;
M(5,3) = F11*F22^2 + F12^2*F31 - F12*F21*F22;
M(6,2) = B*F22;
M(7,1) = -B*F31;
Mpsi = M*[1; PSI; PSI^2];
THETA = roots(Mpsi(end:-1:1)); % different order in roots function
theta = atan(THETA);
theta = theta(imag(theta)==0); % take only real roots
VpQP = zeros(size(theta));
VgQP = zeros(size(theta));
psiQP = zeros(size(theta));
for i=1:length(theta) % for each real root find
% phase velocity
dtheta = 0.001;
ST = sin(theta(i)-dtheta);
D = sqrt( (a33-a44)^2 + 2*(2*(a13+a44)^2 - (a33-a44)*(a11+a33-2*a44))*ST.^2 ...
+ ((a11+a33-2*a44)^2 - 4*(a13+a44)^2)*ST.^4);
VpQPm = sqrt(0.5*(a33 + a44 + (a11 - a33)*ST.^2 + D));
ST = sin(theta(i)+dtheta);
D = sqrt( (a33-a44)^2 + 2*(2*(a13+a44)^2 - (a33-a44)*(a11+a33-2*a44))*ST.^2 ...
+ ((a11+a33-2*a44)^2 - 4*(a13+a44)^2)*ST.^4);
VpQPp = sqrt(0.5*(a33 + a44 + (a11 - a33)*ST.^2 + D));
VpQP(i) = (VpQPp+VpQPm)/2;
dVpQP = (VpQPp-VpQPm)/(2*dtheta);
% group angle
psiQP(i) = (atan(dVpQP./VpQP(i))+theta(i));
% group velocity
VgQP(i) = sqrt(VpQP(i).^2 + dVpQP.^2);
end
Vg = VgQP(abs(sin(psiQP)-STini)<0.00001);
if length(Vg)>1
Vg = Vg(1);
end
end
|
github
|
xqmoo8/operating-cost-optimization-master
|
cost_optimization_for_test_benders.m
|
.m
|
operating-cost-optimization-master/cost_optimization_for_test_benders.m
| 83,862 |
utf_8
|
95fea231af6064af6071a7da4b4035ec
|
%% the main struture of benders decomposition algorithm
function [cost_for_comparison, final_consumed_time, dual_gap, reduced_distance, infeasible_flag_out] ...
= cost_optimization_for_test_benders( time_slot, voya_distance, accelerate_flag_input, near_opt_optimal_input, operation_mode_input, No_case_in, para_LNBD)
global OPTIONS total_sub total_P total_dual accelerate_flag upper_of_lowerbound with_iteration_D infeasible_flag
%% the adjusted parameters
dbstop if error
% The number of operation time slot
if ~exist('time_slot', 'var')
OPTIONS.N_t = 10;
else
OPTIONS.N_t = time_slot;
end
% The voyage distance
if ~exist('voya_distance', 'var')
OPTIONS.Distance = 160;
else
OPTIONS.Distance = voya_distance;
end
% Accelerated options
% 1 no accelerated constraints
% 2 power range and lower bound constraints
% 3 only power range
% 4 only lower bound
if ~exist('accelerate_flag_input', 'var')
accelerate_flag = 1;
else
accelerate_flag = accelerate_flag_input;
end
% Algorithm selection
% 0 optimal algorithm
% 1 LNBD
if ~exist('near_opt_optimal_input', 'var')
near_opt_optimal = 1;
else
near_opt_optimal = near_opt_optimal_input;
end
% Parameters of generator based on former works
% detail information is given in function initial_parameters().
if ~exist('parameter_test_input', 'var')
parameter_test = 3;
else
parameter_test = parameter_test_input;
end
% normal operation mode:
% 0 (Fault wo PPA ESMC)
% 1 (Fault wo PPA w ESMC)
% 2 (Fault w PPA w ESMC)
% 3 (Fault w PPA w ESMC w load shedding & reconfiguration)
% adjustment method 3 is not used in normal mode
% semi-island operation mode:
% 4 (Fault wo PPA ESMC)
% 5 (Fault wo PPA w ESMC)
% 6 (Fault w PPA w ESMC)
% 7 (Fault w PPA w ESMC w load shedding & reconfiguration)
% island operation mode:
% 8 (Fault wo PPA ESMC)
% 9 (Fault wo PPA w ESMC)
% 10 (Fault w PPA w ESMC)
% 11 (Fault w PPA w ESMC w load shedding & reconfiguration)
if ~exist('operation_mode_input', 'var')
operation_mode = 7;
else
operation_mode = operation_mode_input;
% if operation_mode == 3
% operation_mode = 2;
% end
end
% Test ID for saving results
if ~exist('No_case_in', 'var')
No_case = 1;
else
No_case = No_case_in;
end
% Adjustment parameter of load range in LNBD
% Adjustment parameter of propulsion power in LNBD
% with_iteration_D
if ~exist('para_LNBD', 'var')
OPTIONS.varphi_Pl = 0.7;
OPTIONS.varphi_Ppr = 0.3;
with_iteration_D = 0;
else
OPTIONS.varphi_Pl = para_LNBD(1);
OPTIONS.varphi_Ppr = para_LNBD(2);
with_iteration_D = para_LNBD(3);
end
case_numb = No_case;
if (operation_mode <= 7) && (operation_mode > 3)
case_numb = 1;
elseif (operation_mode <= 11) && (operation_mode > 7)
case_numb = 2;
end
% the number of generators and ESM modules in the Cases.
if case_numb == 1
OPTIONS.N_g = 2;
OPTIONS.N_e = 4;
elseif case_numb == 2
OPTIONS.N_g = 3;
OPTIONS.N_e = 3;
elseif case_numb == 3
OPTIONS.N_g = 2;
OPTIONS.N_e = 2;
elseif case_numb == 4
OPTIONS.N_g = 3;
OPTIONS.N_e = 2;
end
% if ~exist('varphi_Ppr', 'var')
% else
% end
infeasible_flag = 0;
infeasible_flag_out = 0;
%% inintial part
% initial the parameters
initial_parameters(parameter_test, operation_mode);
% initial the load demand
load_demand(operation_mode);
% intial the variables and preallocate an arry to the variables
Max_iteration = 800;
delta_g= ones(OPTIONS.N_g, OPTIONS.N_t);
OPTIONS.initial_redundant_sw = [ones(1, OPTIONS.N_t); zeros(1, OPTIONS.N_t); zeros(1, OPTIONS.N_t); ones(1, OPTIONS.N_t)];
redundant_sw = OPTIONS.initial_redundant_sw ;
objval_upperbound = zeros(1, Max_iteration);
objval_lowerbound = zeros(1, Max_iteration);
best_upperbound = zeros(1, Max_iteration);
best_upperbound(1) = inf;
best_lowerbound = zeros(1, Max_iteration);
best_solution_index = 1;
consumed_time = zeros(3, Max_iteration);
RD = zeros(1, Max_iteration);
min_reduced_distance = +inf;
Ppr_best_solution = zeros(1, OPTIONS.N_t);
% Ppr_max_lowerbound = ones(1, OPTIONS.N_t)* sum(OPTIONS.Pg_Max);
% initial the objective value and dual variable
if near_opt_optimal == 0
total_sub(1).sub_optval = 0;
elseif near_opt_optimal == 1
total_sub(1).sub_optval = zeros(OPTIONS.N_g, OPTIONS.N_t+1);
end
total_sub(1).delta_g = delta_g;
total_sub(1).redundant_sw = redundant_sw;
total_P(1).Pg = zeros(OPTIONS.N_g, OPTIONS.N_t);
total_P(1).Pb = zeros(OPTIONS.N_e, OPTIONS.N_t);
total_P(1).Ppr = zeros(1, OPTIONS.N_t);
% here load shedding is only supported for two island parts
total_P(1).load_shedding = zeros(2, OPTIONS.N_t);
total_P(1).Pc = zeros(OPTIONS.N_g, OPTIONS.N_t);
total_P(1).Pd = zeros(OPTIONS.N_g, OPTIONS.N_t);
total_dual(1).delta_g = zeros(OPTIONS.N_g, OPTIONS.N_t);
total_dual(1).switch = zeros(4, OPTIONS.N_t);
% generate lowerbound of benders cut
% delta_bound = [ones(1, OPTIONS.N_t); ones(1, OPTIONS.N_t); ];
% delta_bound = delta_g;
% [objval_upperbound_test, benders_cut_lowerbound] = optimization_subproblem( operation_mode, delta_bound, redundant_sw );
% benders_cut_lowerbound = 0 * benders_cut_lowerbound;
benders_cut_lowerbound = 0;
upper_of_lowerbound = 0;
% only semi-island mode need reconfiguration
if (operation_mode <= 3) || ( (operation_mode <=11) && (operation_mode > 7) )
OPTIONS.Tmin_sw = OPTIONS.N_t;
else % normal mode and island mode do not need reconfiguration
OPTIONS.Tmin_sw = OPTIONS.N_t;
end
%% start the iteration of the algorithm
for benders_index = 1:800
% master_problem optimization based on benders decomposition
% the last input parameter is used to limit the data dimenson for benders cuts
tic;
switch near_opt_optimal
case 0
[objval_lowerbound(benders_index), delta_g, redundant_sw, benders_cut ] ...
= optimization_masterproblem(operation_mode, benders_cut_lowerbound, benders_index-1, Ppr_best_solution);
case 1
[objval_lowerbound(benders_index), delta_g, redundant_sw, benders_cut ] ...
= optimization_masterproblem_t(operation_mode, benders_cut_lowerbound, benders_index-1, Ppr_best_solution);
end
% storage the computational time of master problem in this iteration
consumed_time(1, benders_index) = toc;
if infeasible_flag ~= 0
infeasible_flag_out = infeasible_flag;
break;
end
tic;
% sub_problem optimization based on benders decomposition
switch near_opt_optimal
case 0
[objval_upperbound(benders_index), sub_optval, sub_P, sub_dual, reduced_distance] ...
= optimization_subproblem(operation_mode, delta_g, redundant_sw);
case 1
[objval_upperbound(benders_index), sub_optval, sub_P, sub_dual, reduced_distance] ...
= optimization_subproblem_t(operation_mode, delta_g, redundant_sw);
% [objval_upperbound(benders_index), sub_optval, sub_P, sub_dual, reduced_distance] ...
% = optimization_subproblem(operation_mode, delta_g, redundant_sw);
end
% storage the computational time of subproblem in this iteration
consumed_time(2, benders_index) = toc;
if infeasible_flag ~= 0
infeasible_flag_out = infeasible_flag;
break;
end
% storage and passing of objective value and dual variable
total_sub(benders_index).sub_optval = sub_optval;
total_sub(benders_index).delta_g = delta_g;
total_sub(benders_index).redundant_sw = redundant_sw;
total_P(benders_index).Pg = sub_P.Pg;
total_P(benders_index).Pb = sub_P.Pb;
total_P(benders_index).Ppr = sub_P.Ppr;
total_P(benders_index).load_shedding = sub_P.load_shedding;
total_P(benders_index).Pc = sub_P.Pc;
total_P(benders_index).Pd = sub_P.Pd;
total_dual(benders_index).delta_g = sub_dual.delta_g;
total_dual(benders_index).switch = sub_dual.switch;
RD(benders_index) = reduced_distance;
if objval_lowerbound(benders_index) > upper_of_lowerbound
upper_of_lowerbound = objval_lowerbound(benders_index);
end
% if benders_cut > benders_cut_lowerbound
% benders_cut_lowerbound = benders_cut;
% end
% storage the computational time in this iteration
consumed_time(3, benders_index) = sum(consumed_time(1:2, benders_index), 1);
% print the iteration number and computation time
if near_opt_optimal == 0
fprintf('\nGBD: computation time of MP & SP at iteration %d is %5.2f + %6.2f = %6.2f s \n\n', ...
benders_index, consumed_time(1, benders_index), consumed_time(2, benders_index), consumed_time(3,benders_index) );
else
fprintf('\nLNBD: computation time of MP & SP at iteration %d is %5.2f + %6.2f = %6.2f s \n\n', ...
benders_index, consumed_time(1, benders_index), consumed_time(2, benders_index), consumed_time(3,benders_index) );
end
if benders_index >= 2
% update upperbound and lowerbound
if best_upperbound(benders_index-1) > objval_upperbound(benders_index)
best_upperbound(benders_index) = objval_upperbound(benders_index);
best_solution_index = benders_index;
else
best_upperbound(benders_index) = best_upperbound(benders_index-1);
end
if best_lowerbound(benders_index-1) < objval_lowerbound(benders_index)
best_lowerbound(benders_index) = objval_lowerbound(benders_index);
else
best_lowerbound(benders_index) = best_lowerbound(benders_index-1);
end
% if reduced_distance < min_reduced_distance
% min_reduced_distance = reduced_distance;
Ppr_best_solution = total_P(benders_index).Ppr;
% end
% performance comparison
error = ( best_upperbound(benders_index) - best_lowerbound(benders_index) );
dual_gap = 100*error/best_lowerbound(benders_index);
disp('upperbound, lowerbound, error, dual_gap');
disp([best_upperbound(benders_index) best_lowerbound(benders_index) error dual_gap]);
% convergence determination: error is less than 1e-3 and the total
% consumed time is larger than 7200
if (error <= 1e-3) || (sum(consumed_time(3, 1:benders_index))> 3600)
break;
end
end
% if abs(objval_upperbound(benders_index) - 7.3724e+04) < 10
% disp('debug');
% end
end
best_solution.delta_g = total_sub(best_solution_index).delta_g;
best_solution.redundant_sw = total_sub(best_solution_index).redundant_sw;
best_solution.Pg = total_P(best_solution_index).Pg;
best_solution.Pb = total_P(best_solution_index).Pb;
best_solution.Ppr = total_P(best_solution_index).Ppr;
best_solution.load_shedding = total_P(best_solution_index).load_shedding;
best_solution.Pc = total_P(best_solution_index).Pc;
best_solution.Pd = total_P(best_solution_index).Pd;
best_solution.RD = RD(best_solution_index);
optimal_cost = [best_lowerbound(1:benders_index); best_upperbound(1:benders_index); ];
final_consumed_time(1, 1) = sum(consumed_time(3, 1:benders_index));
final_consumed_time(1, 2) = benders_index;
cost_for_comparison = save_optimal_cost_information(No_case, near_opt_optimal, optimal_cost, best_solution, operation_mode, consumed_time(:, 1:benders_index));
% cost_for_comparison = save_optimal_cost_information(No_case, near_opt_optimal, optimal_cost, sub_P, delta_g, redundant_sw, reduced_distance, operation_mode, consumed_time(:, 1:benders_index));
plot_result(optimal_cost);
end
%% Save optimal operation status
function [cost_for_comparison] = save_optimal_cost_information(No_case, near_opt_optimal, optimal_cost, best_solution, operation_mode, consumed_time)
global OPTIONS accelerate_flag infeasible_flag
operating_cost = OPTIONS.G(1:OPTIONS.N_g, 1).' * power(best_solution.Pg(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
+ OPTIONS.G(1:OPTIONS.N_g, 2).' * best_solution.Pg(1:OPTIONS.N_g, 1:OPTIONS.N_t) ...
+ OPTIONS.G(1:OPTIONS.N_g, 3).' * best_solution.delta_g ...
+ OPTIONS.Xi_E * OPTIONS.E(1:OPTIONS.N_e, 1).' * power(best_solution.Pb(1:OPTIONS.N_e, 1:OPTIONS.N_t), 2) ...
+ OPTIONS.Xi_E * OPTIONS.E(1:OPTIONS.N_e, 2).' * ones(OPTIONS.N_e, OPTIONS.N_t);
Penalty_cost_LS = OPTIONS.Penalty_L * sum(best_solution.load_shedding(1:2, 1:OPTIONS.N_t),1);
Penalty_cost_D = 1.02 * OPTIONS.Penalty_D * best_solution.RD;
startup_g = best_solution.delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) - [zeros(OPTIONS.N_g,1) best_solution.delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t-1)];
startup_cost = OPTIONS.C_ss(1:OPTIONS.N_g,1).'* (round(startup_g) > 0);
operating_cost = operating_cost + startup_cost;
% total cost obtained from the master problem
data.cost(1, 1) = optimal_cost(2, end);
% penalty cost of relaxed power Pc and Pd
data.cost(1, 2) = + sum(10 * OPTIONS.Penalty_D * best_solution.Pc(1, 1:OPTIONS.N_t).' ,1) ...
+ sum(10 * OPTIONS.Penalty_D * best_solution.Pc(2, 1:OPTIONS.N_t).' ,1) ...
+ sum(10 * OPTIONS.Penalty_D * best_solution.Pd(1, 1:OPTIONS.N_t).' ,1) ...
+ sum(10 * OPTIONS.Penalty_D * best_solution.Pd(2, 1:OPTIONS.N_t).' ,1) ;
% operating cost calculated based on the results such as Pg, Ppr and Pe
data.cost(2, 1:OPTIONS.N_t) = operating_cost;
% total operating cost of generators and ESMs
data.cost(3, 1) = sum(operating_cost, 2);
data.cost(4, 1) = sum(operating_cost, 2);
% penalty cost of load shedding
data.cost(3, 2) = sum(Penalty_cost_LS, 2);
data.cost(4, 2) = sum(Penalty_cost_LS, 2)/OPTIONS.Penalty_L;
% penalty cost of reduced distance
data.cost(3, 3) = Penalty_cost_D;
data.cost(4, 3) = best_solution.RD;
% total cost of operating cost, two terms of penalty cost
data.cost(3, 4) = sum(operating_cost) + sum(Penalty_cost_LS) + Penalty_cost_D;
data.cost(4, 4) = sum(operating_cost) + sum(Penalty_cost_LS) + Penalty_cost_D;
% data for parameter passing
cost_for_comparison = data.cost(4, 1:4);
total_switching = sum(abs(best_solution.redundant_sw(1,1) - OPTIONS.initial_redundant_sw(1,1)) ) ...
+ sum(abs(best_solution.redundant_sw(2,1) - OPTIONS.initial_redundant_sw(2,1))) ...
+ sum(abs(best_solution.redundant_sw(1,2:OPTIONS.N_t) - best_solution.redundant_sw(1,1:OPTIONS.N_t-1)) ) ...
+ sum(abs(best_solution.redundant_sw(2,2:OPTIONS.N_t) - best_solution.redundant_sw(2,1:OPTIONS.N_t-1)));
% the final power schedule of SPS
data.Pgc(1:OPTIONS.N_g, 1:OPTIONS.N_t) = best_solution.Pg;
data.Pgc(OPTIONS.N_g+1:2*OPTIONS.N_g, 1:OPTIONS.N_t) = best_solution.Pc;
data.Pb(1:OPTIONS.N_e, 1:OPTIONS.N_t) = best_solution.Pb;
data.Ppr(1, 1:OPTIONS.N_t) = best_solution.Ppr;
data.load_shedding(1:2, 1:OPTIONS.N_t) = best_solution.load_shedding;
if operation_mode <= 3
data.Pl(1, 1:OPTIONS.N_t) = OPTIONS.P_L_TIME_off;
data.Pl(3, 1:OPTIONS.N_t) = sum(best_solution.Pg) + sum(best_solution.Pb, 1) - best_solution.Ppr;
elseif operation_mode <= 11
data.Pl(1, 1:OPTIONS.N_t) = OPTIONS.island1_load;
data.Pl(2, 1:OPTIONS.N_t) = OPTIONS.island2_load;
data.Pl(3, 1:OPTIONS.N_t) = sum(best_solution.Pg) + sum(best_solution.Pb, 1) - best_solution.Ppr;
end
% data.power(10,:) = OPTIONS.P_L_TIME_off(1,1:OPTIONS.N_t);
data.status(1:OPTIONS.N_g, 1:OPTIONS.N_t) = best_solution.delta_g;
data.status(OPTIONS.N_g+1:OPTIONS.N_g+2, 1:OPTIONS.N_t) = [best_solution.redundant_sw(1,1:OPTIONS.N_t); best_solution.redundant_sw(2,1:OPTIONS.N_t)];
data.status(OPTIONS.N_g+3, 1) = total_switching;
% 'Sub Infeasible': infeasible_flag = 1;
% 'Master Infeasible': infeasible_flag = 2;
% 'Master Failed': infeasible_flag = 3;
% 'Sub-t Infeasible': infeasible_flag = 4;
% 'Master-t Infeasible': infeasible_flag = 5;
% 'Master-t Failed': infeasible_flag = 6;
if infeasible_flag ~= 0
data.status(OPTIONS.N_g+4, 1) = infeasible_flag;
else
data.status(OPTIONS.N_g+4, 1) = 0;
end
data.distance(1, 1:2) = [OPTIONS.Distance best_solution.RD];
data.consumed_time = consumed_time;
% 1. average computational time of master problem
% 2. average computational time of subproblem
% 3. average computational time of each iteration
% 4. the total number of iteration
data.consumed_time(4, 1) = sum(consumed_time(1, :))/length(consumed_time(3, :));
data.consumed_time(4, 2) = sum(consumed_time(2, :))/length(consumed_time(3, :));
data.consumed_time(4, 3) = sum(consumed_time(3, :))/length(consumed_time(3, :));
data.consumed_time(4, 4) = length(consumed_time(3, :));
Mg = OPTIONS.M(1:OPTIONS.N_g,1).' * power(best_solution.Pg(1:OPTIONS.N_g,1:OPTIONS.N_t).',2).' ...
+ OPTIONS.M(1:OPTIONS.N_g,2).' * power(best_solution.Pg(1:OPTIONS.N_g,1:OPTIONS.N_t).',1).' ...
+ OPTIONS.M(1:OPTIONS.N_g,3).' * best_solution.delta_g(1:OPTIONS.N_g,1:OPTIONS.N_t);
EEOI_t = Mg./(OPTIONS.M_sl*(best_solution.Ppr(1:OPTIONS.N_t)./2.2e-3).^(1/3));
for index_t = find(best_solution.Ppr == 0)
EEOI_t(index_t) = 0;
end
data.EEOI(1, 1:OPTIONS.N_t) = EEOI_t;
if near_opt_optimal ==0
filename = ['optimal_mode_',num2str(operation_mode),'_D_',num2str(OPTIONS.Distance),...
'_T_',num2str(OPTIONS.N_t),'_Ac_',num2str(accelerate_flag),'_No_',num2str(No_case),'.mat'];
elseif near_opt_optimal ==1
filename = ['LNBD_mode_',num2str(operation_mode),'_D_',num2str(OPTIONS.Distance),'_varphi_',num2str(OPTIONS.varphi_Pl),...
'_T_',num2str(OPTIONS.N_t),'_Ac_',num2str(accelerate_flag),'_No_',num2str(No_case),'.mat'];
end
save(filename,'data');
end
%% Plot the simulation result
function plot_result(result)
hold on
plot(result(1,1:end));
plot(result(2,1:end));
hold off
end
%% Load data generation
function load_demand(operation_mode)
global OPTIONS
OPTIONS.P_L = [4 2]; % P_Generater
OPTIONS.P_L_Scale_t = [0.5 0.6 0.8 0.9 0.82 0.6 0.47 0.42 0.4 0.47 0.49 0.52 0.49 0.47 0.6 0.8 0.82 0.9 0.9 0.7 0.62 0.5 0.33 0.4 0.5 0.4];
OPTIONS.P_vs_t_Scale = [0.5 0.6 0.8 0.9 0.82 0.6 0.47 0.42 0.4 0.47 0.49 0.52 0.49 0.47 0.6 0.8 0.82 0.9 0.9 0.7 0.62 0.5 0.33 0.4 0.5 0.4];
OPTIONS.P_no_t_Scale = [0.5 0.6 0.8 0.9 0.82 0.6 0.47 0.42 0.4 0.47 0.49 0.52 0.49 0.47 0.6 0.8 0.82 0.9 0.9 0.7 0.62 0.5 0.33 0.4 0.5 0.4];
% total load upper bound 3.6 MW
P_no_base = 1.2; % the scale of non-vital loads are 1.2/3.6 = 0.33
P_vs_base = ones(1,OPTIONS.zone).' * (sum(OPTIONS.P_L) - 1.2)/OPTIONS.zone;
if operation_mode <= 3
P_vs = P_vs_base * OPTIONS.P_vs_t_Scale;
P_no = P_no_base * OPTIONS.P_no_t_Scale;
P_total_vs = sum(P_vs);
P_total_time = P_total_vs + P_no;
P_total_average = sum(P_total_time(1:OPTIONS.N_t))/OPTIONS.N_t;
OPTIONS.P_total_vs = P_total_vs(1:OPTIONS.N_t);
OPTIONS.P_no = P_no(1:OPTIONS.N_t);
OPTIONS.P_L_TIME_off = P_total_time(1:OPTIONS.N_t);
OPTIONS.P_L_TIME_off_avg = P_total_average;
OPTIONS.Delta_PL = OPTIONS.P_L_TIME_off - OPTIONS.P_L_TIME_off_avg ;
elseif operation_mode <= 7
% the default fault is at 5-6 bus and 7-8 bus. Thus,the scale factors of
% vital and semi-vital loads in different island parts are 3/6 and 1/6;
% The scale factors of non-vital loads are (5+9-6)/12 and 1-(5+9-6)/12
% (0.75 and 0.25)
P_vs_island1 = sum(P_vs_base(1:3)) * OPTIONS.P_vs_t_Scale;
P_vs_island2 = sum(P_vs_base(6)) * OPTIONS.P_vs_t_Scale;
P_no_island1 = 0.75 * P_no_base * OPTIONS.P_no_t_Scale;
P_no_island2 = 0.25 * P_no_base * OPTIONS.P_no_t_Scale;
P_coupled_load = (P_vs_base(4:5)) * OPTIONS.P_vs_t_Scale;
OPTIONS.Coupled_load = P_coupled_load(1:2,1:OPTIONS.N_t);
OPTIONS.island1_load = P_vs_island1(1:OPTIONS.N_t) + P_no_island1(1:OPTIONS.N_t);
OPTIONS.island1_load_average = sum(OPTIONS.island1_load)/OPTIONS.N_t;
OPTIONS.island1_non_load = P_no_island1(1:OPTIONS.N_t);
% not the real max and min, which can be considered as the minimum value of upperbound
% , and the maximum value of lowbound.
OPTIONS.island1_max = P_vs_island1(1:OPTIONS.N_t) ;
OPTIONS.island1_min = OPTIONS.island1_load(1:OPTIONS.N_t) + sum(P_coupled_load(1:2, 1:OPTIONS.N_t), 1);
OPTIONS.Delta_PL_island1 = OPTIONS.island1_load - OPTIONS.island1_load_average;
OPTIONS.island2_load = P_vs_island2(1:OPTIONS.N_t) + P_no_island2(1:OPTIONS.N_t);
OPTIONS.island2_load_average = sum(OPTIONS.island2_load)/OPTIONS.N_t;
OPTIONS.island2_non_load = P_no_island2(1:OPTIONS.N_t);
% not the real max, it's the maximum of the supply power of vital and semi loads
OPTIONS.island2_max = P_vs_island2(1:OPTIONS.N_t) ;
OPTIONS.island2_min = OPTIONS.island2_load(1:OPTIONS.N_t) + sum(P_coupled_load(1:2, 1:OPTIONS.N_t), 1);
OPTIONS.Delta_PL_island2 = OPTIONS.island2_load - OPTIONS.island2_load_average;
% P_vs = P_vs_base * OPTIONS.P_vs_t_Scale;
% P_no = P_no_base * OPTIONS.P_no_t_Scale;
% P_total_vs = sum(P_vs);
%
% P_total_time = P_total_vs + P_no;
% OPTIONS.P_L_TIME_off = P_total_time(1:OPTIONS.N_t);
elseif operation_mode <= 11
% the default fault is at 5-6 bus and 11-12 bus. Thus,the scale factors of
% vital and semi-vital loads in different island parts are 5/6 and 1/6;
% The scale factors of non-vital loads are (5+5)/12 and 1-(5+5)/12
% (5/6 and 1/6)
P_vs_island1 = sum(P_vs_base(1:5)) * OPTIONS.P_vs_t_Scale;
P_vs_island2 = sum(P_vs_base(6)) * OPTIONS.P_vs_t_Scale;
P_no_island1 = 5/6 * P_no_base * OPTIONS.P_no_t_Scale;
P_no_island2 = 1/6 * P_no_base * OPTIONS.P_no_t_Scale;
OPTIONS.island1_load = P_vs_island1(1:OPTIONS.N_t) + P_no_island1(1:OPTIONS.N_t);
OPTIONS.island1_load_average = sum(OPTIONS.island1_load)/OPTIONS.N_t;
OPTIONS.island1_non_load = P_no_island1(1:OPTIONS.N_t);
% not the real max and min, which can be considered as the minimum value of upperbound
% , and the maximum value of lowbound.
OPTIONS.island1_max = OPTIONS.island1_load;
OPTIONS.island1_min = P_vs_island1(1:OPTIONS.N_t);
OPTIONS.Delta_PL_island1 = OPTIONS.island1_load - OPTIONS.island1_load_average;
OPTIONS.island2_load = P_vs_island2(1:OPTIONS.N_t) + P_no_island2(1:OPTIONS.N_t);
OPTIONS.island2_load_average = sum(OPTIONS.island2_load)/OPTIONS.N_t;
OPTIONS.island2_non_load = P_no_island2(1:OPTIONS.N_t);
% not the real max, it's the maximum of the supply power of vital and semi loads
OPTIONS.island2_max = OPTIONS.island2_load;
OPTIONS.island2_min = P_vs_island2(1:OPTIONS.N_t);
OPTIONS.Delta_PL_island2 = OPTIONS.island2_load - OPTIONS.island2_load_average;
% P_vs = P_vs_base * OPTIONS.P_vs_t_Scale;
% P_no = P_no_base * OPTIONS.P_no_t_Scale;
% P_total_vs = sum(P_vs);
%
% P_total_time = P_total_vs + P_no;
% OPTIONS.P_L_TIME_off = P_total_time(1:OPTIONS.N_t);
end
end
%% Inital the parameters for optimization
function [] = initial_parameters(parameter_test, operation_mode)
global OPTIONS
OPTIONS.velocity = [25 0];
% % number of ESM modules
% OPTIONS.N_e = 4;
% % number of generators
% OPTIONS.N_g = 2;
% number of time slots
% OPTIONS.N_t = 12;
% minmum time between startup and shuntdown
OPTIONS.Tmin_g_st = 1;
% the minimum shutdown time must be greater than 1 (not 0)
OPTIONS.Tmin_g_sd = 1;
% minmum time between switch change
OPTIONS.Tmin_sw = 1;
% time of faults happen
OPTIONS.Fault_time = 4;
% the number of zones in shipboard power system
OPTIONS.zone = 6;
OPTIONS.velocity_avg = OPTIONS.Distance/OPTIONS.N_t;
OPTIONS.P_pr_avg = (OPTIONS.velocity_avg).^3*2.2e-3;
OPTIONS.Pg_Max(1,1) = 8;
OPTIONS.Pg_Min(1,1) = 1;
OPTIONS.Pg_Max(1,2) = 4;
OPTIONS.Pg_Min(1,2) = 0.5;
OPTIONS.Pg_Max(1,3) = 4;
OPTIONS.Pg_Min(1,3) = 0.5;
OPTIONS.Xi_E = 1;
OPTIONS.Ppr_Max = (OPTIONS.velocity(1)).^3*2.2e-3;
% in the normal mode, there are two scenarios (4 ESMs in case 1, 3 ESMs in case 2)
% if operation_mode <= 3
if OPTIONS.N_e == 4
OPTIONS.Pb_Max(1) = 0.5;
OPTIONS.Pb_Min(1) = -0.5;
OPTIONS.E_Max = [1 1 1 1];
OPTIONS.E_Min = [0.2 0.2 0.2 0.2];
OPTIONS.E(1:OPTIONS.N_e,1) = 1 * ones(OPTIONS.N_e,1);
OPTIONS.E(1:OPTIONS.N_e,2) = 0.5 * ones(OPTIONS.N_e,1);
% OPTIONS.E(1:2,1:2) = [1 0.5; 1 0.5];
elseif OPTIONS.N_e == 3
OPTIONS.Pb_Max(1) = 0.5;
OPTIONS.Pb_Min(1) = -0.5;
OPTIONS.E_Max = [1 1 1];
OPTIONS.E_Min = [0.2 0.2 0.2];
OPTIONS.E(1:OPTIONS.N_e,1) = 1 * ones(OPTIONS.N_e,1);
OPTIONS.E(1:OPTIONS.N_e,2) = 0.5 * ones(OPTIONS.N_e,1);
% OPTIONS.E(1:2,1:2) = [1 0.5; 1 0.5];
end
% % in the operation mode 4~7,
% elseif operation_mode <= 7
% OPTIONS.Pb_Max(1) = 1;
% OPTIONS.Pb_Min(1) = -1;
% OPTIONS.E_Max = [3 1];
% OPTIONS.E_Min = [0.2 0.2];
% elseif operation_mode <= 11
% OPTIONS.Pb_Max(1) = 1;
% OPTIONS.Pb_Min(1) = -1;
% OPTIONS.E_Max = [3 1];
% OPTIONS.E_Min = [0.2 0.2];
% end
% a_lc and c_lc
% generator function parameters
switch parameter_test
case 1 %
OPTIONS.G(1,1:3) = [10 19 170];
OPTIONS.G(3,1:3) = [28.5 28 190];
OPTIONS.G(2,1:3) = [10 19 170];
case 2 % similar minimum SFC (160), large SFC deviation (250 and 150) between lower bound Pmin and efficient point Peff
OPTIONS.G(1,1:3) = [12 60 350];
OPTIONS.G(3,1:3) = [30 12 170];
OPTIONS.G(2,1:3) = [12 60 350];
% Kanellos: OPMS in IEEE Transactions on Sustainable Energy, Electric power systems research, and Inventions
case 3
OPTIONS.G(1,1:3) = [5.4 61.5 390];
OPTIONS.G(2,1:3) = [13.1 12 430];
OPTIONS.G(3,1:3) = [13.5 10 450];
OPTIONS.G(4,1:3) = [5.4 63 400];
% Ce Shang: Economic and environmental generation and voyage scheduling of all electric ships in IEEE Transactions on Power Systems
case 4
OPTIONS.G(1,1:3) = [29.16 2185.65 300];
OPTIONS.G(2,1:3) = [18.83 2330.10 291];
OPTIONS.G(3,1:3) = [9.37 622.50 210.00];
OPTIONS.G(4,1:3) = [9.89 618.75 204.00];
OPTIONS.G(5,1:3) = [26.86 886.50 135.0];
OPTIONS.G(6,1:3) = [13.67 532.80 111.0];
end
% GHG function parameters
switch parameter_test
case 1 %
OPTIONS.M(1,1:3) = [10 19 170];
OPTIONS.M(2,1:3) = [28.5 28 190];
OPTIONS.M(3,1:3) = [10 19 170];
OPTIONS.M_sl = 30;
case 2 % similar minimum SFC (160), large SFC deviation (250 and 150) between lower bound Pmin and efficient point Peff
OPTIONS.M(1,1:3) = [12 60 350];
OPTIONS.M(2,1:3) = [30 12 170];
OPTIONS.M(3,1:3) = [12 60 350];
OPTIONS.M_sl = 30;
% Kanellos: OPMS in IEEE Transactions on Sustainable Energy, Electric power systems research, and Inventions
case 3
OPTIONS.M(1,1:3) = 3.2*[5.4 61.5 390];
OPTIONS.M(2,1:3) = 2.5*[13.1 12 430];
OPTIONS.M(3,1:3) = 2.5*[13.5 10 450];
OPTIONS.M(4,1:3) = 3.2*[5.4 63 400];
OPTIONS.M_sl = 30;
% Ce Shang: Economic and environmental generation and voyage scheduling of all electric ships in IEEE Transactions on Power Systems
case 4
OPTIONS.M(1,1:3) = [8383.50 -2070.36 386.10];
OPTIONS.M(2,1:3) = [956.25 -613.12 362.43];
OPTIONS.M(3,1:3) = [8383.50 -2070.36 386.10];
OPTIONS.M(4,1:3) = [956.25 613.12 362.43];
OPTIONS.M(5,1:3) = [850.50 442.39 124.74];
OPTIONS.M(6,1:3) = [241.90 235.94 124.74];
OPTIONS.M_sl = 80;
end
% OPTIONS.C_ss = [90; 45];
OPTIONS.C_ss = 0 * ones(OPTIONS.N_g, 1);
OPTIONS.R_G = OPTIONS.Pg_Max*0.75;
% OPTIONS.R_G = [2 2];
OPTIONS.error = 1e-3;
OPTIONS.Penalty = max([2*OPTIONS.G(1,1)*OPTIONS.Pg_Max(1) + OPTIONS.G(1,2), 2*OPTIONS.G(2,1)*OPTIONS.Pg_Max(2) + OPTIONS.G(2,2)]);
A_max = max(OPTIONS.G(1:2,1));
B_max = max(OPTIONS.G(1:2,2));
Css_max = max(OPTIONS.G(1:2,3));
P_G_max = max(OPTIONS.Pg_Max);
% P_E_max = max(OPTIONS.Pb_Max);
MIN_PRECISE = 0.01;
OPTIONS.Penalty_L = max(2*A_max*P_G_max + B_max, max(2*OPTIONS.Xi_E*OPTIONS.E(1,1)*OPTIONS.Pb_Max));
OPTIONS.Penalty_D = 3*(2.2e-3)^(1/3)*OPTIONS.Penalty_L/(OPTIONS.Ppr_Max)^(1/3-1);
OPTIONS.Penalty_xi = max(2*A_max*P_G_max + B_max + (Css_max*(OPTIONS.N_t-1))/MIN_PRECISE, max(2*OPTIONS.Xi_E*OPTIONS.E(1,1)*OPTIONS.Pb_Max + OPTIONS.E(1,2)/MIN_PRECISE));
% OPTIONS.varphi = 2/3;
end
%% Optimal algorithm: solve the subproblem which is used to calculate the optimal power of generators and ESMs
function [objval_upperbound, sub_optval, sub_P, sub_dual, reduced_distance] = optimization_subproblem( operation_mode, delta_g, redundant_sw )
global OPTIONS infeasible_flag
% cvx_begin
% cvx_solver SeDuMi
cvx_begin quiet
variable Ppr(1, OPTIONS.N_t) nonnegative
variable Pb(OPTIONS.N_e, OPTIONS.N_t)
variable E(OPTIONS.N_e, OPTIONS.N_t) nonnegative
variable Pg(OPTIONS.N_g, OPTIONS.N_t) nonnegative
variable redundant_sw_s(2, OPTIONS.N_t)
variable sub_delta_g(OPTIONS.N_g, OPTIONS.N_t)
variable load_shedding(2, OPTIONS.N_t) nonnegative % it denotes the load shedding amount
variable reduced_distance nonnegative
variable Pc(OPTIONS.N_g, OPTIONS.N_t) nonnegative
variable Pd(OPTIONS.N_g, OPTIONS.N_t) nonnegative
dual variable dual_delta_g1
dual variable dual_delta_g2
if OPTIONS.N_g == 3
dual variable dual_delta_g3
end
dual variable dual_Sp
dual variable dual_Ss
minimize( sum( OPTIONS.G(1:OPTIONS.N_g, 1).' * power(Pg(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2), 2) ...
+ sum( OPTIONS.G(1:OPTIONS.N_g, 2).' * power(Pg(1:OPTIONS.N_g, 1:OPTIONS.N_t), 1), 2) ...
+ OPTIONS.Xi_E * sum(OPTIONS.E(1:OPTIONS.N_e, 1).'* power(Pb(1:OPTIONS.N_e, 1:OPTIONS.N_t),2) ,2) ...
+ OPTIONS.Xi_E * sum(OPTIONS.E(1:OPTIONS.N_e, 2).'* ones(OPTIONS.N_e, OPTIONS.N_t) ,2) ...
+ sum(OPTIONS.Penalty_L * sum(load_shedding(1:2, 1:OPTIONS.N_t),2) ,1) ...
+ 1.02*OPTIONS.Penalty_D * reduced_distance ...
+ sum(sum(100 * OPTIONS.Penalty_D * Pc(1:OPTIONS.N_g, 1:OPTIONS.N_t).', 1), 2) ...
+ sum(sum(100 * OPTIONS.Penalty_D * Pd(1:OPTIONS.N_g, 1:OPTIONS.N_t).' ,1), 2) )
subject to
% the range constraints of all the variables
Pg(1, 1:OPTIONS.N_t) <= sub_delta_g(1, 1:OPTIONS.N_t) * OPTIONS.Pg_Max(1) + Pc(1, 1:OPTIONS.N_t)
Pg(1, 1:OPTIONS.N_t) >= sub_delta_g(1, 1:OPTIONS.N_t) * OPTIONS.Pg_Min(1) - Pd(1, 1:OPTIONS.N_t)
Pg(2, 1:OPTIONS.N_t) <= sub_delta_g(2, 1:OPTIONS.N_t) * OPTIONS.Pg_Max(2) + Pc(2, 1:OPTIONS.N_t)
Pg(2, 1:OPTIONS.N_t) >= sub_delta_g(2, 1:OPTIONS.N_t) * OPTIONS.Pg_Min(2) - Pd(2, 1:OPTIONS.N_t)
if OPTIONS.N_g == 3
Pg(3, 1:OPTIONS.N_t) <= sub_delta_g(3, 1:OPTIONS.N_t) * OPTIONS.Pg_Max(3) + Pc(3, 1:OPTIONS.N_t)
Pg(3, 1:OPTIONS.N_t) >= sub_delta_g(3, 1:OPTIONS.N_t) * OPTIONS.Pg_Min(3) - Pd(3, 1:OPTIONS.N_t)
end
dual_delta_g1 : sub_delta_g(1, 1:OPTIONS.N_t) == delta_g(1, 1:OPTIONS.N_t)
dual_delta_g2 : sub_delta_g(2, 1:OPTIONS.N_t) == delta_g(2, 1:OPTIONS.N_t)
if OPTIONS.N_g == 3
dual_delta_g3 : sub_delta_g(3, 1:OPTIONS.N_t) == delta_g(3, 1:OPTIONS.N_t)
end
% ramping rate power of generators
Pg(1, 1) <= OPTIONS.R_G(1) + Pc(1, 1)
Pg(2, 1) <= OPTIONS.R_G(2) + Pc(2, 1)
if OPTIONS.N_g == 3
Pg(3, 1) <= OPTIONS.R_G(3) + Pc(3, 1)
end
for index_t = 2:OPTIONS.N_t
Pg(1, index_t) - Pg(1, index_t-1) <= OPTIONS.R_G(1)
Pg(1, index_t) - Pg(1, index_t-1) >= -OPTIONS.R_G(1)
Pg(2, index_t) - Pg(2, index_t-1) <= OPTIONS.R_G(2)
Pg(2, index_t) - Pg(2, index_t-1) >= -OPTIONS.R_G(2)
if OPTIONS.N_g == 3
Pg(3, index_t) - Pg(3, index_t-1) <= OPTIONS.R_G(3)
Pg(3, index_t) - Pg(3, index_t-1) >= -OPTIONS.R_G(3)
end
end
Pg(1, OPTIONS.N_t) <= OPTIONS.R_G(1) + Pc(1, OPTIONS.N_t)
Pg(2, OPTIONS.N_t) <= OPTIONS.R_G(2) + Pc(2, OPTIONS.N_t)
if OPTIONS.N_g == 3
Pg(3, OPTIONS.N_t) <= OPTIONS.R_G(3) + Pc(3, OPTIONS.N_t)
end
% propulsion power limitation
Ppr(1, 1:OPTIONS.N_t) <= OPTIONS.Ppr_Max * ones(1, OPTIONS.N_t)
% ESM limitation
for index_e = 1:OPTIONS.N_e
Pb(index_e, 1:OPTIONS.N_t) <= OPTIONS.Pb_Max * ones(1, OPTIONS.N_t)
Pb(index_e, 1:OPTIONS.N_t) >= OPTIONS.Pb_Min * ones(1, OPTIONS.N_t)
end
% Pb(2, 1:OPTIONS.N_t) <= OPTIONS.Pb_Max * ones(1, OPTIONS.N_t)
% Pb(2, 1:OPTIONS.N_t) >= OPTIONS.Pb_Min * ones(1, OPTIONS.N_t)
% charging and discharging
for index_e = 1:OPTIONS.N_e
E(index_e, 1:OPTIONS.N_t) <= OPTIONS.E_Max(1) * ones(1, OPTIONS.N_t)
E(index_e, 1:OPTIONS.N_t) >= OPTIONS.E_Min(1) * ones(1, OPTIONS.N_t)
end
% E(2, 1:OPTIONS.N_t) <= OPTIONS.E_Max(2) * ones(1, OPTIONS.N_t)
% E(2, 1:OPTIONS.N_t) >= OPTIONS.E_Min(2) * ones(1, OPTIONS.N_t)
% ESM output power and the capacity constraints
% When Pb is positive, ESM is in discharge status,
% Thus, Pg + Pg is used in power balance comstraint.
for index_e = 1:OPTIONS.N_e
E(index_e, 1) == OPTIONS.E_Max(index_e) - Pb(index_e,1)
% E(2, 1) == OPTIONS.E_Max(2) - Pb(2,1)
for t_index = 2:OPTIONS.N_t
E(index_e, t_index) == E(index_e, t_index-1) - Pb(index_e, t_index)
% E(2, t_index) == E(2, t_index-1) - Pb(2, t_index)
end
end
% voyage planning and ESS usage
switch mod(operation_mode, 4)
case 0 % only generator scheduling
Ppr(1, 1:OPTIONS.N_t) == OPTIONS.P_pr_avg;
Pb(1:OPTIONS.N_e, 1:OPTIONS.N_t) == 0;
case 1 % generator scheduling & ESMC
Ppr(1, 1:OPTIONS.N_t) == OPTIONS.P_pr_avg;
case 2 % generator scheduling & ESMC & PPA
sum((Ppr(1:OPTIONS.N_t)./2.2e-3).^(1/3)) >= OPTIONS.Distance - reduced_distance;
case 3 % generator scheduling & ESMC & PPA, load shedding is modelled in the code of next part
sum((Ppr(1:OPTIONS.N_t)./2.2e-3).^(1/3)) >= OPTIONS.Distance - reduced_distance;
end
% system power balance & load shedding range in three modes
if operation_mode <= 3
% normal operation without load shedding
for t_index = 1:OPTIONS.N_t
OPTIONS.P_L_TIME_off(1, t_index) - sum(load_shedding(1:2, t_index)) + Ppr(1, t_index) == ...
sum(Pg(1:OPTIONS.N_g, t_index), 1) + sum(Pb(1:OPTIONS.N_e, t_index), 1)
end
% load shedding range
if operation_mode == 3
load_shedding(1, 1:OPTIONS.N_t) + load_shedding(2, 1:OPTIONS.N_t) <= OPTIONS.P_no
else
load_shedding(1, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
load_shedding(2, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
end
elseif operation_mode <= 7
% semi-island mode operation with load shedding and
% reconfiguration (only in mode 7)
for t_index = 1:OPTIONS.N_t
redundant_sw_s(1:2, t_index).' * OPTIONS.Coupled_load(:, t_index) + OPTIONS.island1_load(1, t_index) ...
- load_shedding(1, t_index) + Ppr(1, t_index) == Pg(1, t_index) + sum(Pb(1:OPTIONS.N_e-1, t_index), 1)
(ones(2,1) - redundant_sw_s(1:2, t_index)).' * OPTIONS.Coupled_load(:, t_index) ...
+ OPTIONS.island2_load(1, t_index) - load_shedding(2, t_index) == Pg(2, t_index) + Pb(OPTIONS.N_e, t_index)
end
if operation_mode == 7
% load shedding amount is limited by the demand of non-vital loads
load_shedding(1, 1:OPTIONS.N_t) <= OPTIONS.island1_non_load(1, 1:OPTIONS.N_t)
load_shedding(2, 1:OPTIONS.N_t) <= OPTIONS.island2_non_load(1, 1:OPTIONS.N_t)
else
load_shedding(1, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
load_shedding(2, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
end
elseif operation_mode <= 11
% island fault mode operation with load shedding only in mode
% 11
for t_index = 1:OPTIONS.N_t
OPTIONS.island1_load(1, t_index) - load_shedding(1, t_index) + Ppr(1, t_index) == sum(Pg(1:OPTIONS.N_g-1, t_index), 1) + sum(Pb(1:OPTIONS.N_e-1, t_index), 1)
OPTIONS.island2_load(1, t_index) - load_shedding(2, t_index) == Pg(OPTIONS.N_g, t_index) + Pb(OPTIONS.N_e, t_index)
end
if operation_mode ==11
% load shedding amount is limited by the demand of non-vital loads
load_shedding(1, 1:OPTIONS.N_t) <= OPTIONS.island1_non_load(1, 1:OPTIONS.N_t)
load_shedding(2, 1:OPTIONS.N_t) <= OPTIONS.island2_non_load(1, 1:OPTIONS.N_t)
else
load_shedding(1, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
load_shedding(2, 1:OPTIONS.N_t) == zeros(1, OPTIONS.N_t)
end
end
% the difference of redundant switch is shown in master problem,
% here only obtain the dual value
dual_Sp : redundant_sw_s(1:2, :) == redundant_sw(1:2, :)
% dual_Ss : redundant_sw_s(3:4, :) == redundant_sw(3:4, :)
cvx_end
sub_optval = cvx_optval;
% sub_P.Pg = round(Pg, 5);
% sub_P.Pb = round(Pb, 5);
% sub_P.Pc = round(Pc, 5);
% sub_P.Pd = round(Pd, 5);
% sub_P.Ppr = round(Ppr, 5);
% sub_P.load_shedding = round(load_shedding, 5);
sub_P.Pg = Pg;
sub_P.Pb = Pb;
sub_P.Pc = Pc;
sub_P.Pd = Pd;
sub_P.Ppr = Ppr;
sub_P.load_shedding = load_shedding;
if strcmp(cvx_status, 'Infeasible')
disp('stop');
infeasible_flag = 1;
end
%% startup cost: first startup cost and other startup cost
startup_g = ( (sub_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) - [zeros(OPTIONS.N_g, 1) sub_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t-1)] ) >=1);
startup_cost = sum(OPTIONS.C_ss(1:OPTIONS.N_g, 1).'* startup_g ,2);
% shutdown = ( (sub_delta_g(1:OPTIONS.N_g,1:OPTIONS.N_t) - [ sub_delta_g(1:OPTIONS.N_g, 2:OPTIONS.N_t) zeros(OPTIONS.N_g,1) ] ) >=1);
% shutdown_cost = OPTIONS.weight(1)*sum(OPTIONS.C_ss(1:OPTIONS.N_g,1).'* shutdown ,2);
one_item_cost = sum(OPTIONS.G(1:OPTIONS.N_g, 3).' * sub_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) ,2) ;
objval_upperbound = sub_optval + sum(startup_cost) + one_item_cost;
sub_dual.switch(1:2, :) = dual_Sp;
% sub_dual.switch(3:4, :) = dual_Ss;
sub_dual.delta_g(1, :) = dual_delta_g1;
sub_dual.delta_g(2, :) = dual_delta_g2;
if 3 == OPTIONS.N_g
sub_dual.delta_g(3, :) = dual_delta_g3;
end
if abs(objval_upperbound - 14899.4643324579) <= 2
disp(objval_upperbound);
end
% disp('upperbound');
end
%% Optimal algorithm: solve the master problem which is used to determine the redundant switches and generator state
function [cvx_optval, master_delta_g, master_redundant_switch, benders_cut ] = optimization_masterproblem( operation_mode, benders_cut_lowerbound, Max_benders_iteration, Ppr_best_solution )
global OPTIONS accelerate_flag total_P upper_of_lowerbound total_sub total_dual infeasible_flag
% global total_sub total_dual
if Max_benders_iteration == 0
Max_benders_iteration = 1;
end
if ~exist('benders_cut', 'var')
benders_cut = 0;
end
if ~exist('Pd', 'var')
Pd = 0;
end
% cvx_begin
cvx_solver Mosek
cvx_begin quiet
variable master_delta_g(OPTIONS.N_g, OPTIONS.N_t) binary
variable startup_g(OPTIONS.N_g, OPTIONS.N_t) binary
% variable shutdown_g(OPTIONS.N_g, OPTIONS.N_t) binary
variable master_redundant_switch(2, OPTIONS.N_t) binary
variable switch_change(2, OPTIONS.N_t) binary
variable relax_power_range(1, OPTIONS.N_t) nonnegative
variable benders_cut
minimize( sum(OPTIONS.G(1:OPTIONS.N_g, 3).' * master_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
+ sum(OPTIONS.C_ss(1:OPTIONS.N_g, 1).' * startup_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
+ OPTIONS.Penalty_D * sum(relax_power_range, 2) + benders_cut )
subject to
% startup detect
startup_g(1:OPTIONS.N_g, 1) >= master_delta_g(1:OPTIONS.N_g, 1) - zeros(OPTIONS.N_g, 1)
for t_index = 2 : OPTIONS.N_t
startup_g(1:OPTIONS.N_g, t_index) >= master_delta_g(1:OPTIONS.N_g, t_index) - master_delta_g(1:OPTIONS.N_g, t_index-1)
end
% generator operation time (rising edge)
for t_index = 1 : OPTIONS.N_t-OPTIONS.Tmin_g_st+1
sum(master_delta_g(1:OPTIONS.N_g, t_index:t_index + OPTIONS.Tmin_g_st-1), 2) >= OPTIONS.Tmin_g_st * startup_g(1:OPTIONS.N_g, t_index)
end
% edge condition in OPTIONS.N_t - OPTIONS.Tmin_g_st+2 to OPTIONS.N_t
for t_index = OPTIONS.N_t-OPTIONS.Tmin_g_st+2 : OPTIONS.N_t
sum(master_delta_g(1:OPTIONS.N_g, t_index:OPTIONS.N_t), 2) >= OPTIONS.Tmin_g_st * startup_g(1:OPTIONS.N_g, t_index)
end
% in the normal mode, redundant switches are determined.
if operation_mode <= 3
if operation_mode == 3
% switch change detect
switch_change(1, 1) >= (master_redundant_switch(1, 1) - 1)
switch_change(2, 1) >= (master_redundant_switch(2, 1) - 0)
switch_change(1, 2:OPTIONS.N_t) >= (master_redundant_switch(1, 2:OPTIONS.N_t) - master_redundant_switch(1, 1:OPTIONS.N_t-1))
switch_change(2, 2:OPTIONS.N_t) >= (master_redundant_switch(2, 2:OPTIONS.N_t) - master_redundant_switch(2, 1:OPTIONS.N_t-1))
% Redundent switch time
for t_index = 1 : OPTIONS.N_t-OPTIONS.Tmin_sw+1
sum(master_redundant_switch(1, t_index:t_index + OPTIONS.Tmin_sw-1), 2) >= OPTIONS.Tmin_sw * switch_change(1, t_index)
sum(master_redundant_switch(2, t_index:t_index + OPTIONS.Tmin_sw-1), 2) >= OPTIONS.Tmin_sw * switch_change(2, t_index)
end
for t_index = OPTIONS.N_t-OPTIONS.Tmin_sw+2 : OPTIONS.N_t
sum(master_redundant_switch(1, t_index:OPTIONS.N_t), 2) >= OPTIONS.Tmin_sw * switch_change(1, t_index)
sum(master_redundant_switch(2, t_index:OPTIONS.N_t), 2) >= OPTIONS.Tmin_sw * switch_change(2, t_index)
end
else
master_redundant_switch(1, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(1, 1:OPTIONS.N_t)
master_redundant_switch(2, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(2, 1:OPTIONS.N_t)
end
% master_redundant_switch(3, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(3, 1:OPTIONS.N_t)
% master_redundant_switch(4, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(4, 1:OPTIONS.N_t)
if 2 == OPTIONS.N_g
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval ...
+ total_dual(index_benders).delta_g(1, 1:OPTIONS.N_t) ...
* (master_delta_g(1, :).' - total_sub(index_benders).delta_g(1, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(2, 1:OPTIONS.N_t) ...
* (master_delta_g(2, :).' - total_sub(index_benders).delta_g(2, 1:OPTIONS.N_t).');
end
elseif 3 == OPTIONS.N_g
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval ...
+ total_dual(index_benders).delta_g(1, 1:OPTIONS.N_t) ...
* (master_delta_g(1, :).' - total_sub(index_benders).delta_g(1, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(2, 1:OPTIONS.N_t) ...
* (master_delta_g(2, :).' - total_sub(index_benders).delta_g(2, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(3, 1:OPTIONS.N_t) ...
* (master_delta_g(3, :).' - total_sub(index_benders).delta_g(3, 1:OPTIONS.N_t).');
end
end
% in the fault mode, redundant switches need to be reconfigurated.
elseif operation_mode <= 7
if operation_mode == 7
% switch change detect
switch_change(1, 1) >= (master_redundant_switch(1, 1) - 1)
switch_change(2, 1) >= (master_redundant_switch(2, 1) - 0)
switch_change(1, 2:OPTIONS.N_t) >= (master_redundant_switch(1, 2:OPTIONS.N_t) - master_redundant_switch(1, 1:OPTIONS.N_t-1))
switch_change(2, 2:OPTIONS.N_t) >= (master_redundant_switch(2, 2:OPTIONS.N_t) - master_redundant_switch(2, 1:OPTIONS.N_t-1))
% Redundent switch time
for t_index = 1 : OPTIONS.N_t-OPTIONS.Tmin_sw+1
sum(master_redundant_switch(1, t_index:t_index + OPTIONS.Tmin_sw-1), 2) >= OPTIONS.Tmin_sw * switch_change(1, t_index)
sum(master_redundant_switch(2, t_index:t_index + OPTIONS.Tmin_sw-1), 2) >= OPTIONS.Tmin_sw * switch_change(2, t_index)
end
for t_index = OPTIONS.N_t-OPTIONS.Tmin_sw+2 : OPTIONS.N_t
sum(master_redundant_switch(1, t_index:OPTIONS.N_t), 2) >= OPTIONS.Tmin_sw * switch_change(1, t_index)
sum(master_redundant_switch(2, t_index:OPTIONS.N_t), 2) >= OPTIONS.Tmin_sw * switch_change(2, t_index)
end
else
master_redundant_switch(1, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(1, 1:OPTIONS.N_t)
master_redundant_switch(2, 1:OPTIONS.N_t) == total_sub(1).redundant_sw(2, 1:OPTIONS.N_t)
end
% benders cuts % in the fault mode, redundant switches need to be reconfigurated.
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval ...
+ total_dual(index_benders).delta_g(1, 1:OPTIONS.N_t) ...
* (master_delta_g(1, :).' - total_sub(index_benders).delta_g(1, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(2, 1:OPTIONS.N_t) ...
* (master_delta_g(2, :).' - total_sub(index_benders).delta_g(2, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).switch(1, 1:OPTIONS.N_t) ...
* (master_redundant_switch(1, :).' - total_sub(index_benders).redundant_sw(1, 1:OPTIONS.N_t).')...
+ total_dual(index_benders).switch(2, 1:OPTIONS.N_t) ...
* ((master_redundant_switch(2, :)).' - total_sub(index_benders).redundant_sw(2, 1:OPTIONS.N_t).');
end
elseif operation_mode <= 11
master_redundant_switch(1:2, 1:OPTIONS.N_t) == zeros(2, OPTIONS.N_t)
switch_change(1:2, 1:OPTIONS.N_t) == zeros(2, OPTIONS.N_t)
% benders cuts. In this case, there are three generators.
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval ...
+ total_dual(index_benders).delta_g(1, 1:OPTIONS.N_t) ...
* (master_delta_g(1, :).' - total_sub(index_benders).delta_g(1, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(2, 1:OPTIONS.N_t) ...
* (master_delta_g(2, :).' - total_sub(index_benders).delta_g(2, 1:OPTIONS.N_t).') ...
+ total_dual(index_benders).delta_g(3, 1:OPTIONS.N_t) ...
* (master_delta_g(3, :).' - total_sub(index_benders).delta_g(3, 1:OPTIONS.N_t).');
end
end
switch accelerate_flag
case 1
% % low bound of master problem
% sum(OPTIONS.G(1:OPTIONS.N_g, 3).' * master_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
% + sum(OPTIONS.C_ss(1:OPTIONS.N_g, 1).' * startup_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
% + benders_cut >= upper_of_lowerbound
case 2
% low bound of master problem
sum(OPTIONS.G(1:OPTIONS.N_g, 3).' * master_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
+ sum(OPTIONS.C_ss(1:OPTIONS.N_g, 1).' * startup_g(1:OPTIONS.N_g, 1:OPTIONS.N_t), 2) ...
+ benders_cut >= upper_of_lowerbound
% speedup constraints: power range & lower bound
if operation_mode <=3 % normal mode
% master_delta_g(1, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(1) + master_delta_g(2, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(2) ...
% + OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) >= OPTIONS.P_L_TIME_off + total_P(Max_benders_iteration).Ppr
OPTIONS.Pg_Max(1, 1:OPTIONS.N_g) * master_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) ...
+ 3*OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) + relax_power_range >= OPTIONS.P_L_TIME_off + Ppr_best_solution
OPTIONS.Pg_Min(1, 1:OPTIONS.N_g) * master_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) ...
+ 3*OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.P_total_vs + 0 % Ppr
elseif operation_mode <= 7 % semi-island fault mode
if Max_benders_iteration >= 1
master_delta_g(1, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(1) + 3*OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) ...
+ relax_power_range >= OPTIONS.island1_max + Ppr_best_solution
% >= OPTIONS.island1_max + total_P(Max_benders_iteration).Ppr
master_delta_g(1, 1:OPTIONS.N_t)*OPTIONS.Pg_Min(1) + 3*OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.island1_min + 0 % Ppr
master_delta_g(2, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(2) + OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) >= OPTIONS.island2_max
master_delta_g(2, 1:OPTIONS.N_t)*OPTIONS.Pg_Min(2) + OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.island2_min + 0 % Ppr
end
% ppr in island 1, there must have a worked generator.
% master_delta_g(1, 1:OPTIONS.N_t) >= master_delta_g(2, 1:OPTIONS.N_t)
elseif operation_mode <= 11 % island fault mode
if Max_benders_iteration >= 1
% master_delta_g(1, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(1) + OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) ...
% >= OPTIONS.island1_max + total_P(Max_benders_iteration).Ppr
% master_delta_g(1, 1:OPTIONS.N_t)*OPTIONS.Pg_Min(1) + OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.island1_min + 0 % Ppr
OPTIONS.Pg_Max(1, 1:2)*master_delta_g(1:2, 1:OPTIONS.N_t) + 2*OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) ...
+ relax_power_range >= OPTIONS.island1_max + Ppr_best_solution
OPTIONS.Pg_Min(1, 1:2)*master_delta_g(1:2, 1:OPTIONS.N_t) + 2*OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.island1_min
master_delta_g(3, 1:OPTIONS.N_t)*OPTIONS.Pg_Max(3) + OPTIONS.Pb_Max * ones(1, OPTIONS.N_t) >= OPTIONS.island2_max
master_delta_g(3, 1:OPTIONS.N_t)*OPTIONS.Pg_Min(3) + OPTIONS.Pb_Min * ones(1, OPTIONS.N_t) <= OPTIONS.island2_min + 0 % Ppr
end
% ppr in island 1, there must have a worked generator.
% sum(master_delta_g(1:2, 1:OPTIONS.N_t), 1)/2 >= master_delta_g(3, 1:OPTIONS.N_t)
end
% speedup constraint: lower bound
case 3
% benders_cut >= benders_cut_lowerbound
case 4
% speedup constraint: lower bound
benders_cut >= benders_cut_lowerbound
% otherwise % non-constriant
end
cvx_end
cvx_optval = cvx_optval - OPTIONS.Penalty_D * sum(relax_power_range, 2);
if strcmp(cvx_status, 'Infeasible')
disp('Master Infeasible');
infeasible_flag = 2;
end
if strcmp(cvx_status, 'Failed')
disp('Master Failed');
infeasible_flag = 3;
end
end
%% LNBD algorithm: sovlve the subproblem t which is used to calculate the optimal power of generators and ESMs at time t
function [objval_upperbound, sub_optval, sub_P, sub_dual, reduced_distance] = optimization_subproblem_t( operation_mode, delta_g, redundant_sw )
% in this function, the return variable: suboptval is different with that
% in the function of optimal algorithm.
global OPTIONS with_iteration_D infeasible_flag
% XXX_on denotes the variable that calculated in this iteration.
% inital the rest parameters
Pg = zeros(OPTIONS.N_g, OPTIONS.N_t);
Pb = zeros(OPTIONS.N_e, OPTIONS.N_t);
E = zeros(OPTIONS.N_e, OPTIONS.N_t);
Pc = zeros(OPTIONS.N_g, OPTIONS.N_t);
Pd = zeros(OPTIONS.N_g, OPTIONS.N_t);
Ppr = zeros(1, OPTIONS.N_t);
load_shedding = zeros(2, OPTIONS.N_t);
dual_Sp = zeros(2, OPTIONS.N_t);
dual_Ss = zeros(2, OPTIONS.N_t);
dual_delta_g1 = zeros(1, OPTIONS.N_t);
dual_delta_g2 = zeros(1, OPTIONS.N_t);
if 3 == OPTIONS.N_g
dual_delta_g3 = zeros(1, OPTIONS.N_t);
end
Rest_Distance = OPTIONS.Distance;
Distance_obj_on = zeros(1, OPTIONS.N_t);
Rest_ppr_avg = OPTIONS.P_pr_avg;
D_d = zeros(1, OPTIONS.N_t);
sub_optval_on = 0;
sub_optval_t = zeros(1, OPTIONS.N_t+1);
sub_optval = zeros(2, OPTIONS.N_t+1);
if OPTIONS.N_e == 4
if operation_mode <= 3
p_ESM_avg = (sum(OPTIONS.E_Max, 2) - sum(OPTIONS.E_Min, 2))/OPTIONS.N_t;
elseif operation_mode <= 11
p_ESM_avg(1, 1) = sum(OPTIONS.E_Max(1, 1:3) - OPTIONS.E_Min(1, 1:3), 2)/OPTIONS.N_t;
p_ESM_avg(2, 1) = (OPTIONS.E_Max(4) - OPTIONS.E_Min(4))/OPTIONS.N_t;
end
elseif OPTIONS.N_e == 3
if operation_mode <= 3
p_ESM_avg = (sum(OPTIONS.E_Max, 2) - sum(OPTIONS.E_Min, 2))/OPTIONS.N_t;
elseif operation_mode <= 11
p_ESM_avg(1, 1) = sum(OPTIONS.E_Max(1, 1:2) - OPTIONS.E_Min(1, 1:2), 2)/OPTIONS.N_t;
p_ESM_avg(2, 1) = (OPTIONS.E_Max(3) - OPTIONS.E_Min(3))/OPTIONS.N_t;
end
end
% update the rest parameters: rest distance, rest average ppr, and the
% power deviation of load at next time slot.
temp_T_D_d = OPTIONS.Distance;
best_sub_optval_on = inf;
best_sub_optval_t = zeros(1, OPTIONS.N_t);
for index_loop = 1:10
sub_optval_on = 0;
for index_time = 1:OPTIONS.N_t
% tic;
switch index_time
% all the load demand must be meet at the last time slot (N_t).
% So varphi = 1
case OPTIONS.N_t
sub_varphi_Pl = 1.0;
sub_varphi_Ppr = 0.0;
% the load demand at other time slot is meet proportionally.
otherwise
sub_varphi_Pl = OPTIONS.varphi_Pl;
sub_varphi_Ppr = OPTIONS.varphi_Ppr;
end
if index_time == 1
E_last_time = OPTIONS.E_Max.';
else
E_last_time = E(1:OPTIONS.N_e, index_time-1);
end
if index_loop == 1
[upper_bound_Pb, Distance_slot_obj] = generate_upperbound(operation_mode, Rest_ppr_avg, sub_varphi_Ppr, ...
sub_varphi_Pl, E_last_time, index_time, p_ESM_avg, delta_g);
else
[upper_bound_Pb] = generate_upperbound(operation_mode, Rest_ppr_avg, sub_varphi_Ppr, ...
sub_varphi_Pl, E_last_time, index_time, p_ESM_avg, delta_g);
Distance_slot_obj = Distance_obj_on(index_time);
end
% tic;
% cvx_solver SeDuMi
cvx_begin quiet
variable Pg_on(OPTIONS.N_g,1) nonnegative
variable Pb_on(OPTIONS.N_e,1)
variable E_on(OPTIONS.N_e,1) nonnegative
variable Ppr_on(1) nonnegative
variable sub_delta_g(OPTIONS.N_g,1)
variable redundant_sw_s(4,1)
variable load_shedding_on(2, 1) nonnegative
variable reduced_distance_on nonnegative
variable Pc_on(OPTIONS.N_g,1) nonnegative
variable Pd_on(OPTIONS.N_g,1) nonnegative
variable PcR(OPTIONS.N_g,1) nonnegative
variable PdR(OPTIONS.N_g,1) nonnegative
dual variable temp_dual_delta_g1
dual variable temp_dual_delta_g2
if 3 == OPTIONS.N_g
dual variable temp_dual_delta_g3
end
dual variable temp_dual_Sp
dual variable temp_dual_Ss
minimize( OPTIONS.G(1:OPTIONS.N_g, 1).' * power(Pg_on(1:OPTIONS.N_g, 1), 2) ...
+ OPTIONS.G(1:OPTIONS.N_g, 2).' * power(Pg_on(1:OPTIONS.N_g, 1), 1) ...
+ OPTIONS.Xi_E * OPTIONS.E(1:OPTIONS.N_e, 1).' * power(Pb_on(1:OPTIONS.N_e, 1), 2) ...
+ OPTIONS.Xi_E * sum(OPTIONS.E(1:OPTIONS.N_e, 2), 1)...
+ OPTIONS.Penalty_L * sum(load_shedding_on(1:2, 1), 1) ...
+ 1.1 * OPTIONS.Penalty_D * reduced_distance_on ...
+ 10 * OPTIONS.Penalty_D * sum(Pc_on(1:OPTIONS.N_g), 1) ...
+ 10 * OPTIONS.Penalty_D * sum(Pd_on(1:OPTIONS.N_g), 1) )
subject to
% the range constraints of all the variables
for index_g = 1:OPTIONS.N_g
Pg_on(index_g, 1) <= sub_delta_g(index_g, 1) * OPTIONS.Pg_Max(index_g) ...
+ Pc_on(index_g)
Pg_on(index_g, 1) >= sub_delta_g(index_g, 1) * OPTIONS.Pg_Min(index_g) ...
- Pd_on(index_g)
end
temp_dual_delta_g1 : sub_delta_g(1,1) == delta_g(1,index_time)
temp_dual_delta_g2 : sub_delta_g(2,1) == delta_g(2,index_time)
if 3 == OPTIONS.N_g
temp_dual_delta_g3 : sub_delta_g(3,1) == delta_g(3,index_time)
end
% ramping rate power of generators
if index_time == 1
for index_g = 1:OPTIONS.N_g
Pg_on(index_g, 1) <= OPTIONS.R_G(index_g) %+ PcR(1)
end
elseif index_time == OPTIONS.N_t
for index_g = 1:OPTIONS.N_g
Pg_on(index_g, 1) - Pg(index_g, index_time-1) >= -OPTIONS.R_G(index_g) %- PdR(1)
0 - Pg_on(index_g, 1) >= -OPTIONS.R_G(index_g) %- PcR(2)
end
else
for index_g = 1:OPTIONS.N_g
Pg_on(index_g, 1) - Pg(index_g, index_time-1) <= OPTIONS.R_G(index_g) %+ PcR(1)
Pg_on(index_g, 1) - Pg(index_g, index_time-1) >= -OPTIONS.R_G(index_g) %- PdR(1)
end
end
% propulsion power limitation
Ppr_on(1,1) <= OPTIONS.Ppr_Max
% ESM limitation constraints
% the basic constraints of ESMs
for index_e = 1:OPTIONS.N_e
Pb_on(index_e, 1) <= OPTIONS.Pb_Max
Pb_on(index_e, 1) >= OPTIONS.Pb_Min
end
% the upper bound in suboptimal algorithm
if operation_mode <= 3
% the scaler factor is related with load power in each
% island part and the adjusting factor.
% Pb_on(1,1) + Pb_on(2,1) <= upper_bound_ESM_P
sum(Pb_on(1:OPTIONS.N_e, 1), 1) <= upper_bound_Pb
elseif operation_mode <= 7
% the scaler factor is related with load power in each
% island part and the adjusting factor.
% Pb_on(1,1) <= upper_bound_ESM1P
% Pb_on(2,1) <= upper_bound_ESM2P
sum(Pb_on(1:OPTIONS.N_e-1, 1), 1) <= upper_bound_Pb(1)
Pb_on(OPTIONS.N_e, 1) <= upper_bound_Pb(2)
end
% charging and discharging
for index_e = 1:OPTIONS.N_e
E_on(index_e, 1) <= OPTIONS.E_Max(index_e)
E_on(index_e, 1) >= OPTIONS.E_Min(index_e)
end
% ESM output power and the capacity constraints
if index_time == 1
for index_e = 1:OPTIONS.N_e
E_on(index_e, 1) == OPTIONS.E_Max(index_e) - Pb_on(index_e, 1)
end
else
for index_e = 1:OPTIONS.N_e
E_on(index_e, 1) == E(index_e, index_time-1) - Pb_on(index_e, 1)
end
end
% system power balance & load shedding
if operation_mode <= 3
OPTIONS.P_L_TIME_off(1, index_time) - sum(load_shedding_on(1:2, 1)) + Ppr_on(1, 1) ...
== sum( Pg_on(1:OPTIONS.N_g, 1) ) + sum(Pb_on(1:OPTIONS.N_e, 1))
% load shedding range
if operation_mode == 3
sum(load_shedding_on(1:2, 1)) <= OPTIONS.P_no(index_time)
else
load_shedding_on(1) == zeros(1, 1)
load_shedding_on(2) == zeros(1, 1)
end
elseif operation_mode <= 7
for t_index = index_time
redundant_sw_s(1:2, 1).' * OPTIONS.Coupled_load(:, index_time) + OPTIONS.island1_load(1, t_index) ...
- load_shedding_on(1, 1) + Ppr_on(1, 1) == (Pg_on(1, 1)) + sum(Pb_on(1:OPTIONS.N_e-1, 1), 1)
redundant_sw_s(3:4, 1).'* OPTIONS.Coupled_load(:, index_time) + OPTIONS.island2_load(1, t_index) ...
- load_shedding_on(2, 1) == (Pg_on(2, 1)) + Pb_on(OPTIONS.N_e, 1)
end
% load shedding range
if operation_mode == 7
load_shedding_on(1) <= OPTIONS.island1_non_load(1, index_time)
load_shedding_on(2) <= OPTIONS.island2_non_load(1, index_time)
else
load_shedding_on(1) == zeros(1, 1)
load_shedding_on(2) == zeros(1, 1)
end
elseif operation_mode <= 11
for t_index = index_time
OPTIONS.island1_load(1, t_index) - load_shedding_on(1, 1) + Ppr_on(1, 1) == sum(Pg_on(1:OPTIONS.N_g-1, 1), 1) ...
+ sum(Pb_on(1:OPTIONS.N_e-1, 1), 1)
OPTIONS.island2_load(1, t_index) - load_shedding_on(2, 1) == (Pg_on(OPTIONS.N_g, 1)) + Pb_on(OPTIONS.N_e, 1)
end
% load shedding range
if operation_mode == 11
load_shedding_on(1) <= OPTIONS.island1_non_load(1, index_time)
load_shedding_on(2) <= OPTIONS.island2_non_load(1, index_time)
else
load_shedding_on(1) == zeros(1, 1)
load_shedding_on(2) == zeros(1, 1)
end
end
temp_dual_Sp : redundant_sw_s(1:2, 1) == redundant_sw(1:2, index_time)
temp_dual_Ss : redundant_sw_s(3:4, 1) == redundant_sw(3:4, index_time)
% voyage planning
switch mod(operation_mode, 4)
case 0 % Only GS
Ppr_on(1, 1) == OPTIONS.P_pr_avg;
Pb_on(1:2, 1) == 0;
case 1 % GS & ESSC
Ppr_on(1, 1) == OPTIONS.P_pr_avg;
case 2 % GS & ESSC & PPA
(Ppr_on(1, 1)./2.2e-3).^(1/3) >= Distance_slot_obj - reduced_distance_on;
case 3 % GS & ESSC & PPA (load shedding )
(Ppr_on(1, 1)./2.2e-3).^(1/3) >= Distance_slot_obj - reduced_distance_on;
end
cvx_end
% test_time = toc;
% fprintf('\nSP part 2 at %d is %5.2f s \n\n', index_time, test_time);
if strcmp(cvx_status, 'Infeasible')
disp('Sub-t Infeasible');
infeasible_flag = 4;
break;
end
Pg(1:OPTIONS.N_g, index_time) = Pg_on(1:OPTIONS.N_g, 1);
Pb(1:OPTIONS.N_e, index_time) = Pb_on(1:OPTIONS.N_e, 1);
E(1:OPTIONS.N_e, index_time) = E_on(1:OPTIONS.N_e, 1);
Pc(1:OPTIONS.N_g, index_time) = Pc_on(1:OPTIONS.N_g, 1);
Pd(1:OPTIONS.N_g, index_time) = Pd_on(1:OPTIONS.N_g, 1);
Ppr(1, index_time) = Ppr_on(1, 1);
load_shedding(1:2, index_time) = load_shedding_on(1:2, 1);
% with_iteration_D = 0: D(t) is only adjusted by load change and
% varphi_Pl. sub_optval equals to cvx_optval
% with_iteration_D = 1: D(t) is iterated at each time slot based on the
% load change, varphi_Pl and D_d of last time slot.
if with_iteration_D == 0
% Rest_Distance = Rest_Distance - Distance_slot_obj;
% Rest_velocity_avg = Rest_Distance/(OPTIONS.N_t-index_time);
Rest_ppr_avg = OPTIONS.P_pr_avg;
sub_optval_t(index_time) = cvx_optval;
sub_optval_on = sub_optval_on + cvx_optval;
D_d(index_time) = reduced_distance_on;
Distance_obj_on(index_time) = Distance_slot_obj - reduced_distance_on;
if index_time == OPTIONS.N_t
Rest_Distance = sum(D_d);
end
elseif with_iteration_D == 1
Rest_Distance = Rest_Distance - Distance_slot_obj + reduced_distance_on;
if index_time < OPTIONS.N_t
Rest_velocity_avg = Rest_Distance/(OPTIONS.N_t-index_time);
end
Rest_ppr_avg = (Rest_velocity_avg).^3*2.2e-3;
% the penalty cost of reduced distance is calculated at the last
% iteration, thus it must subtract the penalty cost in the total cost
% before the last iteration.
if index_time < OPTIONS.N_t
sub_optval_t(index_time) = cvx_optval - 1.02 * OPTIONS.Penalty_D * reduced_distance_on;
sub_optval_on = sub_optval_on + sub_optval_t(index_time);
else
sub_optval_on = sub_optval_on + cvx_optval;
sub_optval_t(index_time) = cvx_optval - 1.02 * OPTIONS.Penalty_D * reduced_distance_on;
sub_optval_t(index_time+1) = 1.02 * OPTIONS.Penalty_D * reduced_distance_on;
end
elseif with_iteration_D == 2
end
dual_Sp(1:2, index_time) = temp_dual_Sp;
dual_Ss(1:2, index_time) = temp_dual_Ss;
dual_delta_g1(1, index_time) = temp_dual_delta_g1;
dual_delta_g2(1, index_time) = temp_dual_delta_g2;
if 3 == OPTIONS.N_g
dual_delta_g3(1, index_time) = temp_dual_delta_g3;
end
end
if sub_optval_on < best_sub_optval_on
best_sub_optval_on = sub_optval_on;
best_sub_optval_t = sub_optval_t;
sub_P.Pg = Pg;
sub_P.Pb = Pb;
sub_P.Pc = Pc;
sub_P.Pd = Pd;
sub_P.Ppr = Ppr;
sub_P.load_shedding = load_shedding;
sub_dual.switch(1:2, 1:OPTIONS.N_t) = dual_Sp;
sub_dual.switch(3:4, 1:OPTIONS.N_t) = dual_Ss;
sub_dual.delta_g(1, 1:OPTIONS.N_t) = dual_delta_g1;
sub_dual.delta_g(2, 1:OPTIONS.N_t) = dual_delta_g2;
if 3 == OPTIONS.N_g
sub_dual.delta_g(3, 1:OPTIONS.N_t) = dual_delta_g3;
end
reduced_distance = Rest_Distance;
disp(index_loop);
end
% If it exists any (D_d(t) > 0.01 and D_d(t) <= 0.01), average the D(t) to reduce the D_d.)
% In addition, if the reduced D_d approximately equals to zero, there
% is not optimization space for D_d. T
num_nonzero = sum(D_d >= 0.01);
disp((temp_T_D_d - sum(D_d)));
if (num_nonzero < 12) && (num_nonzero > 0) && ((temp_T_D_d - sum(D_d)) >= 1)
Distance_obj_on = Distance_obj_on + Rest_Distance/OPTIONS.N_t;
else
break;
end
temp_T_D_d = sum(D_d);
if infeasible_flag == 1
break;
end
end
sub_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) = delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t);
sub_optval(1, 1) = best_sub_optval_on;
sub_optval(2, 1:OPTIONS.N_t+1) = best_sub_optval_t;
%% startup cost: first startup cost and other startup cost
one_item_cost = sum(OPTIONS.G(1:OPTIONS.N_g, 3).' * sub_delta_g(1:OPTIONS.N_g, 1:OPTIONS.N_t) ,2) ;
objval_upperbound = sub_optval_on + one_item_cost;
if abs(objval_upperbound - 18085) < 10
disp(objval_upperbound);
end
end
%% Subfunction of LNBD algorithm: generate the upper bound of output power of ESMs based on suboptimal decomposition strategy
function [upper_bound_Pb, Distance_slot_obj] = generate_upperbound(operation_mode, Rest_ppr_avg, sub_varphi_Ppr, sub_varphi_Pl, E_last_time, index_time, p_ESM_avg, delta_g)
global OPTIONS
% upper bound in different operation mode
if operation_mode <= 3
Distance_slot_obj = (( Rest_ppr_avg - sub_varphi_Ppr * OPTIONS.Delta_PL(index_time) )/2.2e-3)^(1/3);
% ESM output power and the capacity constraints
if index_time == 1
rest_pmax_ESM = sum(OPTIONS.E_Max) - sum(OPTIONS.E_Min);
rest_pmin_ESM = sum(OPTIONS.E_Max) - sum(OPTIONS.E_Max);
else
rest_pmax_ESM = sum(E_last_time, 1) - sum(OPTIONS.E_Min);
rest_pmin_ESM = sum(E_last_time, 1) - sum(OPTIONS.E_Max);
end
if sum(delta_g(1:OPTIONS.N_g, index_time)) > 0
if OPTIONS.Delta_PL(index_time) >= 0
upper_bound_ESM_P = roundn(min(p_ESM_avg + sub_varphi_Pl * OPTIONS.Delta_PL(index_time), rest_pmax_ESM), -2);
else
upper_bound_ESM_P = ceil(max(p_ESM_avg + sub_varphi_Pl * OPTIONS.Delta_PL(index_time), rest_pmin_ESM)*100)/100;
end
else
upper_bound_ESM_P = sum(OPTIONS.E_Max) - sum(OPTIONS.E_Min);
end
upper_bound_Pb = upper_bound_ESM_P;
elseif operation_mode <= 7
% propulsion power modules locate in island part 1,
% power adjustment only uses OPTIONS.Delta_PL_island1
Distance_slot_obj = ((Rest_ppr_avg - sub_varphi_Ppr * OPTIONS.Delta_PL_island1(index_time) )/2.2e-3 )^(1/3);
% Maximum charge and discharge power of ESM in different islands
% The initial capacity of ESM is the maximum value (OPTIONS.E_Max)
if index_time == 1
rest_pmax_ESM1 = sum(OPTIONS.E_Max(1:OPTIONS.N_e-1) - OPTIONS.E_Min(1:OPTIONS.N_e-1), 2);
rest_pmax_ESM2 = OPTIONS.E_Max(OPTIONS.N_e) - OPTIONS.E_Min(OPTIONS.N_e);
rest_pmin_ESM1 = sum(OPTIONS.E_Max(1:OPTIONS.N_e-1) - OPTIONS.E_Max(1:OPTIONS.N_e-1), 2);
rest_pmin_ESM2 = OPTIONS.E_Max(OPTIONS.N_e) - OPTIONS.E_Max(OPTIONS.N_e);
else
rest_pmax_ESM1 = sum(E_last_time(1:OPTIONS.N_e-1, 1).' - OPTIONS.E_Min(1:OPTIONS.N_e-1), 2);
rest_pmax_ESM2 = E_last_time(OPTIONS.N_e, 1) - OPTIONS.E_Min(OPTIONS.N_e);
rest_pmin_ESM1 = sum(E_last_time(1:OPTIONS.N_e-1, 1).' - OPTIONS.E_Max(1:OPTIONS.N_e-1), 2);
rest_pmin_ESM2 = E_last_time(OPTIONS.N_e, 1) - OPTIONS.E_Max(OPTIONS.N_e);
end
% charge and discharge bound in island 1
if sum(delta_g(1,index_time))>=1
if OPTIONS.Delta_PL_island1(index_time) >= 0
upper_bound_ESM1P = roundn(min(p_ESM_avg(1, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island1(index_time), rest_pmax_ESM1), -2);
else
upper_bound_ESM1P = roundn(max(p_ESM_avg(1, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island1(index_time), rest_pmin_ESM1), -2);
end
else
upper_bound_ESM1P = OPTIONS.E_Max(1) - OPTIONS.E_Min(1);
end
% charge and discharge bound in i
if sum(delta_g(2,index_time))>=1
if OPTIONS.Delta_PL_island2(index_time) >= 0
upper_bound_ESM2P = roundn(min(p_ESM_avg(2, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island2(index_time), rest_pmax_ESM2), -2);
else
upper_bound_ESM2P = roundn(max(p_ESM_avg(2, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island2(index_time), rest_pmin_ESM2), -2);
end
else
upper_bound_ESM2P = OPTIONS.E_Max(2) - OPTIONS.E_Min(2);
end
upper_bound_Pb(1) = upper_bound_ESM1P;
upper_bound_Pb(2) = upper_bound_ESM2P;
elseif operation_mode <= 11
% propulsion power modules locate in island part 1,
% power adjustment only uses OPTIONS.Delta_PL_island1
Distance_slot_obj = ((Rest_ppr_avg - sub_varphi_Ppr * OPTIONS.Delta_PL_island1(index_time) )/2.2e-3 )^(1/3);
% Maximum charge and discharge power of ESM in different islands
% The initial capacity of ESM is the maximum value (OPTIONS.E_Max)
if index_time == 1
rest_pmax_ESM1 = sum(OPTIONS.E_Max(1:OPTIONS.N_e-1) - OPTIONS.E_Min(1:OPTIONS.N_e-1), 2);
rest_pmax_ESM2 = OPTIONS.E_Max(OPTIONS.N_e) - OPTIONS.E_Min(OPTIONS.N_e);
rest_pmin_ESM1 = sum(OPTIONS.E_Max(1:OPTIONS.N_e-1) - OPTIONS.E_Max(1:OPTIONS.N_e-1), 2);
rest_pmin_ESM2 = OPTIONS.E_Max(OPTIONS.N_e) - OPTIONS.E_Max(OPTIONS.N_e);
else
rest_pmax_ESM1 = sum(E_last_time(1:OPTIONS.N_e-1, 1).' - OPTIONS.E_Min(1:OPTIONS.N_e-1), 2);
rest_pmax_ESM2 = E_last_time(OPTIONS.N_e, 1) - OPTIONS.E_Min(OPTIONS.N_e);
rest_pmin_ESM1 = sum(E_last_time(1:OPTIONS.N_e-1, 1).' - OPTIONS.E_Max(1:OPTIONS.N_e-1), 2);
rest_pmin_ESM2 = E_last_time(OPTIONS.N_e, 1) - OPTIONS.E_Max(OPTIONS.N_e);
end
% charge and discharge bound in island 1
if sum(delta_g(1,index_time))>=1
if OPTIONS.Delta_PL_island1(index_time) >= 0
upper_bound_ESM1P = roundn(min(p_ESM_avg(1, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island1(index_time), rest_pmax_ESM1), -2);
else
upper_bound_ESM1P = roundn(max(p_ESM_avg(1, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island1(index_time), rest_pmin_ESM1), -2);
end
else
upper_bound_ESM1P = OPTIONS.E_Max(1) - OPTIONS.E_Min(1);
end
% charge and discharge bound in i
if sum(delta_g(2,index_time))>=1
if OPTIONS.Delta_PL_island2(index_time) >= 0
upper_bound_ESM2P = roundn(min(p_ESM_avg(2, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island2(index_time), rest_pmax_ESM2), -2);
else
upper_bound_ESM2P = roundn(max(p_ESM_avg(2, 1) + ...
sub_varphi_Pl * OPTIONS.Delta_PL_island2(index_time), rest_pmin_ESM2), -2);
end
else
upper_bound_ESM2P = OPTIONS.E_Max(2) - OPTIONS.E_Min(2);
end
upper_bound_Pb(1) = upper_bound_ESM1P;
upper_bound_Pb(2) = upper_bound_ESM2P;
end
end
%% LNBD algorithm: the master problem which is used to determine the redundant switches and generator state
function [master_optval, master_delta_g, master_redundant_switch, benders_cut ] = optimization_masterproblem_t( operation_mode, benders_cut_lowerbound, Max_benders_iteration, Ppr_best_solution)
global OPTIONS accelerate_flag total_P upper_of_lowerbound total_sub total_dual with_iteration_D infeasible_flag
% global total_sub total_dual
if Max_benders_iteration == 0
Max_benders_iteration = 1;
end
if ~exist('benders_cut', 'var')
benders_cut = 0;
end
if ~exist('Pd', 'var')
Pd = 0;
end
master_delta_g = zeros(OPTIONS.N_g, OPTIONS.N_t);
master_redundant_switch = zeros(OPTIONS.N_g, OPTIONS.N_t);
sub_optval_on = 0;
for index_time = 1:OPTIONS.N_t
% cvx_begin
cvx_solver Mosek
cvx_begin quiet
variable delta_g_on(OPTIONS.N_g, 1) binary
variable redundant_switch_on(4, 1) binary
variable benders_cut
minimize( OPTIONS.G(1:OPTIONS.N_g, 3).' * delta_g_on(1:OPTIONS.N_g, 1) ...
+ benders_cut )
subject to
% Redundent_switch
redundant_switch_on(1, 1) + redundant_switch_on(2, 1) == 1;
redundant_switch_on(3, 1) + redundant_switch_on(4, 1) == 1;
% in the normal mode, redundant switches are determined.
if operation_mode <= 3
redundant_switch_on(1, 1) == total_sub(1).redundant_sw(1, index_time);
redundant_switch_on(2, 1) == total_sub(1).redundant_sw(2, index_time);
redundant_switch_on(3, 1) == total_sub(1).redundant_sw(3, index_time);
redundant_switch_on(4, 1) == total_sub(1).redundant_sw(4, index_time);
if 2 == OPTIONS.N_g
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval(2, index_time) ...
+ total_dual(index_benders).delta_g(1, index_time) ...
* (delta_g_on(1, 1).' - total_sub(index_benders).delta_g(1, index_time).') ...
+ total_dual(index_benders).delta_g(2, index_time) ...
* (delta_g_on(2, 1).' - total_sub(index_benders).delta_g(2, index_time).');
end
elseif 3 == OPTIONS.N_g
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval(2, index_time) ...
+ total_dual(index_benders).delta_g(1, index_time) ...
* (delta_g_on(1, 1).' - total_sub(index_benders).delta_g(1, index_time).') ...
+ total_dual(index_benders).delta_g(2, index_time) ...
* (delta_g_on(2, 1).' - total_sub(index_benders).delta_g(2, index_time).') ...
+ total_dual(index_benders).delta_g(3, index_time) ...
* (delta_g_on(3, 1).' - total_sub(index_benders).delta_g(3, index_time).');
end
end
% in the fault mode, redundant switches need to be reconfigurated.
elseif operation_mode <= 7
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval(2, index_time) ...
+ total_dual(index_benders).delta_g(1, index_time) ...
* (delta_g_on(1, 1).' - total_sub(index_benders).delta_g(1, index_time).') ...
+ total_dual(index_benders).delta_g(2, index_time) ...
* (delta_g_on(2, 1).' - total_sub(index_benders).delta_g(2, index_time).') ...
+ total_dual(index_benders).switch(1, index_time) ...
* (redundant_switch_on(1, 1).' - total_sub(index_benders).redundant_sw(1, index_time).')...
+ total_dual(index_benders).switch(2, index_time) ...
* (redundant_switch_on(2, 1).' - total_sub(index_benders).redundant_sw(2, index_time).')...
+ total_dual(index_benders).switch(3, index_time) ...
* (redundant_switch_on(3, 1).' - total_sub(index_benders).redundant_sw(3, index_time).')...
+ total_dual(index_benders).switch(4, index_time) ...
* (redundant_switch_on(4, 1).' - total_sub(index_benders).redundant_sw(4, index_time).');
end
elseif operation_mode <= 11
% benders cuts
for index_benders = 1:Max_benders_iteration
benders_cut >= total_sub(index_benders).sub_optval(2, index_time) ...
+ total_dual(index_benders).delta_g(1, index_time) ...
* (delta_g_on(1, 1).' - total_sub(index_benders).delta_g(1, index_time).') ...
+ total_dual(index_benders).delta_g(2, index_time) ...
* (delta_g_on(2, 1).' - total_sub(index_benders).delta_g(2, index_time).') ...
+ total_dual(index_benders).delta_g(3, index_time) ...
* (delta_g_on(3, 1).' - total_sub(index_benders).delta_g(3, index_time).');
end
end
switch accelerate_flag
case 1
case 2
% low bound of master problem
OPTIONS.G(1:OPTIONS.N_g, 3).' * delta_g_on(1:OPTIONS.N_g, 1) ...
+ benders_cut >= upper_of_lowerbound;
% speedup constraints: power range & lower bound
if operation_mode <=3 % normal mode
delta_g_on(1, 1)*OPTIONS.Pg_Max(1) + delta_g_on(2, 1)*OPTIONS.Pg_Max(2) ...
+ OPTIONS.Pb_Max >= OPTIONS.P_L_TIME_off(index_time) + Ppr_best_solution;
% + OPTIONS.Pb_Max >= OPTIONS.P_L_TIME_off(index_time) + total_P(Max_benders_iteration).Ppr(index_time);
delta_g_on(1, 1)*OPTIONS.Pg_Min(1) + delta_g_on(2, 1)*OPTIONS.Pg_Min(2) ...
+ OPTIONS.Pb_Min <= OPTIONS.P_total_vs(index_time) + 0; % Ppr
elseif operation_mode <= 7 % fault mode
if Max_benders_iteration >= 1
delta_g_on(1, 1)*OPTIONS.Pg_Max(1) + OPTIONS.Pb_Max ...
>= OPTIONS.island1_max(index_time) + Ppr_best_solution;
% >= OPTIONS.island1_max(index_time) + total_P(Max_benders_iteration).Ppr(index_time);
delta_g_on(1, 1)*OPTIONS.Pg_Min(1) + OPTIONS.Pb_Min <= OPTIONS.island1_min(index_time) + 0; % Ppr
delta_g_on(2, 1)*OPTIONS.Pg_Max(2) + OPTIONS.Pb_Max >= OPTIONS.island2_max(index_time);
delta_g_on(2, 1)*OPTIONS.Pg_Min(2) + OPTIONS.Pb_Min <= OPTIONS.island2_min(index_time) + 0; % Ppr
end
end
end
cvx_end
master_delta_g(1:OPTIONS.N_g, index_time) = delta_g_on(1:OPTIONS.N_g, 1);
master_redundant_switch(1:4, index_time) = redundant_switch_on(1:4, 1);
sub_optval_on = sub_optval_on + cvx_optval;
end
% the related description is given in the function of subproblem
if with_iteration_D == 0
master_optval = sub_optval_on;
elseif with_iteration_D == 1
master_optval = sub_optval_on + total_sub(Max_benders_iteration).sub_optval(2, OPTIONS.N_t);
end
if strcmp(cvx_status, 'Infeasible')
disp('Master-t Infeasible');
infeasible_flag = 5;
end
if strcmp(cvx_status, 'Failed')
disp('Master-t Failed');
infeasible_flag = 6;
end
% disp(master_delta_g);
end
|
github
|
uoguelph-mlrg/vlr-master
|
batchnii2mat.m
|
.m
|
vlr-master/utils/batchnii2mat.m
| 3,745 |
utf_8
|
8b7144b3a54803b964b03e7b897b0aef
|
% BATCHNII2MAT
% This function loads .nii and .nii.gz image files (from IMG/NII)
% and saves them to .mat files (in IMG/MAT/).
% This function is poorly written for one-time use.
function [] = batchnii2mat()
% warning('off','MATLAB:MKDIR:DirectoryExists');
for i = 1:129
fmt2mat(fmtdef,i);
end
warning('on','MATLAB:MKDIR:DirectoryExists');
function [fmt] = fmtdef()
oki = [1:75,109:129]; % images which were processed with VLR
fmt.Original .im .vol = @(i)basicload('FLAIR', i,'single');
fmt.Standardized.im .final = @(i)stdload( 'mni:FLAIR',i,'single');
fmt.Standardized.im .reg = @(i)basicload('mni:FLAIR',i,'single');
fmt.Standardized.im .tform = @(i)basicload('xform', i,'single');
fmt.Standardized.im .itform = @(i)basicload('ixform', i,'single');
fmt.BrainSeg .brain.seg = @(i)tformload('mni:brain',i,'single');
fmt.BrainSeg .brain.reg = @(i)basicload('mni:brain',i,'single');
fmt.wmlGT .wml .gt = @(i)basicload('mans', i,'single');
fmt.wmlGT .wml .gts = @(i)loadmultimans( i,'single');
fmt.wmlGT .wml .reg = @(i)basicload('mni:mans', i,'single');
fmt.wmlSeg .wml .prob = @(i)checkload('les', i,'single',oki);
fmt.wmlSeg .wml .seg = @(i)thrload( 'les', i,'single',oki);
function [setname,setdir,subjname] = setlut(setkey,setnum)
lut.h17 = '17wmhseg';
lut.m16 = '16msseg';
lut.m08 = '08msseg';
lut.cain = 'inhouse';
lut.i15 = '15isbi';
setname = lut.(setkey);
setdir = fullfile('D:','DATA','WML','MAT',setname);
subjname = [setname,'_FLAIR_',num2str(setnum,'%03.f')];
function [] = fmt2mat(fmt,i)
[~,setkey,setnum] = imglutname('FLAIR',129,i);
[~,setdir,subjname] = setlut(setkey,setnum);
fprintf('Working on: %s\n',subjname);
mkdir(setdir);
d = fields(fmt); % directories
for di = 1:numel(d)
% savedir
savedir = fullfile(setdir,d{di});
savemat = fullfile(savedir,subjname);
mkdir(savedir);
% image i/o
fprintf(' / %s\n',d{di});
s = fields(fmt.(d{di})); % structs
for si = 1:numel(s)
fprintf(' > %s\n',s{si});
f = fields(fmt.(d{di}).(s{si})); % fields
for fi = 1:numel(f)
imgfun = fmt.(d{di}).(s{si}).(f{fi});
fprintf(' . %s ',f{fi});
eval([s{si},'.',f{fi},' = imgfun(i);']); % pls forgive eval usage here <3
fprintf('\n');
end
end
save(savemat,s{:});
end
function [I] = loadimg(fname,class)
I = cast(readnii(fname),class);
function [I] = basicload(imgkey,i,class)
I = loadimg(imglutname(imgkey,129,i),class);
function [I] = checkload(imgkey,i,class,oki)
if any(i==oki)
I = basicload(imgkey,i,class);
else
I = [];
end
function [I] = thrload(imgkey,i,class,oki)
% datestamp: 2017-12-21, from: mni96-m3-r=0.5-e-default-loso.mat
lut( 1: 20) = 0.54990; % h17-1
lut( 21: 40) = 0.51982; % h17-2
lut( 41: 60) = 0.59590; % h17-3
lut( 61: 65) = 0.52344; % m16-1
lut( 66: 70) = 0.52461; % m16-2
lut( 71: 75) = 0.52617; % m16-3
lut( 76: 95) = nan; % m08
lut( 96:108) = nan; % cain
lut(109:129) = 0.53945; % i15
I = cast(checkload(imgkey,i,class,oki) > lut(i), class);
function [I] = tformload(imgkey,i,class)
I = mni2ptx(129,i,loadimg(imglutname(imgkey,129,i),class));
function [I] = loadmultimans(i,class)
[~,setkey,setnum] = imglutname('FLAIR',129,i);
switch setkey
case 'm16'
for m = 1:7
I{m} = loadimg(strrep(imgname('m16:mans7',setnum,0),'*',num2str(m)),class);
end
case 'i15'
for m = 1:2
I{m} = loadimg(imgname(['i15:mans',num2str(m)],setnum),class);
end
otherwise
I = {};
end
function [I] = stdload(imgkey,i,class)
% datestamp: 2017-12-21, from: mni96-m3-r=0.5-e-default-loso.mat
I = basicload(imgkey,i,class);
M = basicload('mni:brain',i,'single');
I = standardize(I,M,'m3',pmfdef('lskew'));
|
github
|
uoguelph-mlrg/vlr-master
|
tmpname.m
|
.m
|
vlr-master/utils/tmpname.m
| 508 |
utf_8
|
04ce6709ec40dd0a8efa9a3ad9c38b1a
|
% TMPNAME
% This function generates a string for a temporary file name using concatenated
% varargin arguments. Numbers are converted to '%03.f' format.
function [matname] = tmpname(sub,varargin)
droot = fullfile(pwd);
tmpdir = fullfile(droot,'data','tmp');
if ~exist(tmpdir,'dir')
mkdir(tmpdir);
end
tmpstr = fullfile(tmpdir,'*');
for v = 1:numel(varargin)
if isnumeric(varargin{v})
varargin{v} = num2str(varargin{v},'%03.f');
end
sub = [sub,varargin{v}];
end
matname = strrep(tmpstr,'*',sub);
|
github
|
uoguelph-mlrg/vlr-master
|
fileready.m
|
.m
|
vlr-master/utils/fileready.m
| 242 |
utf_8
|
4a7ebb0248b4384db642ae79f672a549
|
% FILEREADY
% Make sure file fname exists and has not been modified in last [delay] ms
function [ready] = fileready(fname,delay)
if nargin < 2, delay = 1000; end
f = dir(fname);
ready = ~isempty(f) && (1000*60*60*24*(now-f.datenum) > delay);
|
github
|
uoguelph-mlrg/vlr-master
|
matx.m
|
.m
|
vlr-master/utils/matx.m
| 920 |
utf_8
|
cf454e8c3f6050778eeb00362c55e9cd
|
% MATX
% This function spawns an external MATLAB instance to run in the background
% The code specified in codestr is executed by the spawn.
% Spawns close when complete, but this function does not wait for this.
% Arguments to spawsn *must* be passed via .mat file save/load.
function [cmdstr] = matx(codestr)
if nargin < 1, error('Must supply a string of code for evaluation.'); end
bdir = 'C:\Program Files\MATLAB\R2011a\bin';
codewrap = 'cd(''__bdir__''); startup; cd(''__cdir__''); __code__; exit;';
cmdstr = ['matlab -nodesktop -nodisplay -nosplash -minimize -r "',codewrap,'"'];
cmdstr = strrep(cmdstr,'__bdir__',bdir);
cmdstr = strrep(cmdstr,'__cdir__',pwd);
cmdstr = strrep(cmdstr,'__code__',codestr);
if nargout == 0 % hide output (nul), call cmd from matlab, dont wait for it
eval(['!',cmdstr,'> nul &']);
else % append newline and return the cmd as a string
cmdstr = ['start ',cmdstr];
end
|
github
|
uoguelph-mlrg/vlr-master
|
kfcvidx.m
|
.m
|
vlr-master/utils/mri/kfcvidx.m
| 1,763 |
utf_8
|
171feb325addae90a4ac2f60b6f4fd82
|
function [idx] = kfcvidx(h,dofig)
if nargin < 2
dofig = 0;
end
[idx,P] = kfcvexpected(h.scan.N);
if dofig
makefig(h,P,idx);
end
function [idx,P] = kfcvexpected(N)
% logical: used
for n = 1:numel(N)
used{n} = false(1,N(n));
end
NN = numel(N);
idx = cell(1,NN);
CN = cumsum([0,N]);
P = N'*N./sum(N);
PW = floor(P); % first pass: minimum whole numbers
PE = P-PW; % second pass: leftovers
% first pass
for f = 1:NN % folds
for s = 1:NN % scanners
% add the
[idx{f},used{s},Nf(f)] = addn(idx{f},used{s},CN(s),PW(f,s));
end
end
% second pass
[~,so] = sort(PE(:),'descend');
for i = 1:NN^2
% try to add biggest gap in probability from scanner s to fold f
[f,s] = ind2sub([NN,NN],so(i));
if Nf(f) ~= N(f) % if this fold is not complete
[idx{f},used{s},Nf(f)] = addn(idx{f},used{s},CN(s),1); % add
end
end
function [idxf,useds,nf] = addn(idxf,useds,c,n)
if n
toadd = find(~useds,n,'first');
useds(toadd) = true;
idxf = [idxf,toadd+c];
end
nf = numel(idxf);
function [] = makefig(h,P,idx)
% compute the number of images from each scanner in each fold
CN = cumsum([0,h.scan.N]);
NN = numel(h.scan.N);
Xi = nan(3*NN,NN);
Xp = nan(3*NN,NN);
for f = 1:NN
Xi(3*f-1,:) = arrayfun(@(i)sum(idx{i}>CN(f) & idx{i}<=CN(f+1)),1:NN);
end
Xp(1:3:3*f,:) = P;
% plot the results:
hold on;
bar(Xi,'stacked');
b = bar(Xp,'stacked');
for s = 1:NN
b(s).FaceColor = lighten(h.scan.clr(s,:),0.5);
end
set(gca,'xtick',3*(1:NN)-1.5,'xticklabel',[1:NN],'xlim',[0,3*NN]);
figresize(gcf,[1000,500]);
legend(h.scan.names,'location','bestoutside');
tightsubs(1,1,gca,0.05*[2,3,6,1]);
xlabel('Fold','interpreter','latex');
ylabel('Scanner Composition','interpreter','latex');
print(gcf,thesisname('fig','bar-kfcv.eps'),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
scanparams.m
|
.m
|
vlr-master/utils/mri/scanparams.m
| 1,525 |
utf_8
|
a870dcb77cad24d6142656f56a0d0077
|
% SCANPARAMS
% Returns for a scanner index \in [1,10]:
% the name, imgname slug, number of images, voxel size,
% FLAIR scan paramters, and the simulated graylevels: GM, WM, CSF, WMH
function [name,short,N,x,tERI,Y4] = scanparams(i)
switch i
case 1, name = 'WMH 2017 (1)'; short = 'h17'; N = 20; x = [0.96,0.96,3.00]; tERI = [125,11000,2800];
case 2, name = 'WMH 2017 (2)'; short = 'h17'; N = 20; x = [1.00 1.00,3.00]; tERI = [ 82, 9000,2500];
case 3, name = 'WMH 2017 (3)'; short = 'h17'; N = 20; x = [0.98,1.20,3.00]; tERI = [126, 8000,2340];
case 4, name = 'MS 2016 (1)'; short = 'm16'; N = 05; x = [0.50,1.10,0.50]; tERI = [360, 5400,1800];
case 5, name = 'MS 2016 (2)'; short = 'm16'; N = 05; x = [1.04,1.25,1.04]; tERI = [336, 5400,1800];
case 6, name = 'MS 2016 (3)'; short = 'm16'; N = 05; x = [0.74,0.70,0.74]; tERI = [399, 5000,1800];
case 7, name = 'MS 2008 CHB'; short = 'm08'; N = 10; x = [0.50,0.50,0.50]; tERI = [ 0, 0, 0];
case 8, name = 'MS 2008 UNC'; short = 'm08'; N = 10; x = [0.50,0.50,0.50]; tERI = [125, 9000,2800];
case 9, name = 'ISBI MS 2015'; short = 'i15'; N = 21; x = [1.00,1.00,1.00]; tERI = [ 68, 9000,2800];
case 10, name = 'In-House'; short = 'cain'; N = 13; x = [0.43,0.43,3.00]; tERI = [125, 9000,2800];
case 11, name = 'T1 e.g.'; short = ''; N = 0; x = [1.00,1.00,1.00]; tERI = [ 5, 15, nan];
case 12, name = 'T2 e.g.'; short = ''; N = 0; x = [1.00,1.00,1.00]; tERI = [100, 5500, nan];
end
Y4 = flairy(tERI);
|
github
|
uoguelph-mlrg/vlr-master
|
simflair.m
|
.m
|
vlr-master/utils/mri/simflair.m
| 1,884 |
utf_8
|
46ac5cb3b6b5b283c445986cf1cc00c0
|
function [flair,y,tpm] = simflair(TERI,norm,mri)
if nargin < 1
error('Must specify the TE/TR/TI in TERI.');
end
if nargin < 2
norm = 'wm';
end
if nargin < 3
mri = 'ir';
end
[tpm,M] = gettpm(3);
[y] = getintensities(TERI(1),TERI(2),TERI(3),mri);
flair = zeros(size(M));
for c = 1:size(tpm,4)
flair = flair + tpm(:,:,:,c).*y(c);
end
switch norm
case 0
case 'gm', flair = flair ./ y(1); y = y ./ y(1);
case 'wm', flair = flair ./ y(2); y = y ./ y(2);
case 'csf', flair = flair ./ y(3); y = y ./ y(3);
case 'les', flair = flair ./ y(4); y = y ./ y(4);
case 'max', flair = flair ./ max(y); y = y ./ max(y);
otherwise, error('Normalization type: %s not implemented.',norm);
end
if nargout == 0
volshow(flair);
end
function [tpm,M] = gettpm(les)
% need to clean this up __JK__
tpmname = 'D:\DATA\brainweb\GT\msles\phantom_1.0mm_msles*.nii';
%tpmname = 'D:\DATA\brainweb\TPM.nii';
maskname = 'D:\DATA\WML\mni\brain\MNI_1.0mm_brain_old.nii';
tpm = imrotate(im2double(readnii(strrep(tpmname,'*',num2str(les)))),180);
M = ones(size(tpm(:,:,:,1)));
%M = imrotate(im2double(readnii(maskname)),180);
tpm = tpm(:,:,:,[1,2,3,end]);
%tpm = tpm(:,:,:,[1,2,3]);
tpm = bsxfun(@rdivide,tpm,sum(tpm,4).*M);
%Mi = padarray(M,[0,0,0,size(tpm,4)-1],'circular','post');
%tpm(~Mi | isnan(tpm)) = 0;
function [Y] = getintensities(TE,TR,TI,mri)
% tiss: GM, WM, CSF, les
T1 = [ 940, 550, 4210, 1300];
T2 = [ 100, 90, 2100, 150];
P = [ 0.75, 0.65, 1.00, 0.80];
switch mri
case 'ir'
% Fast Spin Echo
%Y = P.*(1 - 2.*exp(-TI./T1) + exp(-(TR-TE)./T1)).*exp(-TE./T2);
% Conventional Spin Echo
Y = P.*(1 - 2.*exp(-TI./T1) + exp(-(TR)./T1)).*exp(-TE./T2);
case 'se'
Y = P.*(1 - exp(-(TR)./T1)).*exp(-TE./T2);
end
Y = max(0, Y);
% references:
% Melhem1997 (all 4 tissues)
% % x GM, WM: Stanisz2005
% % x CSF: Condon1987
|
github
|
uoguelph-mlrg/vlr-master
|
imgname.m
|
.m
|
vlr-master/utils/mri/imgname/imgname.m
| 10,315 |
utf_8
|
808dc1b3cb36d4614cda7f224dbe04d3
|
% IMGNAME
% This function is a database of names of saved images. The arguments are:
% key -- format 'setkey:imgkey', where
% setkey -- one of: h17, m16, i15, m08, cain, mni
% corresponding to these different datasets (see comments below)
% note: mni is all the other images in MNI space
% where the subject number is from the order in lut-129.txt
% imgkey -- the type of image, e.g. FLAIR etc.
% num -- a number selecting the subject in the set
% docheck -- check to make sure the image exists (check .nii then .nii.gz)
function [iname] = imgname(key,num,docheck)
if nargin < 3, docheck = 1; end
iroot = fullfile('D:','DATA','WML');
spmdir = fullfile('spm','default');
[setkey,key] = strtok(key,':');
[imgkey, ~ ] = strtok(key,':');
switch setkey
% WMHSEG 17 ------------------------------------------------------------------
case 'h17', iroot = ff(iroot,'wmhseg17');
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR','h17_FLAIR_#');
case 'mans', iname = ff(iroot,'mans','h17_GTC_#');
case 'les', iname = ff(iroot,'les','h17_les_#');
case 'paper', iname = ff(iroot,'les','h17_paperles_#');
case 'base', iname = ff(iroot,'les','h17_baseles_#');
case 'lpa', iname = ff(iroot,'spm','lpa','les','ples_lpa_mh17_FLAIR_#');
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm','mh17_FLAIR_#');
case 'bias', iname = ff(iroot,spmdir,'bias', 'BiasField_h17_FLAIR_#');
case 'c1', iname = ff(iroot,spmdir,'tpm', 'c1h17_FLAIR_#');
case 'c2', iname = ff(iroot,spmdir,'tpm', 'c2h17_FLAIR_#');
case 'c3', iname = ff(iroot,spmdir,'tpm', 'c3h17_FLAIR_#');
case 'xform', iname = ff(iroot,spmdir,'xform', 'y_h17_FLAIR_#');
case 'ixform', iname = ff(iroot,spmdir,'xform', 'iy_h17_FLAIR_#');
case 'mni2ptx',iname = ff(iroot,spmdir,'diffeo','h17_mni2ptx_#');
case 'ptx2mni',iname = ff(iroot,spmdir,'diffeo','h17_ptx2mni_#');
case 'mat', iname = ff(iroot,spmdir,'mat', 'h17_FLAIR_#_seg8');
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
% MSSEG 16 -------------------------------------------------------------------
case 'm16', iroot = ff(iroot,'msseg16');
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR','m16_FLAIR_#');
case 'mans', iname = ff(iroot,'mans','m16_GTC_#');
case 'mans7', iname = ff(iroot,'mans','(7)','m16_GT_#_(*)');
case 'les', iname = ff(iroot,'les','m16_les_#');
case 'paper', iname = ff(iroot,'les','m16_paperles_#');
case 'base', iname = ff(iroot,'les','m16_baseles_#');
case 'lpa', iname = ff(iroot,'spm','lpa','les','ples_lpa_mm16_FLAIR_#');
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm','mm16_FLAIR_#');
case 'bias', iname = ff(iroot,spmdir,'bias','BiasField_m16_FLAIR_#');
case 'c1', iname = ff(iroot,spmdir,'tpm', 'c1m16_FLAIR_#');
case 'c2', iname = ff(iroot,spmdir,'tpm', 'c2m16_FLAIR_#');
case 'c3', iname = ff(iroot,spmdir,'tpm', 'c3m16_FLAIR_#');
case 'xform', iname = ff(iroot,spmdir,'xform','y_m16_FLAIR_#');
case 'ixform', iname = ff(iroot,spmdir,'xform','iy_m16_FLAIR_#');
case 'mni2ptx',iname = ff(iroot,spmdir,'diffeo','m16_mni2ptx_#');
case 'ptx2mni',iname = ff(iroot,spmdir,'diffeo','m16_ptx2mni_#');
case 'mat', iname = ff(iroot,spmdir,'mat', 'm16_FLAIR_#_seg8');
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
% ISBI 15 -------------------------------------------------------------------
case 'i15', iroot = ff(iroot,'isbi15');
if isnumeric(num)
Nt = [4,4,5,4,4]; ti = cell2mat(arrayfun(@(x)(1:x),Nt,'uniformout',0));
pnum = sum(num > cumsum(Nt)) + 1; num = ti(num);
stub = ['training',num2str(pnum,'%02.f'),'_#_*'];
end
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR',strrep(stub,'*','FLAIR_pp'));
case 'mans', iname = ff(iroot,'mans',strrep(stub,'*','mask_and'));
case 'mans1', iname = ff(iroot,'mans','(2)+',strrep(stub,'*','mask1'));
case 'mans2', iname = ff(iroot,'mans','(2)+',strrep(stub,'*','mask2'));
case 'mansand',iname = ff(iroot,'mans','(2)+',strrep(stub,'*','mask_and'));
case 'mansor', iname = ff(iroot,'mans','(2)+',strrep(stub,'*','mask_or'));
case 'les', iname = ff(iroot,'les',strrep(stub,'*','les'));
case 'paper', iname = ff(iroot,'les',strrep(stub,'*','paperles'));
case 'base', iname = ff(iroot,'les',strrep(stub,'*','baseles'));
case 'lpa', iname = ff(iroot,'spm','lpa','les',['ples_lpa_m',strrep(stub,'*','FLAIR_pp')]);
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm',['m',strrep(stub,'*','FLAIR_pp')]);
case 'bias', iname = ff(iroot,spmdir,'bias', ['BiasField_',strrep(stub,'*','FLAIR_pp')]);
case 'c1', iname = ff(iroot,spmdir,'tpm', ['c1',strrep(stub,'*','FLAIR_pp')]);
case 'c2', iname = ff(iroot,spmdir,'tpm', ['c2',strrep(stub,'*','FLAIR_pp')]);
case 'c3', iname = ff(iroot,spmdir,'tpm', ['c3',strrep(stub,'*','FLAIR_pp')]);
case 'xform', iname = ff(iroot,spmdir,'xform', ['y_',strrep(stub,'*','FLAIR_pp')]);
case 'ixform', iname = ff(iroot,spmdir,'xform', ['iy_',strrep(stub,'*','FLAIR_pp')]);
case 'mni2ptx',iname = ff(iroot,spmdir,'diffeo',[strrep(stub,'*','mni2ptx')]);
case 'ptx2mni',iname = ff(iroot,spmdir,'diffeo',[strrep(stub,'*','ptx2mni')]);
case 'mat', iname = ff(iroot,spmdir,'mat', [strrep(stub,'*','FLAIR_pp'),'_seg8']);
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
% MSSEG 08 -------------------------------------------------------------------
case 'm08', iroot = ff(iroot,'msseg08');
if isnumeric(num)
if num <= 10, stub = 'CHB_train_Case#_*'; num = num;
elseif num >= 11, stub = 'UNC_train_Case#_*'; num = num-10;
end
else
stub = 'CHB_train_Case#_*';
stub = 'UNC_train_Case#_*';
end
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR',strrep(stub,'*','FLAIR'));
case 'mans', iname = ff(iroot,'mans','segmentations',strrep(stub,'*','lesion_(1)')); % revisions
case 'mano', iname = ff(iroot,'mans','original',strrep(stub,'*','lesion')); % originals
case 'les', iname = ff(iroot,'les',strrep(stub,'*','les'));
case 'lpa', iname = ff(iroot,'spm','lpa','les',['ples_lpa_m',strrep(stub,'*','FLAIR')]);
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm',['m',strrep(stub,'*','FLAIR')]);
case 'bias', iname = ff(iroot,spmdir,'bias', ['BiasField_',strrep(stub,'*','FLAIR')]);
case 'c1', iname = ff(iroot,spmdir,'tpm', ['c1',strrep(stub,'*','FLAIR')]);
case 'c2', iname = ff(iroot,spmdir,'tpm', ['c2',strrep(stub,'*','FLAIR')]);
case 'c3', iname = ff(iroot,spmdir,'tpm', ['c3',strrep(stub,'*','FLAIR')]);
case 'xform', iname = ff(iroot,spmdir,'xform', ['y_',strrep(stub,'*','FLAIR')]);
case 'ixform', iname = ff(iroot,spmdir,'xform', ['iy_',strrep(stub,'*','FLAIR')]);
case 'mni2ptx',iname = ff(iroot,spmdir,'diffeo',[strrep(stub,'*','mni2ptx')]);
case 'ptx2mni',iname = ff(iroot,spmdir,'diffeo',[strrep(stub,'*','ptx2mni')]);
case 'mat', iname = ff(iroot,spmdir,'mat', [strrep(stub,'*','FLAIR'),'_seg8']);
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
% CAIN -----------------------------------------------------------------------
case 'cain', iroot = ff(iroot,'cain');
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR','CAIN_FLAIR_#');
case 'mans', iname = ff(iroot,'mans','CAIN_GT_#');
case 'les', iname = ff(iroot,'les','CAIN_les_#');
case 'paper', iname = ff(iroot,'les','CAIN_paperles_#');
case 'lpa', iname = ff(iroot,'spm','lpa','les','ples_lpa_mCAIN_FLAIR_#');
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm','mCAIN_FLAIR_#');
case 'bias', iname = ff(iroot,spmdir,'bias','BiasField_CAIN_FLAIR_#');
case 'c1', iname = ff(iroot,spmdir,'tpm', 'c1CAIN_FLAIR_#');
case 'c2', iname = ff(iroot,spmdir,'tpm', 'c2CAIN_FLAIR_#');
case 'c3', iname = ff(iroot,spmdir,'tpm', 'c3CAIN_FLAIR_#');
case 'xform', iname = ff(iroot,spmdir,'xform','y_CAIN_FLAIR_#');
case 'ixform', iname = ff(iroot,spmdir,'xform','iy_CAIN_FLAIR_#');
case 'mni2ptx',iname = ff(iroot,spmdir,'diffeo','CAIN_mni2ptx_#');
case 'ptx2mni',iname = ff(iroot,spmdir,'diffeo','CAIN_ptx2mni_#');
case 'mat', iname = ff(iroot,spmdir,'mat', 'CAIN_FLAIR_#_seg8');
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
% MNI ------------------------------------------------------------------------
case 'mni', iroot = ff(iroot,'mni');
switch imgkey
case 'FLAIR', iname = ff(iroot,'FLAIR','mni_FLAIR_#');
case 'mans', iname = ff(iroot,'mans','mni_GT_#');
case 'FLAIRm', iname = ff(iroot,spmdir,'FLAIRm','mni_FLAIRm_#');
case 'bias', iname = ff(iroot,spmdir,'bias','mni_bias_#');
case 'c1', iname = ff(iroot,spmdir,'tpm', 'mni_c1_#');
case 'c2', iname = ff(iroot,spmdir,'tpm', 'mni_c2_#');
case 'c3', iname = ff(iroot,spmdir,'tpm', 'mni_c3_#');
case 'brainx', iname = ff(iroot,'brain','MNI_1.5mm_brain'); % (v4)
case 'brain', iname = ff(iroot,'brain','MNI_brain');
case 'tpm', iname = ff(iroot,'spm','TPM');
case 'root', iname = iroot;
otherwise error('Image key not found.');
end
otherwise error('Set key not found.');
end
% sub the specific number
if isnumeric(num), num = num2str(num,'%02.f'); else, docheck = 0; end
iname = strrep(iname,'#',num);
% make sure it exists (maybe)
if any(strcmp(imgkey,{'mat','mni2ptx','ptx2mni'}))
iname = [iname,'.mat'];
elseif docheck
if exist([iname,'.nii'],'file')
iname = [iname,'.nii'];
return
elseif exist([iname,'.nii.gz'],'file')
iname = [iname,'.nii.gz'];
return
else
error(['Cannot find: ',iname,'.nii(.gz)']);
end
else
iname = [iname,'.nii'];
return
end
function [out] = ff(varargin)
out = fullfile(varargin{:});
|
github
|
uoguelph-mlrg/vlr-master
|
imglutname.m
|
.m
|
vlr-master/utils/mri/imgname/imglutname.m
| 967 |
utf_8
|
9689164e6026aa43961081e257290e5a
|
% IMGLUTNAME
% This function is a wrapper for imgname,
% where the index of an image in a multi-source set can be used
% instead of the image index from its original set
% e.g. 1:96 instead of 1:20, 1:20, 1:20, 1:5, 1:5, 1:5, 1:21
% The specific multi-source set must be indexed in a lut-#.txt file (# = h.Ni)
function [name,setkey,setnum] = imglutname(imgkey,N,n,varargin)
lut = getlut(N);
[setkey,setnum] = strtok(lut{n},':');
setnum = str2double(setnum(2:end));
% usual lookup for any given dataset
if isempty(strfind(imgkey,'mni:'))
name = imgname([setkey,':',imgkey],setnum,varargin{:});
% special mni lookup
% since need to use both the current lut-index and the master lut-129.txt
else
lutall = getlut(129);
n = find(strcmp(lutall,lut{n}));
name = imgname(imgkey,n,varargin{:});
end
function [lut] = getlut(N)
% n.b. relative path
fid = fopen(['.\utils\mri\imgname\lut\lut-',num2str(N),'.txt']);
lut = textscan(fid,'%s',N);
lut = lut{1};
fclose(fid);
|
github
|
uoguelph-mlrg/vlr-master
|
tightsubs.m
|
.m
|
vlr-master/utils/fig/tightsubs.m
| 1,162 |
utf_8
|
a06d300b27ee6d3e4dd3ec268f800a3a
|
% TIGHTSUBS is a function for flexible fine tune control over subplot spacing.
%
% Inputs:
% nx, ny - the number of plots in x and y directions, respectively.
%
% ax - handles to existing subplots for spacing.
%
% pad - the padding around each axis relative to the total figure size.
% (3 options by argument size):
% 1. Scalar - same amount to all axes, all sides
% 2. 4 Vector - same amount to all axes: [left bottom right top]
% 3. Nx4 Matrix - different amout for each of N axes, same order
%
% Jesse Knight 2016
function [] = tightsubs(nx,ny,ax,pad)
% option 1.: ensure we get a 4-vector
if isscalar(pad)
pad = pad*ones(1,4);
end
% option 2.: ensure we get Nx4 matrix
if isvector(pad)
pad = ones(nx*ny,1)*pad;
end
% option 3.: apply the padding
for i = 1:numel(ax)
[x,y] = ind2sub([nx, ny], i);
set(ax(i),'position',[((x - 1) / nx) + pad(i,1), ...
(1 - (y / ny)) + pad(i,2), ...
(1 / nx) - (pad(i,1) + pad(i,3)), ...
(1 / ny) - (pad(i,2) + pad(i,4))]);
end
|
github
|
uoguelph-mlrg/vlr-master
|
vcolorbar.m
|
.m
|
vlr-master/utils/fig/color/vcolorbar.m
| 463 |
utf_8
|
a3c4ec50886f45840ea12ba5c5d2d9c5
|
% VCOLORBAR
% Create a vertical colorbar size [80,600]
% with ticks specified, and colormap cmap
function [ax] = vcolorbar(ctick,cmap)
N = size(cmap,1);
C = linspace(1,N,N);
figure;
imagesc(imrotate(cat(3,cmap(C,1)',cmap(C,2)',cmap(C,3)'),90));
ax = gca;
ctick = rot90(ctick);
set(ax,'xtick',[],'fontsize',22,...
'ytick',linspace(1,N,numel(ctick)),'yticklabel',ctick,'YAxisLocation','right');
tightsubs(1,1,ax,[0.05, 0.05, 0.7, 0.05])
figresize(gcf,[80,600]);
|
github
|
uoguelph-mlrg/vlr-master
|
hcolorbar.m
|
.m
|
vlr-master/utils/fig/color/hcolorbar.m
| 399 |
utf_8
|
fac2291f93788e40c3873f921182e695
|
% HCOLORBAR
% Create a horizontal colorbar size [600,80]
% with ticks specified, and colormap cmap
function [ax] = hcolorbar(ctick,cmap)
N = size(cmap,1);
C = linspace(1,N,N);
figure;
imagesc(cat(3,cmap(C,1)',cmap(C,2)',cmap(C,3)'));
ax = gca;
set(ax,'ytick',[],'xtick',linspace(1,N,numel(ctick)),'xticklabel',ctick,'fontsize',30);
tightsubs(1,1,ax,[0.05, 0.5, 0.05, 0.0])
figresize(gcf,[600,80]);
|
github
|
uoguelph-mlrg/vlr-master
|
monomap.m
|
.m
|
vlr-master/utils/fig/color/colormaps/monomap.m
| 557 |
utf_8
|
dbcf6216bb35f8acd9eb37bebbf3f15c
|
% MONOMAP
% creates a colormap using the colour clr as a base
% clr - base colour
% m - number of levels
% mm - 2 element specifying darken/lighten levels as the limits:
% negatives: darken by factor |mm(i)|
% positives: lighten by factor |mm(i)|
function [cmap] = monomap(clr,m,mm)
if nargin < 2, m = size(get(gcf,'colormap'),1); end
if nargin < 3, mm = [-0.5,0.5]; end
f = linspace(mm(1),mm(2),m);
cmap = [];
for i = 1:m
if f(i) <= 0
cmap = [cmap;darken(clr,abs(f(i)))];
else
cmap = [cmap;lighten(clr,abs(f(i)))];
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
darken.m
|
.m
|
vlr-master/utils/fig/color/colormaps/darken.m
| 96 |
utf_8
|
02241be065df39bb8cb5af8cbf8fef36
|
% DARKEN
% darken the clr by factor f \in [0,1]
function [clr] = darken(clr,f)
clr = clr.*(1-f);
|
github
|
uoguelph-mlrg/vlr-master
|
lighten.m
|
.m
|
vlr-master/utils/fig/color/colormaps/lighten.m
| 107 |
utf_8
|
f4f1d723fe4037627413d3a2dabbacc5
|
% LIGHTEN
% lighten the clr by factor f \in [0,1]
function [clr] = lighten(clr,f)
clr = 1-((1-clr).*(1-f));
|
github
|
uoguelph-mlrg/vlr-master
|
timshow.m
|
.m
|
vlr-master/utils/fig/show/timshow.m
| 6,124 |
utf_8
|
78307c95d0bff35be7bfaecebbdbb4dd
|
% TIMSHOW is a flexible function for displaying multiple images tightly on the
% same figure. Padding between images, grid dimensions, contrast scale,
% and colourmaps can be specified. Attributes apply to all images. Best
% results with same sized images. Grayscale or colour images.
%
% Input: (any order, all optional except at least one image)
% image(s) - any number of 2D grayscale or colour images. Rendered in the
% order they are presented, top to bottom, left to right.
% * The x-dimension of any image should not have a size of 3,
% else it will be confused for a colourmap.
%
% minmax - minmax specification for contrast scaling, as in imshow(I,[]).
% array of size: 1 by 2, or a empty array: []. Applies to all
% images equally.
% Default: [] (image-adaptive)
%
% colourmap - colourmap used for displaying images:
% array of size: M by 3 or a colourmap function
% Default: curent default figure colormap
%
% padval - decimal value on the interval (0, 0.5) dictating the padded
% spacing between images (relative to figure size).
% Default: 0.005 (0.5%)
%
% gridstr - string like "5x2", specifying the number of images to tile
% horizontally (5) and vertically (2)
% Default: square as possible based on num. images, wider bias
%
% maxwid - string like "w800", specifying the maximum width of the figure
% (overrides maxht).
% Default: 0.9*screenwidth
%
% maxht - string like "h300", specifying the maximum height of the figure
% (overrides maxwid).
% Default: 0.9*screenheight
%
% * if 2+ non-image arguments are given, only the last one is used.
%
% Output arguments:
% axes - handles to all subplot axes.
% * only returned on nargout == 1
%
% Examples:
%
% timshow(randn(10,10));
% Show a random 10x10 image of data with the default figure
% colourmap, automatic contrast scaling, with 0.5% of total
% figure size padded around.
%
% timshow(I1, I2, I3, I4, hot, 0, [0,1], '4x1');
% Show images I1, I2, I3, I4 using the hot colourmap, with no
% space between, contrast from 0 to 1, and in a horizontal line.
%
% Jesse Knight 2016
function [varargout] = timshow(varargin)
[data] = parseargs(varargin);
[data] = initaxes(data);
[data] = showims(data);
if nargout == 1
varargout{1} = data.ax;
end
function [data] = parseargs(vargs)
screensize = get(0,'screensize');
% default values
data.img = [];
data.minmax = [];
data.colourmap = get(0,'defaultfigurecolormap');
data.pad = 0.005;
data.maxwid = 0.9*screensize(3);
data.maxht = 0.9*screensize(4);
% handle input arguments based on dimensions / attributes
for v = 1:numel(vargs)
sizev = size(vargs{v});
% padval
if (numel(sizev) == 2) && (all(sizev == [1,1])) && (vargs{v} < 0.5)
data.pad = vargs{v};
% gridstr
elseif ischar(vargs{v}) && numel(sscanf(vargs{v},'%dx%d')) == 2
xy = sscanf(vargs{v},'%dx%d');
data.nSubx = xy(1);
data.nSuby = xy(2);
% maxwid
elseif ischar(vargs{v}) && numel(sscanf(vargs{v},'w%d')) == 1
data.maxwid = sscanf(vargs{v},'w%d');
data.maxht = inf;
% maxht
elseif ischar(vargs{v}) && numel(sscanf(vargs{v},'h%d')) == 1
data.maxht = sscanf(vargs{v},'h%d');
data.maxwid = inf;
% colourmap
elseif sizev(2) == 3
data.colourmap = vargs{v};
% minmax (numerical)
elseif (numel(sizev) == 2) && (all(sizev == [1,2]))
data.minmax = vargs{v};
% minmax ([])
elseif sizev(1) == 0
data.minmax = [];
% image
elseif (numel(sizev) == 2) || (numel(sizev) == 3 && sizev(3) == 3)
data.img(end+1).data = vargs{v};
data.img(end).size = size(data.img(end).data);
% argument not recognized: ignoring
else
warning(['Ignoring argument number ',num2str(v),'.']);
end
end
assert(size(data.img,1) ~= 0,'Must give at least one image.');
function [data] = initaxes(data)
% optimize display grid square-ish if not user specified
data.N = numel(data.img);
if ~all(isfield(data,{'nSubx','nSuby'}))
if data.N ~= 3
data.nSubx = ceil(sqrt(data.N));
data.nSuby = ceil(data.N/data.nSubx);
else % special case for 3: horizontal line - less awkward
data.nSubx = 3;
data.nSuby = 1;
end
end
% subplot handles initialization
for a = 1:data.N
data.ax(a) = subplot(data.nSuby,data.nSubx,a);
end
% optimize figure display size for the current monitor and first image size
% centres the figure in onscreen too.
screensize = get(0,'screensize');
aspect = (size(data.img(1).data,1) / size(data.img(1).data,2));
imgSize = min( data.maxwid / data.nSubx, data.maxht / data.nSuby / aspect);
figSize = ...
[(screensize(3) - ( imgSize*data.nSubx))/2,... % Lower-left corner X
(screensize(4) - (aspect*imgSize*data.nSuby))/2,... % Lower-left corner Y
(imgSize*data.nSubx),... % Width in X
(imgSize*data.nSuby*aspect)]; % Width in Y
set(gcf,'color','k','position',figSize);
function [data] = showims(data)
% show the images in default subplot locations
for i = 1:data.N
imshow(data.img(i).data,data.minmax,...
'parent',data.ax(i),'initialmagnification','fit');
end
% subplot spacing (separate loop since otherwise axes die if they overlap)
for i = 1:data.N
y = ceil(i / data.nSubx);
x = mod(i, data.nSubx);
x(~x) = data.nSubx;
set(data.ax(i),'position',[(x - 1) / data.nSubx + 0.5*data.pad, ...
1 - (y / data.nSuby - 0.5*data.pad), ...
1 / data.nSubx - data.pad, ...
1 / data.nSuby - data.pad]);
colormap(data.ax(i),data.colourmap); % R2017+
end
colormap(data.colourmap); % R0:R2016
|
github
|
uoguelph-mlrg/vlr-master
|
sliceshow.m
|
.m
|
vlr-master/utils/fig/show/sliceshow.m
| 465 |
utf_8
|
2eab54a16244c2d7bcaf767f469d4ece
|
% SLICESHOW
% Show slices of a volume I at the indices z
% using timshow, with varargin{:} passed directly to timshow
function [ax] = sliceshow(I,z,varargin)
N = numel(z);
mm = [min(I(:)),max(I(:))];
for i = 1:N
S{i} = squeeze(I(:,:,z(i),:));
end
numstr = num2str(N,'%dx1');
ax = timshow(S{:},numstr,mm,varargin{:});
for i = 1:N
text(0.05,0.95,num2str(z(i),'%02.f'),...
'color','w','parent',ax(i),'units','normalized');
end
set(gcf,'inverthardcopy','off');
|
github
|
uoguelph-mlrg/vlr-master
|
volshow.m
|
.m
|
vlr-master/utils/fig/show/volshow.m
| 13,242 |
utf_8
|
1d25d4374727aece1ef4a5b1862e4a3e
|
% VOLSHOW is a flexible tool for displaying multiple image volumes quickly
% on the same figure. Mouse scroll wheel scrolls the z (3rd) dimension.
% Padding between images, grid dimensions, contrast scale, and
% colourmaps can be specified. Attributes apply to all images. Best
% results with same sized volumes. Grayscale or colour (4rd dimension)
% images. A user-supplied 'click' function can also be supplied,
% to plot some near-click data on an extra axes (e.g. local histogram).
%
% Inputs: (any order, all optional except at least one image)
% images(s) - any number of 3D grayscale or colour images. Rendered in the
% order they are presented, top to bottom, left to right.
% * The x-dimension of any image should not have a size of 3,
% else it will be confused for a colourmap.
% * if using colour volumes, the colour channels should be the
% last (4th) dimension.
%
% minmax - minmax specification for contrast scaling, as in imshow(I,[]).
% array of size: 1 by 2, or a empty array: []. Applies to all
% images equally.
% Default: [] (image-adaptive)
%
% colourmap - colourmap used for displaying images:
% array of size: M by 3 or a colourmap function
% Default: curent default figure colormap
%
% padval - decimal value on the interval (0, 0.5) dictating the padded
% spacing between images (relative to figure size).
% Default: 0.005 (0.5%)
%
% gridstr - string like "5x2", specifying the number of images to tile
% horizontally (5) and vertically (2)
% Default: square as possible based on num. images, wider bias
%
% maxwid - string like "w800", specifying the maximum width of the figure
% (overrides maxht).
% Default: 0.9*screenwidth
%
% maxht - string like "h300", specifying the maximum height of the figure
% (overrides maxwid).
% Default: 0.9*screenheight
%
% patchfcn - user specified function which accepts some data and plots
% some result from it after a double click in any of the axes.
% Function should take the form:
% function [] = patchfcn(ax, minmax, patchdata)
% Inputs: ax - handle to the last unused axes
% minmax - cell array of minmax for all image axes.
% patchdata - cell array of image data corresponding
% to the clicked patch (from all axes).
% patchdata, mimax orders: {clicked axes, all others}.
% Outputs: None required, but presumably plotting on the axes.
% Default: None
%
% patchsize - size of the patch data passed to patchfcn (size: 1 by 3)
% Default: [15, 15, 1]
%
% * if 2+ non-image arguments are given, only the last one is used.
%
% Examples:
%
% >> volshow(randn(10,10,10));
% Show a random 10x10x10 volume of data with the default figure colourmap,
% automatic contrast scaling, with 0.5% of total figure size padded around.
%
% >> volshow(I1, I2, I3, I4, hot, 0, [0,1], '4x1');
% Show volumes I1, I2, I3, I4 using the hot colourmap, with no space between
% contrast from 0 to 1, and in a horizontal line.
%
% Jesse Knight 2016
function varargout = volshow(varargin)
% -- do not edit: MATLAB GUIDE
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @volshow_OpeningFcn, ...
'gui_OutputFcn', @volshow_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end % -- end do not edit
% --- Executes just before volshow is made visible.
function volshow_OpeningFcn(hObject, ~, handles, varargin)
handles.output = hObject;
handles.badcall = 0;
set(0,'defaultTextFontName','Courier New');
try % if any errors: abort and give error (to ensure GUI closes)
screensize = get(0,'screensize');
% default values
handles.img = [];
handles.minmax = [];
handles.patchfcn = [];
handles.patchsize = [15,15,1];
handles.colourmap = get(0,'defaultfigurecolormap');
handles.pad = 0.005;
handles.maxwid = 0.9*screensize(3);
handles.maxht = 0.9*screensize(4);
% handle input arguments based on their dimensions
for v = 1:numel(varargin)
sizev = size(varargin{v});
% image volume (possibly including colour in 3rd dimension)
if numel(sizev) >= 3
if islogical(varargin{v}), varargin{v} = single(varargin{v}); end
handles.img(end+1).data = varargin{v};
handles.img(end).size = size(handles.img(end).data);
handles.img(end).frame = round(handles.img(end).size(3)*0.5);
handles.img(end).textpos = [round(handles.img(end).size(1)/20 + 1),...
round(handles.img(end).size(2)/20 + 1)];
% grid specification string
elseif ischar(varargin{v}) && numel(sscanf(varargin{v},'%dx%d')) == 2
xy = sscanf(varargin{v},'%dx%d');
handles.nSubx = xy(1);
handles.nSuby = xy(2);
% maxwid
elseif ischar(varargin{v}) && numel(sscanf(varargin{v},'w%d')) == 1
handles.maxwid = sscanf(varargin{v},'w%d');
handles.maxht = inf;
% maxht
elseif ischar(varargin{v}) && numel(sscanf(varargin{v},'h%d')) == 1
handles.maxht = sscanf(varargin{v},'h%d');
handles.maxwid = inf;
% click function
elseif isa(varargin{v},'function_handle')
handles.patchfcn = varargin{v};
% patch size for the click
elseif all(sizev == [1,3]) || all(sizev == [3,1])
handles.patchsize = varargin{v};
% minmax (numerical)
elseif all(sizev == [1,2]) || all(sizev == [2,1])
handles.minmax = varargin{v};
% pad value
elseif all(sizev == [1,1])
handles.pad = varargin{v};
% minmax ([])
elseif sizev(1) == 0
handles.minmax = [];
% colourmap
elseif sizev(2) == 3
handles.colourmap = varargin{v};
% argument not recognized: ignoring
else
warning(['Ignoring argument number ',num2str(v),'.']);
end
end
% quick error check: need an image volume to proceed
assert(size(handles.img,1) ~= 0,'Must give at least one 3D image volume.');
% optimize display grid square-ish if not user specified
handles.N = numel(handles.img) + ~isempty(handles.patchfcn);
if ~all(isfield(handles,{'nSubx','nSuby'}))
if handles.N ~= 3
handles.nSubx = ceil(sqrt(handles.N));
handles.nSuby = ceil(handles.N/handles.nSubx);
else % special case for 3: horizontal line - less awkward
handles.nSubx = 3;
handles.nSuby = 1;
end
end
% defining per-image minmaxs
for n = 1:numel(handles.img)
if isempty(handles.minmax)
handles.img(n).minmax = [min(handles.img(n).data(:)),...
max(handles.img(n).data(:))];
else
handles.img(n).minmax = handles.minmax;
end
end
% subplot handles initialization
for a = 1:numel(handles.img)
handles.ax(a) = subplot(handles.nSuby,handles.nSubx,a,...
'ButtonDownFcn',{@clickfcn,handles},...
'HitTest','off');%,'NextPlot','replacechildren');
end
if ~isempty(handles.patchfcn);
handles.ax(end+1) = subplot(handles.nSuby,handles.nSubx,handles.N,...
'xtick',[],'ytick',[]);
end
% subplot spacing (separate loop since otherwise axes die if they overlap)
for a = 1:handles.N
y = ceil(a / handles.nSubx);
x = mod(a, handles.nSubx);
x(~x) = handles.nSubx;
set(handles.ax(a),'position',[(x - 1) / handles.nSubx + 0.5*handles.pad, ...
1 - (y / handles.nSuby - 0.5*handles.pad), ...
1 / handles.nSubx - handles.pad, ...
1 / handles.nSuby - handles.pad]);
end
% optimize figure display size for the current monitor and first image size
% centres the figure in onscreen too.
screensize = get(0,'screensize');
aspect = (size(handles.img(1).data,1) / size(handles.img(1).data,2));
%imgSize = min(800, (0.9*screensize(3)) / handles.nSubx);
imgSize = min( handles.maxwid / handles.nSubx, ...
handles.maxht / handles.nSuby / aspect);
set(gcf,'color','k','position',...
[(screensize(3) - ( imgSize*handles.nSubx))/2,...
(screensize(4) - (aspect*imgSize*handles.nSuby))/2,...
(imgSize*handles.nSubx),...
(imgSize*handles.nSuby*aspect)]);
% render the middle frame of each volume to start
imupdate(handles);
% input argument parsing failed: exit (could be more graceful)
catch ME
error(ME.getReport);
handles.badcall = 1;
end
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line (none).
function varargout = volshow_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
if handles.badcall
figure1_CloseRequestFcn(hObject, eventdata, handles);
end
% --- Executes on scroll wheel click while the figure is in focus.
function volshow_WindowScrollWheelFcn(hObject, eventdata, handles)
% for all volumes
for i = 1:numel(handles.img)
% adjust the frame index by the scroll count
handles.img(i).frame = handles.img(i).frame + eventdata.VerticalScrollCount;
% wrap around if z is less than 1 or larger than img.size
if handles.img(i).frame > handles.img(i).size(3)
handles.img(i).frame = 1;
elseif handles.img(i).frame < 1
handles.img(i).frame = handles.img(i).size(3);
end
end
% update the frames onscreen
guidata(hObject, handles);
imupdate(handles);
% --- Called by other functions on WindowScrollWheelFcn movement.
function imupdate(handles)
% for all volumes
for i = 1:numel(handles.img)
% show the current frame
ha = imshow(squeeze(handles.img(i).data(:,:,handles.img(i).frame,:)),...
handles.img(i).minmax,'parent',handles.ax(i),'initialmagnification','fit');
set(ha,'ButtonDownFcn',{@clickfcn,handles});
% print the current frame number in the top left corner (red)
% comment this out if you want
text(handles.img(i).textpos(2),handles.img(i).textpos(1),...
num2str(handles.img(i).frame),'color','r','parent',handles.ax(i));
colormap(handles.ax(i),handles.colourmap); % R2017+
end
colormap(handles.colourmap); % R0:R2016
% --- Executes on any button click function within axes.
function clickfcn(hObject, ~, handles)
% need to do anything? (user supplied click function)
if isempty(handles.patchfcn)
return
end
% yes ...
% determine calling axes
for i = 1:numel(handles.img)
if get(hObject,'Parent') == handles.ax(i)
img = handles.img(i);
end
end
% request the second click now that we know the calling axes
% goes smoothly on double click
[x,y] = ginput(1);
z = img.frame;
% get the local patch coordinates and show the user the patch
isize = img.size;
yy = floor(max(1, y - handles.patchsize(1)/2)) : ...
floor(min(isize(1), y + handles.patchsize(1)/2));
xx = floor(max(1, x - handles.patchsize(2)/2)) : ...
floor(min(isize(2), x + handles.patchsize(2)/2));
zz = floor(max(1, z - handles.patchsize(3)/2)) : ...
floor(min(isize(3), z + handles.patchsize(3)/2));
minmaxes{1} = highlightpatch(hObject,yy,xx,img.minmax);
drawnow;
% gather the patch data (might be 3D)
patches{1} = img.data(yy,xx,zz,:);
for i = 1:numel(handles.img)
if get(hObject,'Parent') ~= handles.ax(i)
patches{end+1} = handles.img(i).data(yy,xx,zz,:);
minmaxes{end+1} = handles.img(i).minmax;
end
end
% try calling the user-specified function
try
handles.patchfcn(handles.ax(end), minmaxes, patches);
catch ME % you done goofed
error(ME.getReport);
end
% restore the images without patch highlighting
imupdate(handles);
% --- called by clickfcn to show the user where they've clicked
function [minmax] = highlightpatch(ax,yy,xx,minmax)
% get the frame data
I2 = get(ax,'CData');
% determine minmax if it isn't defined
if isempty(minmax)
minmax = [min(I2(:)),max(I2(:))];
end
% paint the whole box bright
I2o = I2(yy(2:end-1),xx(2:end-1),:);
I2(yy,xx,:) = minmax(2);
% paint an inner box dark
%I2(yy(2:end-1),xx(2:end-1),:) = minmax(1);
I2(yy(2:end-1),xx(2:end-1),:) = I2o;
% refresh the frame data
set(ax,'CData',I2);
% --- Executes when user attempts to close volshow.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
delete(hObject);
|
github
|
uoguelph-mlrg/vlr-master
|
im2rgb.m
|
.m
|
vlr-master/utils/fig/show/im2rgb.m
| 477 |
utf_8
|
9d49418d48b6c13033964d67802561d8
|
% IM2RGB
% This function converts an image (2D or 3D) from grayscale to color using the
% specified colormap.
% Dependencies: biny
function [RGB] = im2rgb(I,map,varargin)
% get the size of the colormap
M = size(map,1);
% bin the image data
if isempty(varargin), varargin{1} = []; end
IU = biny(I,varargin{:},[1,M],M);
% parse the RGB channels
RGB(:,1) = map(IU,1);
RGB(:,2) = map(IU,2);
RGB(:,3) = map(IU,3);
% reshape to the appropriate size
RGB = reshape(RGB,[size(I),3]);
|
github
|
uoguelph-mlrg/vlr-master
|
boxplotn.m
|
.m
|
vlr-master/utils/fig/plot/boxplotn.m
| 746 |
utf_8
|
2c7b93ad6a0c8cbe8cfc4c01f03903af
|
% BOXPLOTN
% Box plot with coloured grouping.
% X is a cell array. size: [bins, groups]
% cmap must have size [groups,3]
% blabs must be a cell array of bins labels
function boxplotn(X0,cmap,blabs,varargin)
NB = size(X0,1);
NC = size(X0,2);
X = []; G = []; C = [];
for b = 1:NB
for c = 1:NC
Xi = X0{b,c}(:);
X = [X;Xi];
G = [G;((b-1)*NC+c)*ones(size(Xi))];
C = [C;c];
end
end
if nargin < 2, cmap = jet(NC); end
if nargin < 3, blabs = 1:NB; end
wb = 1;
wi = 1.2*wb;
wo = 2 *wb;
x = wi.*[1:NB*NC] + (wo-wi).*ceil([1:NB*NC]./NC);
t = cat(1,arrayfun(@(i)mean(x(NC*(i-1)+1:NC*(i))),1:NB));
boxplot(X(:),G(:),'width',wb,'position',x,varargin{:},'color',cmap(C(:),:),'symbol','+');
set(gca,'xtick',t,'xticklabel',blabs);
|
github
|
uoguelph-mlrg/vlr-master
|
readnii.m
|
.m
|
vlr-master/utils/nii/readnii.m
| 529 |
utf_8
|
b5351779fcf96b8ab4d76d2eb269a48d
|
% READNII
% read a .nii file: image data and voxel size (optional)
function [I,vsize] = readnii(fname)
[~,~,ftype] = fileparts(fname);
if ~exist(fname,'file')
error('Cannot find NIFTI file: %s',fname);
elseif ~any(strcmp(ftype,{'.nii','.gz'}))
error('File: %s is not NIFTI',fname);
end
try
NII = load_untouch_nii(fname);
I = double(imrotate(NII.img,-90));
%I = I./max(I(:));
catch ME
disp( getReport( ME, 'extended', 'hyperlinks', 'on' ) );
end
try
vsize = NII.hdr.dime.pixdim([3,2,4]);
catch
vsize = [];
end
|
github
|
uoguelph-mlrg/vlr-master
|
readniivsize.m
|
.m
|
vlr-master/utils/nii/readniivsize.m
| 466 |
utf_8
|
f85c2453d694ad9cb6696cdd2ba98aa8
|
% READNIIVSIZE
% Read just the voxel size from a .nii file
function [vsize] = readniivsize(fname)
[~,~,ftype] = fileparts(fname);
if ~exist(fname,'file')
error('Cannot find NIFTI file: %s',fname);
elseif ~any(strcmp(ftype,{'.nii','.gz'}))
error('File: %s is not NIFTI',fname);
end
try
hdr = load_untouch_header_only(fname);
catch ME
disp( getReport( ME, 'extended', 'hyperlinks', 'on' ) );
end
try
vsize = hdr.dime.pixdim([3,2,4]);
catch
vsize = [];
end
|
github
|
uoguelph-mlrg/vlr-master
|
readnicenii.m
|
.m
|
vlr-master/utils/nii/readnicenii.m
| 489 |
utf_8
|
83cabdf6577158e4a2f795720ea61bff
|
% READNICENII
% Read a .nii file and immediately apply some basic pre-processing.
% M is a brain mask (must be same size as I)
% mm is a 2 element vector denoting the quantiles (0-1) for clipping the data
% and rescaling to the range [0,1]
function [I,x] = readnicenii(fname,M,mm)
if nargin == 2, e = 0.0001; mm = [e,1-e]; end
[I,x] = readnii(fname);
I = imrotate(I,180);
I(isnan(I)) = 0;
I = max(0,I);
if nargin == 2
I(M<0.5) = 0;
I = momi(alphaclip(I,mm,M>0.5));
end
I = single(I);
|
github
|
uoguelph-mlrg/vlr-master
|
writenii.m
|
.m
|
vlr-master/utils/nii/writenii.m
| 1,537 |
utf_8
|
734479ada17064250e0110215778bf96
|
% WRITENII
% Write an image to .nii format using a template .nii file for the header
% I - the image volume data
% fname - the new .nii file name
% niiname - the template .nii file name
% datatype - I don't think this actually works
function [] = writenii(I,fname,niiname,datatype)
if nargin == 3
datatype = class(I);
end
if ~exist(niiname,'file')
error('Cannot find NIFTI file: %s',niiname);
elseif ~any(strcmp(filetype(niiname),{'.nii','.gz'}))
error('File: %s is not NIFTI',niiname);
end
try
NII = load_untouch_nii(niiname);
% if ~isempty(extradim) % hax for writing TPM
% NII.hdr.dime.dim = [4 121 145 121 dim4 1 1 1];
% end
I = double(imrotate(I,+90));
NII.hdr.dime.dim = [4, size(I), ones(1,7-numel(size(I)))];
NII.img = I;
[NII.hdr.dime.datatype, NII.hdr.dime.bitpix] = dtypelut(datatype);
save_untouch_nii(NII,fname);
catch ME
disp( getReport( ME, 'extended', 'hyperlinks', 'on' ) );
end
function [ft] = filetype(fname)
[~,~,ft] = fileparts(fname);
function [dt,bp] = dtypelut(datatype)
switch datatype
case 'logical', dt = 1; bp = 1;
case 'int8', dt = 256; bp = 8;
case 'uint8', dt = 128; bp = 8;
case 'int16', dt = 4; bp = 16;
case 'uint16', dt = 512; bp = 16;
case 'int32', dt = 8; bp = 32;
case 'uint32', dt = 768; bp = 32;
case 'int64', dt = 1024; bp = 64;
case 'uint64', dt = 1280; bp = 64;
case 'single', dt = 16; bp = 32;
case 'double', dt = 64; bp = 64;
otherwise, error('Unknown datatype');
end
|
github
|
uoguelph-mlrg/vlr-master
|
load_nii_ext.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_nii_ext.m
| 5,337 |
utf_8
|
fa0e831b0a596c3208b21bddc1c6d812
|
% Load NIFTI header extension after its header is loaded using load_nii_hdr.
%
% Usage: ext = load_nii_ext(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function ext = load_nii_ext(filename)
if ~exist('filename','var'),
error('Usage: ext = load_nii_ext(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',filename) & strcmp(filename(end-3:end), '.nii')
new_ext = 1;
filename(end-3:end)='';
end
if findstr('.hdr',filename) & strcmp(filename(end-3:end), '.hdr')
filename(end-3:end)='';
end
if findstr('.img',filename) & strcmp(filename(end-3:end), '.img')
filename(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', filename);
error(msg);
end
else
fn = sprintf('%s.hdr',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', filename);
error(msg);
end
end
fid = fopen(fn,'r',machine);
vox_offset = 0;
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
end
end
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return % load_nii_ext
%---------------------------------------------------------------------
function ext = read_extension(fid, vox_offset)
ext = [];
if vox_offset
end_of_ext = vox_offset;
else
fseek(fid, 0, 'eof');
end_of_ext = ftell(fid);
end
if end_of_ext > 352
fseek(fid, 348, 'bof');
ext.extension = fread(fid,4)';
end
if isempty(ext) | ext.extension(1) == 0
ext = [];
return;
end
i = 1;
while(ftell(fid) < end_of_ext)
ext.section(i).esize = fread(fid,1,'int32');
ext.section(i).ecode = fread(fid,1,'int32');
ext.section(i).edata = char(fread(fid,ext.section(i).esize-8)');
i = i + 1;
end
ext.num_ext = length(ext.section);
return % read_extension
|
github
|
uoguelph-mlrg/vlr-master
|
rri_orient.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_orient.m
| 2,251 |
utf_8
|
4253fb96b9189a8a4bad49661d9ecac3
|
% Convert image of different orientations to standard Analyze orientation
%
% Usage: nii = rri_orient(nii);
% Jimmy Shen ([email protected]), 26-APR-04
%___________________________________________________________________
function [nii, orient, pattern] = rri_orient(nii, varargin)
if nargin > 1
pattern = varargin{1};
else
pattern = [];
end
if(nargin > 2)
orient = varargin{2};
if(length(find(orient>6)) || length(find(orient<1))) %value checking
orient=[1 2 3]; %set to default if bogus values set
end
else
orient = [1 2 3];
end
dim = double(nii.hdr.dime.dim([2:4]));
if ~isempty(pattern) & ~isequal(length(pattern), prod(dim))
return;
end
% get orient of the current image
%
if isequal(orient, [1 2 3])
orient = rri_orient_ui;
pause(.1);
end
% no need for conversion
%
if isequal(orient, [1 2 3])
return;
end
if isempty(pattern)
pattern = 1:prod(dim);
end
pattern = reshape(pattern, dim);
img = nii.img;
% calculate after flip orient
%
rot_orient = mod(orient + 2, 3) + 1;
% do flip:
%
flip_orient = orient - rot_orient;
for i = 1:3
if flip_orient(i)
pattern = flipdim(pattern, i);
img = flipdim(img, i);
end
end
% get index of orient (do inverse)
%
[tmp rot_orient] = sort(rot_orient);
% do rotation:
%
pattern = permute(pattern, rot_orient);
img = permute(img, [rot_orient 4 5 6]);
% rotate resolution, or 'dim'
%
new_dim = nii.hdr.dime.dim([2:4]);
new_dim = new_dim(rot_orient);
nii.hdr.dime.dim([2:4]) = new_dim;
% rotate voxel_size, or 'pixdim'
%
tmp = nii.hdr.dime.pixdim([2:4]);
tmp = tmp(rot_orient);
nii.hdr.dime.pixdim([2:4]) = tmp;
% re-calculate originator
%
tmp = nii.hdr.hist.originator([1:3]);
tmp = tmp(rot_orient);
flip_orient = flip_orient(rot_orient);
for i = 1:3
if flip_orient(i) & ~isequal(double(tmp(i)), 0)
tmp(i) = int16(double(new_dim(i)) - double(tmp(i)) + 1);
end
end
nii.hdr.hist.originator([1:3]) = tmp;
nii.img = img;
pattern = pattern(:);
return; % rri_orient
|
github
|
uoguelph-mlrg/vlr-master
|
save_untouch0_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_untouch0_nii_hdr.m
| 8,594 |
utf_8
|
7e8b1b327e1924837820f75780d52d01
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar');
fwrite(fid, hk.hkey_un0(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
pad = zeros(1, 4-length(dime.vox_units));
dime.vox_units = [dime.vox_units char(pad)];
fwrite(fid, dime.vox_units(1:4), 'uchar');
pad = zeros(1, 8-length(dime.cal_units));
dime.cal_units = [dime.cal_units char(pad)];
fwrite(fid, dime.cal_units(1:8), 'uchar');
fwrite(fid, dime.unused1(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.dim_un0(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.roi_scale(1), 'float32');
fwrite(fid, dime.funused1(1), 'float32');
fwrite(fid, dime.funused2(1), 'float32');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.compressed(1), 'int32');
fwrite(fid, dime.verified(1), 'int32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures - ANALYZE 7.5
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.orient(1), 'uchar');
fwrite(fid, hist.originator(1:5), 'int16');
pad = zeros(1, 10-length(hist.generated));
hist.generated = [hist.generated char(pad)];
fwrite(fid, hist.generated(1:10), 'uchar');
pad = zeros(1, 10-length(hist.scannum));
hist.scannum = [hist.scannum char(pad)];
fwrite(fid, hist.scannum(1:10), 'uchar');
pad = zeros(1, 10-length(hist.patient_id));
hist.patient_id = [hist.patient_id char(pad)];
fwrite(fid, hist.patient_id(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_date));
hist.exp_date = [hist.exp_date char(pad)];
fwrite(fid, hist.exp_date(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_time));
hist.exp_time = [hist.exp_time char(pad)];
fwrite(fid, hist.exp_time(1:10), 'uchar');
pad = zeros(1, 3-length(hist.hist_un0));
hist.hist_un0 = [hist.hist_un0 char(pad)];
fwrite(fid, hist.hist_un0(1:3), 'uchar');
fwrite(fid, hist.views(1), 'int32');
fwrite(fid, hist.vols_added(1), 'int32');
fwrite(fid, hist.start_field(1),'int32');
fwrite(fid, hist.field_skip(1), 'int32');
fwrite(fid, hist.omax(1), 'int32');
fwrite(fid, hist.omin(1), 'int32');
fwrite(fid, hist.smax(1), 'int32');
fwrite(fid, hist.smin(1), 'int32');
return; % data_history
|
github
|
uoguelph-mlrg/vlr-master
|
rri_zoom_menu.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_zoom_menu.m
| 737 |
utf_8
|
d8151523470b0fba970eb1d98ba56030
|
% Imbed a zoom menu to any figure.
%
% Usage: rri_zoom_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = rri_zoom_menu(fig)
if isnumeric(fig)
menu_hdl = uimenu('Parent',fig, ...
'Label','Zoom on', ...
'Userdata', 1, ...
'Callback','rri_zoom_menu(''zoom'');');
return;
end
zoom_on_state = get(gcbo,'Userdata');
if (zoom_on_state == 1)
zoom on;
set(gcbo,'Userdata',0,'Label','Zoom off');
set(gcbf,'pointer','crosshair');
else
zoom off;
set(gcbo,'Userdata',1,'Label','Zoom on');
set(gcbf,'pointer','arrow');
end
return % rri_zoom_menu
|
github
|
uoguelph-mlrg/vlr-master
|
rri_select_file.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_select_file.m
| 16,599 |
utf_8
|
e349954ca803370f62ceeabdbab5912e
|
function [selected_file, selected_path] = rri_select_file(varargin)
%
% USAGE: [selected_file, selected_path] = ...
% rri_select_file(dir_name, fig_title)
%
% Allow user to select a file from a list of Matlab competible
% file format
%
% Example:
%
% [selected_file, selected_path] = ...
% rri_select_file('/usr','Select Data File');
%
% See Also RRI_GETFILES
% -- Created June 2001 by Wilkin Chau, Rotman Research Institute
%
% use rri_select_file to open & save Matlab recognized format
% -- Modified Dec 2002 by Jimmy Shen, Rotman Research Institute
%
if nargin == 0 | ischar(varargin{1}) % create rri_select_file figure
dir_name = '';
fig_title = 'Select a File';
if nargin > 0
dir_name = varargin{1};
end
if nargin > 1
fig_title = varargin{2};
end
Init(fig_title,dir_name);
uiwait; % wait for user finish
selected_path = getappdata(gcf,'SelectedDirectory');
selected_file = getappdata(gcf,'SelectedFile');
cd (getappdata(gcf,'StartDirectory'));
close(gcf);
return;
end;
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
action = varargin{1}{1};
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
if strcmp(action,'EditFilter'),
EditFilter;
% run delete_fig when figure is closing
%
elseif strcmp(action,'delete_fig'),
delete_fig;
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
elseif strcmp(action,'select_dir'),
select_dir;
% select 'Files':
% update 'File selection'
%
elseif strcmp(action,'select_file'),
select_file;
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
elseif strcmp(action,'EditSelection'),
EditSelection;
% clicked 'Select'
%
elseif strcmp(action,'DONE_BUTTON_PRESSED'),
h = findobj(gcf,'Tag','SelectionEdit');
[filepath,filename,fileext] = fileparts(get(h,'String'));
if isempty(filepath) | isempty(filename) | isempty(fileext)
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
else
if ~strcmp(filepath(end),filesep) % not end with filesep
filepath = [filepath filesep]; % add a filesep to filepath
end
setappdata(gcf,'SelectedDirectory',filepath);
setappdata(gcf,'SelectedFile',[filename fileext]);
end
if getappdata(gcf,'ready') % ready to exit
uiresume;
end
% clicked 'cancel'
%
elseif strcmp(action,'CANCEL_BUTTON_PRESSED'),
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
set(findobj(gcf,'Tag','FileList'),'String','');
uiresume;
end;
return;
% --------------------------------------------------------------------
function Init(fig_title,dir_name),
StartDirectory = pwd;
if isempty(StartDirectory),
StartDirectory = filesep;
end;
filter_disp = {'JPEG image (*.jpg)', ...
'TIFF image, compressed (*.tif)', ...
'EPS Level 1 (*.eps)', ...
'Adobe Illustrator 88 (*.ai)', ...
'Enhanced metafile (*.emf)', ...
'Matlab Figure (*.fig)', ...
'Matlab M-file (*.m)', ...
'Portable bitmap (*.pbm)', ...
'Paintbrush 24-bit (*.pcx)', ...
'Portable Graymap (*.pgm)', ...
'Portable Network Graphics (*.png)', ...
'Portable Pixmap (*.ppm)', ...
};
filter_string = {'*.jpg', ...
'*.tif', ...
'*.eps', ...
'*.ai', ...
'*.emf', ...
'*.fig', ...
'*.m', ...
'*.pbm', ...
'*.pcx', ...
'*.pgm', ...
'*.png', ...
'*.ppm', ...
};
% filter_disp = char(filter_disp);
filter_string = char(filter_string);
margine = 0.05;
line_height = 0.07;
char_height = line_height*0.8;
save_setting_status = 'on';
rri_select_file_pos = [];
try
load('pls_profile');
catch
end
if ~isempty(rri_select_file_pos) & strcmp(save_setting_status,'on')
pos = rri_select_file_pos;
else
w = 0.4;
h = 0.6;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
h0 = figure('parent',0, 'Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name',fig_title, ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position', pos, ...
'deleteFcn','rri_select_file({''delete_fig''});', ...
'WindowStyle', 'modal', ...
'Tag','GetFilesFigure', ...
'ToolBar','none');
x = margine;
y = 1 - 1*line_height - margine;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Filter Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','Choose one of the file format:', ...
'Tag','FilterLabel');
y = 1 - 2*line_height - margine + line_height*0.2;
w = 1-2*x;
pos = [x y w h];
h_filter = uicontrol('Parent',h0, ... % Filter list
'Style','popupmenu', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', filter_disp, ...
'user', filter_string, ...
'value', 1, ...
'Callback','rri_select_file({''EditFilter''});', ...
'Tag','FilterEdit');
y = 1 - 3*line_height - margine;
w = 0.5 - x - margine/2;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Directory Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Directories', ...
'Tag','DirectoryLabel');
x = 0.5;
y = 1 - 3*line_height - margine;
w = 0.5 - margine;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % File Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Files', ...
'Tag','FileLabel');
x = margine;
y = 4*line_height + margine;
w = 0.5 - x - margine/2;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_dir = uicontrol('Parent',h0, ... % Directory Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'Interruptible', 'off', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_dir''});', ...
'Tag','DirectoryList');
x = 0.5;
y = 4*line_height + margine;
w = 0.5 - margine;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_file = uicontrol('Parent',h0, ... % File Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_file''});', ...
'Tag','FileList');
x = margine;
y = 3*line_height + margine - line_height*0.2;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Selection Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','File you selected:', ...
'Tag','SelectionLabel');
y = 2*line_height + margine;
w = 1-2*x;
pos = [x y w h];
h_select = uicontrol('Parent',h0, ... % Selection Edit
'Style','edit', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''EditSelection''});', ...
'Tag','SelectionEdit');
x = 2*margine;
y = line_height/2 + margine;
w = 0.2;
h = line_height;
pos = [x y w h];
h_done = uicontrol('Parent',h0, ... % DONE
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Save', ... % 'Select', ...
'Callback','rri_select_file({''DONE_BUTTON_PRESSED''});', ...
'Tag','DONEButton');
x = 1 - x - w;
pos = [x y w h];
h_cancel = uicontrol('Parent',h0, ... % CANCEL
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Cancel', ...
'Callback','rri_select_file({''CANCEL_BUTTON_PRESSED''});', ...
'Tag','CANCELButton');
if isempty(dir_name)
dir_name = StartDirectory;
end
set(h_select,'string',dir_name);
filter_select = get(h_filter,'value');
filter_pattern = filter_string(filter_select,:);
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
setappdata(gcf,'filter_string',filter_string);
setappdata(gcf,'h_filter', h_filter);
setappdata(gcf,'h_dir', h_dir);
setappdata(gcf,'h_file', h_file);
setappdata(gcf,'h_select', h_select);
setappdata(gcf,'h_done', h_done);
setappdata(gcf,'h_cancel', h_cancel);
setappdata(gcf,'StartDirectory',StartDirectory);
EditSelection;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % Init
% called by all the actions, to update 'Directories' or 'Files'
% based on filter_pattern. Select first file in filelist.
%
% --------------------------------------------------------------------
function update_dirlist;
filter_path = getappdata(gcf,'curr_dir');
filter_pattern = getappdata(gcf,'FilterPattern');
if exist(filter_pattern) == 2 % user input specific filename
is_single_file = 1; % need manually take path out later
else
is_single_file = 0;
end
% take the file path out from filter_pattern
%
[fpath fname fext] = fileparts(filter_pattern);
filter_pattern = [fname fext];
dir_struct = dir(filter_path);
if isempty(dir_struct)
msg = 'ERROR: Directory not found!';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
old_pointer = get(gcf,'Pointer');
set(gcf,'Pointer','watch');
dir_list = dir_struct(find([dir_struct.isdir] == 1));
[sorted_dir_names,sorted_dir_index] = sortrows({dir_list.name}');
dir_struct = dir([filter_path filesep filter_pattern]);
if isempty(dir_struct)
sorted_file_names = [];
else
file_list = dir_struct(find([dir_struct.isdir] == 0));
if is_single_file % take out path
tmp = file_list.name;
[fpath fname fext] = fileparts(tmp);
file_list.name = [fname fext];
end
[sorted_file_names,sorted_file_index] = sortrows({file_list.name}');
end;
disp_dir_names = []; % if need full path, use this
% instead of sorted_dir_names
for i=1:length(sorted_dir_names)
tmp = [filter_path filesep sorted_dir_names{i}];
disp_dir_names = [disp_dir_names {tmp}];
end
h = findobj(gcf,'Tag','DirectoryList');
set(h,'String',sorted_dir_names,'Value',1);
h = findobj(gcf,'Tag','FileList');
set(h,'String',sorted_file_names,'value',1);
h_select = getappdata(gcf,'h_select');
if strcmp(filter_path(end),filesep) % filepath end with filesep
filter_path = filter_path(1:end-1); % take filesep out
end
if isempty(sorted_file_names)
set(h_select,'string',[filter_path filesep]);
else
set(h_select,'string',[filter_path filesep sorted_file_names{1}]);
end
set(gcf,'Pointer',old_pointer);
return; % update_dirlist
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function EditFilter()
filter_select = get(gcbo,'value');
filter_string = getappdata(gcf,'filter_string');
filter_pattern = filter_string(filter_select,:);
filter_path = getappdata(gcf,'curr_dir');
% update filter_pattern
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
if isempty(filter_path),
filter_path = filesep;
end;
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % EditFilter
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function select_dir()
listed_dir = get(gcbo,'String');
selected_dir_idx = get(gcbo,'Value');
selected_dir = listed_dir{selected_dir_idx};
curr_dir = getappdata(gcf,'curr_dir');
% update the selection box
%
try
cd ([curr_dir filesep selected_dir]);
catch
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
if isempty(pwd)
curr_dir = filesep;
else
curr_dir = pwd;
end;
setappdata(gcf,'curr_dir',curr_dir);
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % select_dir
% select 'Files':
% update 'File selection'
%
% --------------------------------------------------------------------
function select_file()
setappdata(gcf,'ready',1);
listed_file = get(gcbo,'String');
selected_file_idx = get(gcbo,'Value');
selected_file = listed_file{selected_file_idx};
curr_dir = getappdata(gcf,'curr_dir');
if strcmp(curr_dir(end),filesep) % filepath end with filesep
curr_dir = curr_dir(1:end-1); % take filesep out
end
h_select = getappdata(gcf,'h_select');
set(h_select,'string',[curr_dir filesep selected_file]);
return; % select_file
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
% --------------------------------------------------------------------
function EditSelection()
filter_string = getappdata(gcf,'filter_string');
h_select = getappdata(gcf,'h_select');
selected_file = get(h_select,'string');
if exist(selected_file) == 7 % if user enter a dir
setappdata(gcf,'ready',0);
setappdata(gcf,'curr_dir',selected_file); % get new dir
update_dirlist;
else
setappdata(gcf,'ready',1);
[fpath fname fext]= fileparts(selected_file);
if exist(fpath) ~=7 % fpath is not a dir
setappdata(gcf,'ready',0);
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
% if the file format user entered is not supported by matlab
if isempty(strmatch(['*',fext],filter_string,'exact'))
setappdata(gcf,'ready',0);
msg = 'ERROR: File format is not supported by Matlab.';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
end
return; % EditSelection
% --------------------------------------------------------------------
function delete_fig()
try
load('pls_profile');
pls_profile = which('pls_profile.mat');
rri_select_file_pos = get(gcbf,'position');
save(pls_profile, '-append', 'rri_select_file_pos');
catch
end
return;
|
github
|
uoguelph-mlrg/vlr-master
|
clip_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/clip_nii.m
| 3,306 |
utf_8
|
a70bdbed5a0813312d4c83f94b99a710
|
% CLIP_NII: Clip the NIfTI volume from any of the 6 sides
%
% Usage: nii = clip_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be cut from which side.
%
% option.cut_from_L = ( number of voxel )
% option.cut_from_R = ( number of voxel )
% option.cut_from_P = ( number of voxel )
% option.cut_from_A = ( number of voxel )
% option.cut_from_I = ( number of voxel )
% option.cut_from_S = ( number of voxel )
%
% Options description in detail:
% ==============================
%
% cut_from_L: Number of voxels from Left side will be clipped.
%
% cut_from_R: Number of voxels from Right side will be clipped.
%
% cut_from_P: Number of voxels from Posterior side will be clipped.
%
% cut_from_A: Number of voxels from Anterior side will be clipped.
%
% cut_from_I: Number of voxels from Inferior side will be clipped.
%
% cut_from_S: Number of voxels from Superior side will be clipped.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = clip_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
cut_from_L = 0;
cut_from_R = 0;
cut_from_P = 0;
cut_from_A = 0;
cut_from_I = 0;
cut_from_S = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'cut_from_L')
cut_from_L = round(opt.cut_from_L);
if cut_from_L >= origin(1) | cut_from_L < 0
error('cut_from_L cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_P')
cut_from_P = round(opt.cut_from_P);
if cut_from_P >= origin(2) | cut_from_P < 0
error('cut_from_P cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_I')
cut_from_I = round(opt.cut_from_I);
if cut_from_I >= origin(3) | cut_from_I < 0
error('cut_from_I cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_R')
cut_from_R = round(opt.cut_from_R);
if cut_from_R > dims(1)-origin(1) | cut_from_R < 0
error('cut_from_R cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_A')
cut_from_A = round(opt.cut_from_A);
if cut_from_A > dims(2)-origin(2) | cut_from_A < 0
error('cut_from_A cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_S')
cut_from_S = round(opt.cut_from_S);
if cut_from_S > dims(3)-origin(3) | cut_from_S < 0
error('cut_from_S cannot be negative or cut beyond originator');
end
end
end
nii = make_nii(nii.img( (cut_from_L+1) : (dims(1)-cut_from_R), ...
(cut_from_P+1) : (dims(2)-cut_from_A), ...
(cut_from_I+1) : (dims(3)-cut_from_S), ...
:,:,:,:,:), nii.hdr.dime.pixdim(2:4), ...
[origin(1)-cut_from_L origin(2)-cut_from_P origin(3)-cut_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
uoguelph-mlrg/vlr-master
|
affine.m
|
.m
|
vlr-master/utils/nii/nifti_DL/affine.m
| 16,110 |
utf_8
|
768d2303e551a9584685bdb01abf6f8b
|
% Using 2D or 3D affine matrix to rotate, translate, scale, reflect and
% shear a 2D image or 3D volume. 2D image is represented by a 2D matrix,
% 3D volume is represented by a 3D matrix, and data type can be real
% integer or floating-point.
%
% You may notice that MATLAB has a function called 'imtransform.m' for
% 2D spatial transformation. However, keep in mind that 'imtransform.m'
% assumes y for the 1st dimension, and x for the 2nd dimension. They are
% equivalent otherwise.
%
% In addition, if you adjust the 'new_elem_size' parameter, this 'affine.m'
% is equivalent to 'interp2.m' for 2D image, and equivalent to 'interp3.m'
% for 3D volume.
%
% Usage: [new_img new_M] = ...
% affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);
%
% old_img - original 2D image or 3D volume. We assume x for the 1st
% dimension, y for the 2nd dimension, and z for the 3rd
% dimension.
%
% old_M - a 3x3 2D affine matrix for 2D image, or a 4x4 3D affine
% matrix for 3D volume. We assume x for the 1st dimension,
% y for the 2nd dimension, and z for the 3rd dimension.
%
% new_elem_size (optional) - size of voxel along x y z direction for
% a transformed 3D volume, or size of pixel along x y for
% a transformed 2D image. We assume x for the 1st dimension
% y for the 2nd dimension, and z for the 3rd dimension.
% 'new_elem_size' is 1 if it is default or empty.
%
% You can increase its value to decrease the resampling rate,
% and make the 2D image or 3D volume more coarse. It works
% just like 'interp3'.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by the interpolation. 0 in most cases. If it is
% default or empty, 'bg' will be the average of two corner
% voxel intensities in original data.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% new_img - transformed 2D image or 3D volume
%
% new_M - transformed affine matrix
%
% Example 1 (3D rotation):
% load mri.mat; old_img = double(squeeze(D));
% old_M = [0.88 0.5 3 -90; -0.5 0.88 3 -126; 0 0 2 -72; 0 0 0 1];
% new_img = affine(old_img, old_M, 2);
% [x y z] = meshgrid(1:128,1:128,1:27);
% sz = size(new_img);
% [x1 y1 z1] = meshgrid(1:sz(2),1:sz(1),1:sz(3));
% figure; slice(x, y, z, old_img, 64, 64, 13.5);
% shading flat; colormap(map); view(-66, 66);
% figure; slice(x1, y1, z1, new_img, sz(1)/2, sz(2)/2, sz(3)/2);
% shading flat; colormap(map); view(-66, 66);
%
% Example 2 (2D interpolation):
% load mri.mat; old_img=D(:,:,1,13)';
% old_M = [1 0 0; 0 1 0; 0 0 1];
% new_img = affine(old_img, old_M, [.2 .4]);
% figure; image(old_img); colormap(map);
% figure; image(new_img); colormap(map);
%
% This program is inspired by:
% SPM5 Software from Wellcome Trust Centre for Neuroimaging
% http://www.fil.ion.ucl.ac.uk/spm/software
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [new_img, new_M] = affine(old_img, old_M, new_elem_size, verbose, bg, method)
if ~exist('old_img','var') | ~exist('old_M','var')
error('Usage: [new_img new_M] = affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);');
end
if ndims(old_img) == 3
if ~isequal(size(old_M),[4 4])
error('old_M should be a 4x4 affine matrix for 3D volume.');
end
elseif ndims(old_img) == 2
if ~isequal(size(old_M),[3 3])
error('old_M should be a 3x3 affine matrix for 2D image.');
end
else
error('old_img should be either 2D image or 3D volume.');
end
if ~exist('new_elem_size','var') | isempty(new_elem_size)
new_elem_size = [1 1 1];
elseif length(new_elem_size) < 2
new_elem_size = new_elem_size(1)*ones(1,3);
elseif length(new_elem_size) < 3
new_elem_size = [new_elem_size(:); 1]';
end
if ~exist('method','var') | isempty(method)
method = 1;
elseif ~exist('bresenham_line3d.m','file') & method == 3
error([char(10) char(10) 'Please download 3D Bresenham''s line generation program from:' char(10) char(10) 'http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21057' char(10) char(10) 'to test Fischer''s Bresenham interpolation method.' char(10) char(10)]);
end
% Make compatible to MATLAB earlier than version 7 (R14), which
% can only perform arithmetic on double data type
%
old_img = double(old_img);
old_dim = size(old_img);
if ~exist('bg','var') | isempty(bg)
bg = mean([old_img(1) old_img(end)]);
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ndims(old_img) == 2
old_dim(3) = 1;
old_M = old_M(:, [1 2 3 3]);
old_M = old_M([1 2 3 3], :);
old_M(3,:) = [0 0 1 0];
old_M(:,3) = [0 0 1 0]';
end
% Vertices of img in voxel
%
XYZvox = [ 1 1 1
1 1 old_dim(3)
1 old_dim(2) 1
1 old_dim(2) old_dim(3)
old_dim(1) 1 1
old_dim(1) 1 old_dim(3)
old_dim(1) old_dim(2) 1
old_dim(1) old_dim(2) old_dim(3) ]';
old_R = old_M(1:3,1:3);
old_T = old_M(1:3,4);
% Vertices of img in millimeter
%
XYZmm = old_R*(XYZvox-1) + repmat(old_T, [1, 8]);
% Make scale of new_M according to new_elem_size
%
new_M = diag([new_elem_size 1]);
% Make translation so minimum vertex is moved to [1,1,1]
%
new_M(1:3,4) = round( min(XYZmm,[],2) );
% New dimensions will be the maximum vertices in XYZ direction (dim_vox)
% i.e. compute dim_vox via dim_mm = R*(dim_vox-1)+T
% where, dim_mm = round(max(XYZmm,[],2));
%
new_dim = ceil(new_M(1:3,1:3) \ ( round(max(XYZmm,[],2))-new_M(1:3,4) )+1)';
% Initialize new_img with new_dim
%
new_img = zeros(new_dim(1:3));
% Mask out any changes from Z axis of transformed volume, since we
% will traverse it voxel by voxel below. We will only apply unit
% increment of mask_Z(3,4) to simulate the cursor movement
%
% i.e. we will use mask_Z * new_XYZvox to replace new_XYZvox
%
mask_Z = diag(ones(1,4));
mask_Z(3,3) = 0;
% It will be easier to do the interpolation if we invert the process
% by not traversing the original volume. Instead, we traverse the
% transformed volume, and backproject each voxel in the transformed
% volume back into the original volume. If the backprojected voxel
% in original volume is within its boundary, the intensity of that
% voxel can be used by the cursor location in the transformed volume.
%
% First, we traverse along Z axis of transformed volume voxel by voxel
%
for z = 1:new_dim(3)
if verbose & ~mod(z,10)
fprintf('%.2f percent is done.\n', 100*z/new_dim(3));
end
% We need to find out the mapping from voxel in the transformed
% volume (new_XYZvox) to voxel in the original volume (old_XYZvox)
%
% The following equation works, because they all equal to XYZmm:
% new_R*(new_XYZvox-1) + new_T == old_R*(old_XYZvox-1) + old_T
%
% We can use modified new_M1 & old_M1 to substitute new_M & old_M
% new_M1 * new_XYZvox == old_M1 * old_XYZvox
%
% where: M1 = M; M1(:,4) = M(:,4) - sum(M(:,1:3),2);
% and: M(:,4) == [T; 1] == sum(M1,2)
%
% Therefore: old_XYZvox = old_M1 \ new_M1 * new_XYZvox;
%
% Since we are traverse Z axis, and new_XYZvox is replaced
% by mask_Z * new_XYZvox, the above formula can be rewritten
% as: old_XYZvox = old_M1 \ new_M1 * mask_Z * new_XYZvox;
%
% i.e. we find the mapping from new_XYZvox to old_XYZvox:
% M = old_M1 \ new_M1 * mask_Z;
%
% First, compute modified old_M1 & new_M1
%
old_M1 = old_M; old_M1(:,4) = old_M(:,4) - sum(old_M(:,1:3),2);
new_M1 = new_M; new_M1(:,4) = new_M(:,4) - sum(new_M(:,1:3),2);
% Then, apply unit increment of mask_Z(3,4) to simulate the
% cursor movement
%
mask_Z(3,4) = z;
% Here is the mapping from new_XYZvox to old_XYZvox
%
M = old_M1 \ new_M1 * mask_Z;
switch method
case 1
new_img(:,:,z) = trilinear(old_img, new_dim, old_dim, M, bg);
case 2
new_img(:,:,z) = nearest_neighbor(old_img, new_dim, old_dim, M, bg);
case 3
new_img(:,:,z) = bresenham(old_img, new_dim, old_dim, M, bg);
end
end; % for z
if ndims(old_img) == 2
new_M(3,:) = [];
new_M(:,3) = [];
end
return; % affine
%--------------------------------------------------------------------
function img_slice = trilinear(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
TINY = 5e-2; % tolerance
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X, and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
% within boundary of original image
%
if ( old_X > 1-TINY & old_X < xdim2+TINY & ...
old_Y > 1-TINY & old_Y < ydim2+TINY & ...
old_Z > 1-TINY & old_Z < zdim2+TINY )
% Calculate distance of old_XYZ to its neighbors for
% weighted intensity average
%
dx = old_X - floor(old_X);
dy = old_Y - floor(old_Y);
dz = old_Z - floor(old_Z);
x000 = floor(old_X);
x100 = x000 + 1;
if floor(old_X) < 1
x000 = 1;
x100 = x000;
elseif floor(old_X) > xdim2-1
x000 = xdim2;
x100 = x000;
end
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
y000 = floor(old_Y);
y010 = y000 + 1;
if floor(old_Y) < 1
y000 = 1;
y100 = y000;
elseif floor(old_Y) > ydim2-1
y000 = ydim2;
y010 = y000;
end
y100 = y000;
y001 = y000;
y101 = y000;
y110 = y010;
y011 = y010;
y111 = y010;
z000 = floor(old_Z);
z001 = z000 + 1;
if floor(old_Z) < 1
z000 = 1;
z001 = z000;
elseif floor(old_Z) > zdim2-1
z000 = zdim2;
z001 = z000;
end
z100 = z000;
z010 = z000;
z110 = z000;
z101 = z001;
z011 = z001;
z111 = z001;
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
v000 = double(img(x000, y000, z000));
v010 = double(img(x010, y010, z010));
v001 = double(img(x001, y001, z001));
v011 = double(img(x011, y011, z011));
v100 = double(img(x100, y100, z100));
v110 = double(img(x110, y110, z110));
v101 = double(img(x101, y101, z101));
v111 = double(img(x111, y111, z111));
img_slice(x,y) = v000*(1-dx)*(1-dy)*(1-dz) + ...
v010*(1-dx)*dy*(1-dz) + ...
v001*(1-dx)*(1-dy)*dz + ...
v011*(1-dx)*dy*dz + ...
v100*dx*(1-dy)*(1-dz) + ...
v110*dx*dy*(1-dz) + ...
v101*dx*(1-dy)*dz + ...
v111*dx*dy*dz;
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % trilinear
%--------------------------------------------------------------------
function img_slice = nearest_neighbor(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
xi = round(old_X);
yi = round(old_Y);
zi = round(old_Z);
% within boundary of original image
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % nearest_neighbor
%--------------------------------------------------------------------
function img_slice = bresenham(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
for y = 1:ydim1
start_old_XYZ = round(M*[0 y 0 1]');
end_old_XYZ = round(M*[xdim1 y 0 1]');
[X Y Z] = bresenham_line3d(start_old_XYZ, end_old_XYZ);
% line error correction
%
% del = end_old_XYZ - start_old_XYZ;
% del_dom = max(del);
% idx_dom = find(del==del_dom);
% idx_dom = idx_dom(1);
% idx_other = [1 2 3];
% idx_other(idx_dom) = [];
%del_x1 = del(idx_other(1));
% del_x2 = del(idx_other(2));
% line_slope = sqrt((del_x1/del_dom)^2 + (del_x2/del_dom)^2 + 1);
% line_error = line_slope - 1;
% line error correction removed because it is too slow
for x = 1:xdim1
% rescale ratio
%
i = round(x * length(X) / xdim1);
if i < 1
i = 1;
elseif i > length(X)
i = length(X);
end
xi = X(i);
yi = Y(i);
zi = Z(i);
% within boundary of the old XYZ space
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
% if line_error > 1
% x = x + 1;
% if x <= xdim1
% img_slice(x,y) = img(xi,yi,zi);
% line_error = line_slope - 1;
% end
% end % if line_error
% line error correction removed because it is too slow
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % bresenham
|
github
|
uoguelph-mlrg/vlr-master
|
load_untouch_nii_img.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_untouch_nii_img.m
| 14,756 |
utf_8
|
688b2a42f8071c6402a037c7ca923689
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_untouch_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB],[slice_idx]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
tmp = hdr.dime.dim(2:end);
tmp(find(tmp < 1)) = 1;
hdr.dime.dim(2:end) = tmp;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(slice_idx)*length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
else
img = [];
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
% ROMAN: begin
if(roman)
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
else
img = [img fread(fid, img_siz, sprintf('*%s',precision))];
end; %if(roman)
% ROMAN: end
end
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(slice_idx)
hdr.dime.dim(4) = length(slice_idx);
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
uoguelph-mlrg/vlr-master
|
load_untouch_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_untouch_nii.m
| 6,182 |
utf_8
|
93108a725d2e357d773c8aa0acf71328
|
% Load NIFTI or ANALYZE dataset, but not applying any appropriate affine
% geometric transform or voxel intensity scaling.
%
% Although according to NIFTI website, all those header information are
% supposed to be applied to the loaded NIFTI image, there are some
% situations that people do want to leave the original NIFTI header and
% data untouched. They will probably just use MATLAB to do certain image
% processing regardless of image orientation, and to save data back with
% the same NIfTI header.
%
% Since this program is only served for those situations, please use it
% together with "save_untouch_nii.m", and do not use "save_nii.m" or
% "view_nii.m" for the data that is loaded by "load_untouch_nii.m". For
% normal situation, you should use "load_nii.m" instead.
%
% Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [slice_idx])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of image volume indices.
% Only the specified volumes will be loaded. All available image
% volumes will be loaded, if it is default or empty.
%
% The number of images scans can be obtained from get_nii_frame.m,
% or simply: hdr.dime.dim(5).
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% slice_idx (optional) - a numerical array of image slice indices.
% Only the specified slices will be loaded. All available image
% slices will be loaded, if it is default or empty.
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% - Jimmy Shen ([email protected])
%
function nii = load_untouch_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, slice_idx)
if ~exist('filename','var')
error('Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [slice_idx])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx)
slice_idx = [];
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
nii.ext = [];
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
% Read the header extension
%
nii.ext = load_nii_ext(filename);
end
% Read the dataset body
%
[nii.img,nii.hdr] = load_untouch_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
% Perform some of sform/qform transform
%
% nii = xform_nii(nii, tolerance, preferredForm);
nii.untouch = 1;
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_untouch_nii
|
github
|
uoguelph-mlrg/vlr-master
|
collapse_nii_scan.m
|
.m
|
vlr-master/utils/nii/nifti_DL/collapse_nii_scan.m
| 6,778 |
utf_8
|
64b1cb0f7cd9e095d3c11ca66453df69
|
% Collapse multiple single-scan NIFTI files into a multiple-scan NIFTI file
%
% Usage: collapse_nii_scan(scan_file_pattern, [collapsed_fileprefix], [scan_file_folder])
%
% Here, scan_file_pattern should look like: 'myscan_0*.img'
% If collapsed_fileprefix is omit, 'multi_scan' will be used
% If scan_file_folder is omit, current file folder will be used
%
% The order of volumes in the collapsed file will be the order of
% corresponding filenames for those selected scan files.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function collapse_nii_scan(scan_pattern, fileprefix, scan_path)
if ~exist('fileprefix','var')
fileprefix = 'multi_scan';
else
[tmp fileprefix] = fileparts(fileprefix);
end
if ~exist('scan_path','var'), scan_path = pwd; end
pnfn = fullfile(scan_path, scan_pattern);
file_lst = dir(pnfn);
flist = {file_lst.name};
flist = flist(:);
filename = flist{1};
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
end
else
if ~strcmp(filename(end-3:end), '.img') & ...
~strcmp(filename(end-3:end), '.hdr') & ...
~strcmp(filename(end-3:end), '.nii')
error('Please check filename.');
end
end
nii = load_untouch_nii(fullfile(scan_path,filename));
nii.hdr.dime.dim(5) = length(flist);
if nii.hdr.dime.dim(1) < 4
nii.hdr.dime.dim(1) = 4;
end
hdr = nii.hdr;
filetype = nii.filetype;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
elseif filetype == 1
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid);
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
glmax = -inf;
glmin = inf;
for i = 1:length(flist)
nii = load_untouch_nii(fullfile(scan_path,flist{i}));
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if nii.hdr.dime.glmax > glmax
glmax = nii.hdr.dime.glmax;
end
if nii.hdr.dime.glmin < glmin
glmin = nii.hdr.dime.glmin;
end
fwrite(fid, nii.img, precision);
end
hdr.dime.glmax = round(glmax);
hdr.dime.glmin = round(glmin);
if filetype == 2
fseek(fid, 140, 'bof');
fwrite(fid, hdr.dime.glmax, 'int32');
fwrite(fid, hdr.dime.glmin, 'int32');
elseif filetype == 1
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch_nii_hdr(hdr, fid2);
if ~isempty(ext)
save_nii_ext(ext, fid2);
end
fclose(fid2);
else
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid2);
fclose(fid2);
end
fclose(fid);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
return; % collapse_nii_scan
|
github
|
uoguelph-mlrg/vlr-master
|
rri_orient_ui.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_orient_ui.m
| 5,384 |
utf_8
|
e1196b81940d9f93fbdb43c33799e587
|
% Return orientation of the current image:
% orient is orientation 1x3 matrix, in that:
% Three elements represent: [x y z]
% Element value: 1 - Left to Right; 2 - Posterior to Anterior;
% 3 - Inferior to Superior; 4 - Right to Left;
% 5 - Anterior to Posterior; 6 - Superior to Inferior;
% e.g.:
% Standard RAS Orientation: [1 2 3]
% Standard RHOS Orientation: [2 4 3]
% Jimmy Shen ([email protected]), 26-APR-04
%
function orient = rri_orient_ui(varargin)
if nargin == 0
init;
orient_ui_fig = gcf;
uiwait; % wait for user finish
orient = getappdata(gcf, 'orient');
if isempty(orient)
orient = [1 2 3];
end
if ishandle(orient_ui_fig)
close(gcf);
end
return;
end
action = varargin{1};
if strcmp(action, 'done')
click_done;
elseif strcmp(action, 'cancel')
uiresume;
end
return; % rri_orient_ui
%----------------------------------------------------------------------
function init
save_setting_status = 'on';
rri_orient_pos = [];
try
load('pls_profile');
catch
end
try
load('rri_pos_profile');
catch
end
if ~isempty(rri_orient_pos) & strcmp(save_setting_status,'on')
pos = rri_orient_pos;
else
w = 0.35;
h = 0.4;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
handles.figure = figure('Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name', 'Convert to standard RAS orientation', ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position',pos, ...
'WindowStyle', 'normal', ...
'ToolBar','none');
h0 = handles.figure;
Font.FontUnits = 'point';
Font.FontSize = 12;
margin = .1;
line_num = 6;
line_ht = (1 - margin*2) / line_num;
x = margin;
y = 1 - margin - line_ht;
w = 1 - margin * 2;
h = line_ht * .7;
pos = [x y w h];
handles.Ttit = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Please input orientation of the current image:');
y = y - line_ht;
w = .2;
pos = [x y w h];
handles.Tx_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'X Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Ty_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Y Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Tz_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Z Axes:');
choice = { 'From Left to Right', 'From Posterior to Anterior', ...
'From Inferior to Superior', 'From Right to Left', ...
'From Anterior to Posterior', 'From Superior to Inferior' };
y = 1 - margin - line_ht;
y = y - line_ht;
w = 1 - margin - x - w;
x = 1 - margin - w;
pos = [x y w h];
handles.x_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 1, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.y_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 2, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.z_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 3, ...
'background', [1 1 1]);
x = margin;
y = y - line_ht * 1.5;
w = .3;
pos = [x y w h];
handles.done = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''done'');', ...
'string', 'Done');
x = 1 - margin - w;
pos = [x y w h];
handles.cancel = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''cancel'');', ...
'string', 'Cancel');
setappdata(h0, 'handles', handles);
setappdata(h0, 'orient', [1 2 3]);
return; % init
%----------------------------------------------------------------------
function click_done
handles = getappdata(gcf, 'handles');
x_orient = get(handles.x_orient, 'value');
y_orient = get(handles.y_orient, 'value');
z_orient = get(handles.z_orient, 'value');
orient = [x_orient y_orient z_orient];
test_orient = [orient, orient + 3];
test_orient = mod(test_orient, 3);
if length(unique(test_orient)) ~= 3
msgbox('Please don''t choose same or opposite direction','Error','modal');
return;
end
setappdata(gcf, 'orient', [x_orient y_orient z_orient]);
uiresume;
return; % click_done
|
github
|
uoguelph-mlrg/vlr-master
|
load_untouch0_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_untouch0_nii_hdr.m
| 8,093 |
utf_8
|
3de9ff6a1da47b56ae680e7660eaa041
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine)
fn = sprintf('%s.hdr',fileprefix);
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.hkey_un0 = fread(fid, 1,directchar)';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
dime.dim = fread(fid,8,'int16')';
dime.vox_units = deblank(fread(fid,4,directchar)');
dime.cal_units = deblank(fread(fid,8,directchar)');
dime.unused1 = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.dim_un0 = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.roi_scale = fread(fid,1,'float32')';
dime.funused1 = fread(fid,1,'float32')';
dime.funused2 = fread(fid,1,'float32')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.compressed = fread(fid,1,'int32')';
dime.verified = fread(fid,1,'int32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.orient = fread(fid, 1,'char')';
hist.originator = fread(fid, 5,'int16')';
hist.generated = deblank(fread(fid,10,directchar)');
hist.scannum = deblank(fread(fid,10,directchar)');
hist.patient_id = deblank(fread(fid,10,directchar)');
hist.exp_date = deblank(fread(fid,10,directchar)');
hist.exp_time = deblank(fread(fid,10,directchar)');
hist.hist_un0 = deblank(fread(fid, 3,directchar)');
hist.views = fread(fid, 1,'int32')';
hist.vols_added = fread(fid, 1,'int32')';
hist.start_field = fread(fid, 1,'int32')';
hist.field_skip = fread(fid, 1,'int32')';
hist.omax = fread(fid, 1,'int32')';
hist.omin = fread(fid, 1,'int32')';
hist.smax = fread(fid, 1,'int32')';
hist.smin = fread(fid, 1,'int32')';
return % data_history
|
github
|
uoguelph-mlrg/vlr-master
|
load_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_nii.m
| 6,808 |
utf_8
|
d098a5dbea3cd4ad76cea624ffbef9db
|
% Load NIFTI or ANALYZE dataset. Support both *.nii and *.hdr/*.img
% file extension. If file extension is not provided, *.hdr/*.img will
% be used as default.
%
% A subset of NIFTI transform is included. For non-orthogonal rotation,
% shearing etc., please use 'reslice_nii.m' to reslice the NIFTI file.
% It will not cause negative effect, as long as you remember not to do
% slice time correction after reslicing the NIFTI file. Output variable
% nii will be in RAS orientation, i.e. X axis from Left to Right,
% Y axis from Posterior to Anterior, and Z axis from Inferior to
% Superior.
%
% Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [tolerance], [preferredForm])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of 4th dimension indices,
% which is the indices of image scan volume. The number of images
% scan volumes can be obtained from get_nii_frame.m, or simply
% hdr.dime.dim(5). Only the specified volumes will be loaded.
% All available image volumes will be loaded, if it is default or
% empty.
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed in the loaded image for any
% non-orthogonal rotation or shearing of NIfTI affine matrix. If
% you set 'tolerance' to 0, it means that you do not allow any
% distortion. If you set 'tolerance' to 1, it means that you do
% not care any distortion. The image will fail to be loaded if it
% can not be tolerated. The tolerance will be set to 0.1 (10%), if
% it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% original - the original header before any affine transform.
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = load_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, tolerance, preferredForm)
if ~exist('filename','var')
error('Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [tolerance], [preferredForm])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1; % 10 percent
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
% Read the header extension
%
% nii.ext = load_nii_ext(filename);
% Read the dataset body
%
[nii.img,nii.hdr] = load_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
% Perform some of sform/qform transform
%
nii = xform_nii(nii, tolerance, preferredForm);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_nii
|
github
|
uoguelph-mlrg/vlr-master
|
unxform_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/unxform_nii.m
| 1,181 |
utf_8
|
a77d113be34b09d588b2eb326a3c65c8
|
% Undo the flipping and rotations performed by xform_nii; spit back only
% the raw img data block. Initial cut will only deal with 3D volumes
% strongly assume we have called xform_nii to write down the steps used
% in xform_nii.
%
% Usage: a = load_nii('original_name');
% manipulate a.img to make array b;
%
% if you use unxform_nii to un-tranform the image (img) data
% block, then nii.original.hdr is the corresponding header.
%
% nii.original.img = unxform_nii(a, b);
% save_nii(nii.original,'newname');
%
% Where, 'newname' is created with data in the same space as the
% original_name data
%
% - Jeff Gunter, 26-JUN-06
%
function outblock = unxform_nii(nii, inblock)
if isempty(nii.hdr.hist.rot_orient)
outblock=inblock;
else
[dummy unrotate_orient] = sort(nii.hdr.hist.rot_orient);
outblock = permute(inblock, unrotate_orient);
end
if ~isempty(nii.hdr.hist.flip_orient)
flip_orient = nii.hdr.hist.flip_orient(unrotate_orient);
for i = 1:3
if flip_orient(i)
outblock = flipdim(outblock, i);
end
end
end;
return;
|
github
|
uoguelph-mlrg/vlr-master
|
load_untouch_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_untouch_nii_hdr.m
| 8,522 |
utf_8
|
2d4bc8c8ffb83b37daf1e8dd87c108e6
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine, filetype)
if filetype == 2
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
return % data_history
|
github
|
uoguelph-mlrg/vlr-master
|
save_nii_ext.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_nii_ext.m
| 977 |
utf_8
|
b60a98ab7537a883dc3ffef3175f19ae
|
% Save NIFTI header extension.
%
% Usage: save_nii_ext(ext, fid)
%
% ext - struct with NIFTI header extension fields.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function save_nii_ext(ext, fid)
if ~exist('ext','var') | ~exist('fid','var')
error('Usage: save_nii_ext(ext, fid)');
end
if ~isfield(ext,'extension') | ~isfield(ext,'section') | ~isfield(ext,'num_ext')
error('Wrong header extension');
end
write_ext(ext, fid);
return; % save_nii_ext
%---------------------------------------------------------------------
function write_ext(ext, fid)
fwrite(fid, ext.extension, 'uchar');
for i=1:ext.num_ext
fwrite(fid, ext.section(i).esize, 'int32');
fwrite(fid, ext.section(i).ecode, 'int32');
fwrite(fid, ext.section(i).edata, 'uchar');
end
return; % write_ext
|
github
|
uoguelph-mlrg/vlr-master
|
view_nii_menu.m
|
.m
|
vlr-master/utils/nii/nifti_DL/view_nii_menu.m
| 14,415 |
utf_8
|
32dd591fa1070721f0255f47f6e02510
|
% Imbed Zoom, Interp, and Info menu to view_nii window.
%
% Usage: view_nii_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = view_nii_menu(fig, varargin)
if isnumeric(fig)
menu_hdl = init(fig);
return;
end
menu_hdl = [];
switch fig
case 'interp'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
nii_menu = getappdata(fig, 'nii_menu');
interp_on_state = get(nii_menu.Minterp,'Userdata');
if (interp_on_state == 1)
opt.useinterp = 1;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
reset_zoom(fig);
else
opt.useinterp = 0;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
reset_zoom(fig);
end
case 'reset_zoom'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
reset_zoom(fig);
case 'orient'
orient;
case 'editvox'
editvox;
case 'img_info'
img_info;
case 'img_hist'
img_hist;
case 'save_disp'
save_disp;
end
return % view_nii_menu
%--------------------------------------------------------------------
function menu_hdl = init(fig)
% search for edit, view menu
%
nii_menu.Mfile = [];
nii_menu.Medit = [];
nii_menu.Mview = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
nii_menu.Mfile = menuitems(i);
end
editlabel = get(menuitems(i),'label');
if strcmpi(strrep(editlabel, '&', ''), 'edit')
nii_menu.Medit = menuitems(i);
end
viewlabel = get(menuitems(i),'label');
if strcmpi(strrep(viewlabel, '&', ''), 'view')
nii_menu.Mview = menuitems(i);
end
end
set(fig, 'menubar', 'none');
if isempty(nii_menu.Mfile)
nii_menu.Mfile = uimenu('Parent',fig, ...
'Label','File');
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'Callback','view_nii_menu(''save_disp'');');
else
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'separator','on', ...
'Callback','view_nii_menu(''save_disp'');');
end
if isempty(nii_menu.Medit)
nii_menu.Medit = uimenu('Parent',fig, ...
'Label','Edit');
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
else
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'separator','on', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
end
if isempty(nii_menu.Mview)
nii_menu.Mview = uimenu('Parent',fig, ...
'Label','View');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
else
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'separator','on', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
end
nii_menu.Mzoom = rri_zoom_menu(fig);
nii_menu.Minterp = uimenu('Parent',fig, ...
'Label','Interp on', ...
'Userdata', 1, ...
'Callback','view_nii_menu(''interp'');');
setappdata(fig,'nii_menu',nii_menu);
menu_hdl = nii_menu.Minterp;
return % init
%----------------------------------------------------------------
function reset_zoom(fig)
old_handle_vis = get(fig, 'HandleVisibility');
set(fig, 'HandleVisibility', 'on');
nii_view = getappdata(fig, 'nii_view');
nii_menu = getappdata(fig, 'nii_menu');
set(nii_menu.Mzoom,'Userdata',1,'Label','Zoom on');
set(fig,'pointer','arrow');
zoom off;
axes(nii_view.handles.axial_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.coronal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.sagittal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
set(fig, 'HandleVisibility', old_handle_vis);
return; % reset_zoom
%----------------------------------------------------------------
function img_info
nii_view = getappdata(gcbf, 'nii_view');
hdr = nii_view.nii.hdr;
max_value = num2str(double(max(nii_view.nii.img(:))));
min_value = num2str(double(min(nii_view.nii.img(:))));
dim = sprintf('%d %d %d', double(hdr.dime.dim(2:4)));
vox = sprintf('%.3f %.3f %.3f', double(hdr.dime.pixdim(2:4)));
if double(hdr.dime.datatype) == 1
type = '1-bit binary';
elseif double(hdr.dime.datatype) == 2
type = '8-bit unsigned integer';
elseif double(hdr.dime.datatype) == 4
type = '16-bit signed integer';
elseif double(hdr.dime.datatype) == 8
type = '32-bit signed integer';
elseif double(hdr.dime.datatype) == 16
type = '32-bit single float';
elseif double(hdr.dime.datatype) == 64
type = '64-bit double precision';
elseif double(hdr.dime.datatype) == 128
type = '24-bit RGB true color';
elseif double(hdr.dime.datatype) == 256
type = '8-bit signed integer';
elseif double(hdr.dime.datatype) == 511
type = '96-bit RGB true color';
elseif double(hdr.dime.datatype) == 512
type = '16-bit unsigned integer';
elseif double(hdr.dime.datatype) == 768
type = '32-bit unsigned integer';
elseif double(hdr.dime.datatype) == 1024
type = '64-bit signed integer';
elseif double(hdr.dime.datatype) == 1280
type = '64-bit unsigned integer';
end
msg = {};
msg = [msg {''}];
msg = [msg {['Dimension: [', dim, ']']}];
msg = [msg {''}];
msg = [msg {['Voxel Size: [', vox, ']']}];
msg = [msg {''}];
msg = [msg {['Data Type: [', type, ']']}];
msg = [msg {''}];
msg = [msg {['Max Value: [', max_value, ']']}];
msg = [msg {''}];
msg = [msg {['Min Value: [', min_value, ']']}];
msg = [msg {''}];
if isfield(nii_view.nii, 'fileprefix')
if isfield(nii_view.nii, 'filetype') & nii_view.nii.filetype == 2
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.nii]']}];
msg = [msg {''}];
elseif isfield(nii_view.nii, 'filetype')
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.img]']}];
msg = [msg {''}];
else
msg = [msg {['File Prefix: [', nii_view.nii.fileprefix, ']']}];
msg = [msg {''}];
end
end
h = msgbox(msg, 'Image Information', 'modal');
set(h,'color',[1 1 1]);
return; % img_info
%----------------------------------------------------------------
function orient
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
nii = nii_view.nii;
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
[nii orient] = rri_orient(nii);
if isequal(orient, [1 2 3]) % do nothing
set(fig,'Pointer',old_pointer);
return;
end
oldopt = view_nii(fig);
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % orient
%----------------------------------------------------------------
function editvox
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
nii = nii_view.nii;
oldopt = view_nii(fig);
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(nii.img(sag,cor,axi,1,nii_view.scanid)) double(nii.img(sag,cor,axi,2,nii_view.scanid)) double(nii.img(sag,cor,axi,3,nii_view.scanid))];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(nii.img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(nii.img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(nii.img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [R G B];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
else
imgvalue = double(nii.img(sag,cor,axi,nii_view.scanid));
init_val = sprintf('%.6g',imgvalue);
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
repeat = 1;
while repeat
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
init_val = inputdlg({'Replace the current voxel values with 3 new numbers:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
else
init_val = inputdlg({'Replace the current voxel value with 1 new number:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
end
if isempty(init_val)
set(fig,'Pointer',old_pointer);
return
end
imgvalue = str2num(init_val{1});
if ( (nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511) ...
& length(imgvalue) ~= 3 ) | ...
( (nii_view.nii.hdr.dime.datatype ~= 128 & nii_view.nii.hdr.dime.datatype ~= 511) ...
& length(imgvalue) ~= 1 )
% do nothing
else
repeat = 0;
end
end
if nii_view.nii.hdr.dime.datatype == 128
nii.img(sag,cor,axi,1,nii_view.scanid) = imgvalue(1);
nii.img(sag,cor,axi,2,nii_view.scanid) = imgvalue(2);
nii.img(sag,cor,axi,3,nii_view.scanid) = imgvalue(3);
elseif nii_view.nii.hdr.dime.datatype == 511
nii.img(sag,cor,axi,1,nii_view.scanid) = (imgvalue(1) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,2,nii_view.scanid) = (imgvalue(2) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,3,nii_view.scanid) = (imgvalue(3) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
else
nii.img(sag,cor,axi,nii_view.scanid) = imgvalue;
end
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % editvox
%----------------------------------------------------------------
function save_disp
[filename pathname] = uiputfile('*.*', 'Save displayed image as (*.nii or *.img)');
if isequal(filename,0) | isequal(pathname,0)
return;
else
out_imgfile = fullfile(pathname, filename); % original image file
end
old_pointer = get(gcbf,'Pointer');
set(gcbf,'Pointer','watch');
nii_view = getappdata(gcbf, 'nii_view');
nii = nii_view.nii;
try
save_nii(nii, out_imgfile);
catch
msg = 'File can not be saved.';
msgbox(msg, 'File write error', 'modal');
end
set(gcbf,'Pointer',old_pointer);
return; % save_disp
%----------------------------------------------------------------
function img_hist
nii_view = getappdata(gcbf, 'nii_view');
N = hist(double(nii_view.nii.img(:)),256);
x = linspace(double(min(nii_view.nii.img(:))), double(max(nii_view.nii.img(:))), 256);
figure;bar(x,N);
set(gcf, 'number', 'off', 'name', 'Volume Histogram');
set(gcf, 'windowstyle', 'modal'); % no zoom ...
xspan = max(x) - min(x) + 1;
yspan = max(N) + 1;
set(gca, 'xlim', [min(x)-xspan/20, max(x)+xspan/20]);
set(gca, 'ylim', [-yspan/20, max(N)+yspan/20]);
return; % img_hist
|
github
|
uoguelph-mlrg/vlr-master
|
save_untouch_header_only.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_untouch_header_only.m
| 2,132 |
utf_8
|
5f0515ef6a35f171bc8371d0f3fd365d
|
% This function is only used to save Analyze or NIfTI header that is
% ended with .hdr and loaded by load_untouch_header_only.m. If you
% have NIfTI file that is ended with .nii and you want to change its
% header only, you can use load_untouch_nii / save_untouch_nii pair.
%
% Usage: save_untouch_header_only(hdr, new_header_file_name)
%
% hdr - struct with NIfTI / Analyze header fields, which is obtained from:
% hdr = load_untouch_header_only(original_header_file_name)
%
% new_header_file_name - NIfTI / Analyze header name ended with .hdr.
% You can either copy original.img(.gz) to new.img(.gz) manually,
% or simply input original.hdr(.gz) in save_untouch_header_only.m
% to overwrite the original header.
%
% - Jimmy Shen ([email protected])
%
function save_untouch_header_only(hdr, filename)
if ~exist('hdr','var') | isempty(hdr) | ~exist('filename','var') | isempty(filename)
error('Usage: save_untouch_header_only(hdr, filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.hdr.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
filename = filename(1:end-3);
end
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
write_hdr(hdr, fileprefix);
% gzip output file if requested
%
if exist('gzFile', 'var')
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
end;
return % save_untouch_header_only
%-----------------------------------------------------------------------------------
function write_hdr(hdr, fileprefix)
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if isfield(hdr.hist,'magic')
save_untouch_nii_hdr(hdr, fid);
else
save_untouch0_nii_hdr(hdr, fid);
end
fclose(fid);
return % write_hdr
|
github
|
uoguelph-mlrg/vlr-master
|
pad_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/pad_nii.m
| 3,712 |
utf_8
|
0b9de8feba6840e2d8ea1ab1752747c7
|
% PAD_NII: Pad the NIfTI volume from any of the 6 sides
%
% Usage: nii = pad_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be padded from which side.
%
% option.pad_from_L = ( number of voxel )
% option.pad_from_R = ( number of voxel )
% option.pad_from_P = ( number of voxel )
% option.pad_from_A = ( number of voxel )
% option.pad_from_I = ( number of voxel )
% option.pad_from_S = ( number of voxel )
% option.bg = [0]
%
% Options description in detail:
% ==============================
%
% pad_from_L: Number of voxels from Left side will be padded.
%
% pad_from_R: Number of voxels from Right side will be padded.
%
% pad_from_P: Number of voxels from Posterior side will be padded.
%
% pad_from_A: Number of voxels from Anterior side will be padded.
%
% pad_from_I: Number of voxels from Inferior side will be padded.
%
% pad_from_S: Number of voxels from Superior side will be padded.
%
% bg: Background intensity, which is 0 by default.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = pad_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
pad_from_L = 0;
pad_from_R = 0;
pad_from_P = 0;
pad_from_A = 0;
pad_from_I = 0;
pad_from_S = 0;
bg = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'pad_from_L')
pad_from_L = round(opt.pad_from_L);
if pad_from_L >= origin(1) | pad_from_L < 0
error('pad_from_L cannot be negative');
end
end
if isfield(opt,'pad_from_P')
pad_from_P = round(opt.pad_from_P);
if pad_from_P >= origin(2) | pad_from_P < 0
error('pad_from_P cannot be negative');
end
end
if isfield(opt,'pad_from_I')
pad_from_I = round(opt.pad_from_I);
if pad_from_I >= origin(3) | pad_from_I < 0
error('pad_from_I cannot be negative');
end
end
if isfield(opt,'pad_from_R')
pad_from_R = round(opt.pad_from_R);
if pad_from_R > dims(1)-origin(1) | pad_from_R < 0
error('pad_from_R cannot be negative');
end
end
if isfield(opt,'pad_from_A')
pad_from_A = round(opt.pad_from_A);
if pad_from_A > dims(2)-origin(2) | pad_from_A < 0
error('pad_from_A cannot be negative');
end
end
if isfield(opt,'pad_from_S')
pad_from_S = round(opt.pad_from_S);
if pad_from_S > dims(3)-origin(3) | pad_from_S < 0
error('pad_from_S cannot be negative');
end
end
if isfield(opt,'bg')
bg = opt.bg;
end
end
blk = bg * ones( pad_from_L, dims(2), dims(3) );
nii.img = cat(1, blk, nii.img);
blk = bg * ones( pad_from_R, dims(2), dims(3) );
nii.img = cat(1, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), pad_from_P, dims(3) );
nii.img = cat(2, blk, nii.img);
blk = bg * ones( dims(1), pad_from_A, dims(3) );
nii.img = cat(2, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_I );
nii.img = cat(3, blk, nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_S );
nii.img = cat(3, nii.img, blk);
nii = make_nii(nii.img, nii.hdr.dime.pixdim(2:4), ...
[origin(1)+pad_from_L origin(2)+pad_from_P origin(3)+pad_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
uoguelph-mlrg/vlr-master
|
load_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_nii_hdr.m
| 10,031 |
utf_8
|
e95839e314863f7ee463cc2626dd447c
|
% internal function
% - Jimmy Shen ([email protected])
function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix)
if ~exist('fileprefix','var'),
error('Usage: [hdr, filetype, fileprefix, machine] = load_nii_hdr(filename)');
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
hdr = read_header(fid);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
hdr = read_header(fid);
fclose(fid);
end
end
end
if strcmp(hdr.hist.magic, 'n+1')
filetype = 2;
elseif strcmp(hdr.hist.magic, 'ni1')
filetype = 1;
else
filetype = 0;
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
fseek(fid,253,'bof');
hist.originator = fread(fid, 5,'int16')';
return % data_history
|
github
|
uoguelph-mlrg/vlr-master
|
save_untouch_slice.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_untouch_slice.m
| 19,683 |
utf_8
|
364468e5dbd3790c1aadf9a768534f1f
|
% Save back to the original image with a portion of slices that was
% loaded by "load_untouch_nii". You can process those slices matrix
% in any way, as long as their dimension is not altered.
%
% Usage: save_untouch_slice(slice, filename, ...
% slice_idx, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx])
%
% slice - a portion of slices that was loaded by "load_untouch_nii".
% This should be a numeric matrix (i.e. only the .img field in the
% loaded structure)
%
% filename - NIfTI or ANALYZE file name.
%
% slice_idx (depending on slice size) - a numerical array of image
% slice indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% img_idx (depending on slice size) - a numerical array of image
% volume indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim5_idx (depending on slice size) - a numerical array of 5th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim6_idx (depending on slice size) - a numerical array of 6th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim7_idx (depending on slice size) - a numerical array of 7th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% Example:
% nii = load_nii('avg152T1_LR_nifti.nii');
% save_nii(nii, 'test.nii');
% view_nii(nii);
% nii = load_untouch_nii('test.nii','','','','','',[40 51:53]);
% nii.img = ones(91,109,4)*122;
% save_untouch_slice(nii.img, 'test.nii', [40 51:52]);
% nii = load_nii('test.nii');
% view_nii(nii);
%
% - Jimmy Shen ([email protected])
%
function save_untouch_slice(slice, filename, slice_idx, img_idx, dim5_idx, dim6_idx, dim7_idx)
if ~exist('slice','var') | ~isnumeric(slice)
msg = [char(10) '"slice" argument should be a portion of slices that was loaded' char(10)];
msg = [msg 'by "load_untouch_nii.m". This should be a numeric matrix (i.e.' char(10)];
msg = [msg 'only the .img field in the loaded structure).'];
error(msg);
end
if ~exist('filename','var') | ~exist(filename,'file')
error('In order to save back, original NIfTI or ANALYZE file must exist.');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | ~isequal(size(slice,3),length(slice_idx))
msg = [char(10) '"slice_idx" is a numerical array of image slice indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
if ~isequal(size(slice,4),1)
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,4),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
if ~isequal(size(slice,5),1)
msg = [char(10) '"dim5_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,5),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
if ~isequal(size(slice,6),1)
msg = [char(10) '"dim6_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,6),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
if ~isequal(size(slice,7),1)
msg = [char(10) '"dim7_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,7),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
% rmdir(tmpDir,'s');
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
% fileprefix = nii.fileprefix;
filetype = nii.filetype;
if ~isequal( nii.hdr.dime.dim(2:3), [size(slice,1),size(slice,2)] )
msg = [char(10) 'The first two dimensions of slice matrix should be the same as' char(10)];
msg = [msg 'the first two dimensions of image loaded by "load_untouch_nii".'];
error(msg);
end
% Save the dataset body
%
save_untouch_slice_img(slice, nii.hdr, filetype, fileprefix, ...
nii.machine, slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
% gzip output file if requested
%
if exist('gzFileName', 'var')
[p,f] = fileparts(gzFileName);
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
movefile([fileprefix, '.img.gz']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
movefile([fileprefix, '.hdr.gz']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
movefile([fileprefix, '.nii.gz']);
end;
rmdir(tmpDir,'s');
end;
return % save_untouch_slice
%--------------------------------------------------------------------------
function save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx]);');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
return % save_untouch_slice_img
%---------------------------------------------------------------------
function write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
else
fid = fopen(sprintf('%s.img',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.img.',fileprefix);
error(msg);
end
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
msg = [char(10) char(10) ' "save_untouch_slice" is used to save back to the original image a' char(10)];
msg = [msg ' portion of slices that were loaded by "load_untouch_nii". You can' char(10)];
msg = [msg ' process those slices matrix in any way, as long as their dimension' char(10)];
msg = [msg ' is not changed.'];
error(msg);
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fwrite will write precision of value
% in img_siz times
%
fwrite(fid, slice(:,:,s,t,i5,i6,i7), sprintf('*%s',precision));
end
end
end
end
end
end
fclose(fid);
return % write_image
|
github
|
uoguelph-mlrg/vlr-master
|
load_nii_img.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_nii_img.m
| 12,328 |
utf_8
|
b1b9dd2838a8f217b10fefdc8a931d5e
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(5:8),ones(1,4)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
% compute size of one image
%
img_siz = prod(hdr.dime.dim(2:4));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, 1, ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 hdr.dime.dim(4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
uoguelph-mlrg/vlr-master
|
bresenham_line3d.m
|
.m
|
vlr-master/utils/nii/nifti_DL/bresenham_line3d.m
| 4,493 |
utf_8
|
c19f06df423676afeb59762ac55c0c2f
|
% Generate X Y Z coordinates of a 3D Bresenham's line between
% two given points.
%
% A very useful application of this algorithm can be found in the
% implementation of Fischer's Bresenham interpolation method in my
% another program that can rotate three dimensional image volume
% with an affine matrix:
% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21080
%
% Usage: [X Y Z] = bresenham_line3d(P1, P2, [precision]);
%
% P1 - vector for Point1, where P1 = [x1 y1 z1]
%
% P2 - vector for Point2, where P2 = [x2 y2 z2]
%
% precision (optional) - Although according to Bresenham's line
% algorithm, point coordinates x1 y1 z1 and x2 y2 z2 should
% be integer numbers, this program extends its limit to all
% real numbers. If any of them are floating numbers, you
% should specify how many digits of decimal that you would
% like to preserve. Be aware that the length of output X Y
% Z coordinates will increase in 10 times for each decimal
% digit that you want to preserve. By default, the precision
% is 0, which means that they will be rounded to the nearest
% integer.
%
% X - a set of x coordinates on Bresenham's line
%
% Y - a set of y coordinates on Bresenham's line
%
% Z - a set of z coordinates on Bresenham's line
%
% Therefore, all points in XYZ set (i.e. P(i) = [X(i) Y(i) Z(i)])
% will constitute the Bresenham's line between P1 and P1.
%
% Example:
% P1 = [12 37 6]; P2 = [46 3 35];
% [X Y Z] = bresenham_line3d(P1, P2);
% figure; plot3(X,Y,Z,'s','markerface','b');
%
% This program is ported to MATLAB from:
%
% B.Pendleton. line3d - 3D Bresenham's (a 3D line drawing algorithm)
% ftp://ftp.isc.org/pub/usenet/comp.sources.unix/volume26/line3d, 1992
%
% Which is also referenced by:
%
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [X,Y,Z] = bresenham_line3d(P1, P2, precision)
if ~exist('precision','var') | isempty(precision) | round(precision) == 0
precision = 0;
P1 = round(P1);
P2 = round(P2);
else
precision = round(precision);
P1 = round(P1*(10^precision));
P2 = round(P2*(10^precision));
end
d = max(abs(P2-P1)+1);
X = zeros(1, d);
Y = zeros(1, d);
Z = zeros(1, d);
x1 = P1(1);
y1 = P1(2);
z1 = P1(3);
x2 = P2(1);
y2 = P2(2);
z2 = P2(3);
dx = x2 - x1;
dy = y2 - y1;
dz = z2 - z1;
ax = abs(dx)*2;
ay = abs(dy)*2;
az = abs(dz)*2;
sx = sign(dx);
sy = sign(dy);
sz = sign(dz);
x = x1;
y = y1;
z = z1;
idx = 1;
if(ax>=max(ay,az)) % x dominant
yd = ay - ax/2;
zd = az - ax/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(x == x2) % end
break;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - ax;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ax;
end
x = x + sx; % move along x
yd = yd + ay;
zd = zd + az;
end
elseif(ay>=max(ax,az)) % y dominant
xd = ax - ay/2;
zd = az - ay/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(y == y2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - ay;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ay;
end
y = y + sy; % move along y
xd = xd + ax;
zd = zd + az;
end
elseif(az>=max(ax,ay)) % z dominant
xd = ax - az/2;
yd = ay - az/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(z == z2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - az;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - az;
end
z = z + sz; % move along z
xd = xd + ax;
yd = yd + ay;
end
end
if precision ~= 0
X = X/(10^precision);
Y = Y/(10^precision);
Z = Z/(10^precision);
end
return; % bresenham_line3d
|
github
|
uoguelph-mlrg/vlr-master
|
make_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/make_nii.m
| 6,849 |
utf_8
|
3c7c8b81655c111a9ce4b82086bde4f5
|
% Make NIfTI structure specified by an N-D matrix. Usually, N is 3 for
% 3D matrix [x y z], or 4 for 4D matrix with time series [x y z t].
% Optional parameters can also be included, such as: voxel_size,
% origin, datatype, and description.
%
% Once the NIfTI structure is made, it can be saved into NIfTI file
% using "save_nii" command (for more detail, type: help save_nii).
%
% Usage: nii = make_nii(img, [voxel_size], [origin], [datatype], [description])
%
% Where:
%
% img: Usually, img is a 3D matrix [x y z], or a 4D
% matrix with time series [x y z t]. However,
% NIfTI allows a maximum of 7D matrix. When the
% image is in RGB format, make sure that the size
% of 4th dimension is always 3 (i.e. [R G B]). In
% that case, make sure that you must specify RGB
% datatype, which is either 128 or 511.
%
% voxel_size (optional): Voxel size in millimeter for each
% dimension. Default is [1 1 1].
%
% origin (optional): The AC origin. Default is [0 0 0].
%
% datatype (optional): Storage data type:
% 2 - uint8, 4 - int16, 8 - int32, 16 - float32,
% 32 - complex64, 64 - float64, 128 - RGB24,
% 256 - int8, 511 - RGB96, 512 - uint16,
% 768 - uint32, 1792 - complex128
% Default will use the data type of 'img' matrix
% For RGB image, you must specify it to either 128
% or 511.
%
% description (optional): Description of data. Default is ''.
%
% e.g.:
% origin = [33 44 13]; datatype = 64;
% nii = make_nii(img, [], origin, datatype); % default voxel_size
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = make_nii(varargin)
nii.img = varargin{1};
dims = size(nii.img);
dims = [length(dims) dims ones(1,8)];
dims = dims(1:8);
voxel_size = [0 ones(1,7)];
origin = zeros(1,5);
descrip = '';
switch class(nii.img)
case 'uint8'
datatype = 2;
case 'int16'
datatype = 4;
case 'int32'
datatype = 8;
case 'single'
if isreal(nii.img)
datatype = 16;
else
datatype = 32;
end
case 'double'
if isreal(nii.img)
datatype = 64;
else
datatype = 1792;
end
case 'int8'
datatype = 256;
case 'uint16'
datatype = 512;
case 'uint32'
datatype = 768;
otherwise
error('Datatype is not supported by make_nii.');
end
if nargin > 1 & ~isempty(varargin{2})
voxel_size(2:4) = double(varargin{2});
end
if nargin > 2 & ~isempty(varargin{3})
origin(1:3) = double(varargin{3});
end
if nargin > 3 & ~isempty(varargin{4})
datatype = double(varargin{4});
if datatype == 128 | datatype == 511
dims(5) = [];
dims(1) = dims(1) - 1;
dims = [dims 1];
end
end
if nargin > 4 & ~isempty(varargin{5})
descrip = varargin{5};
end
if ndims(nii.img) > 7
error('NIfTI only allows a maximum of 7 Dimension matrix.');
end
maxval = round(double(max(nii.img(:))));
minval = round(double(min(nii.img(:))));
nii.hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval);
switch nii.hdr.dime.datatype
case 2
nii.img = uint8(nii.img);
case 4
nii.img = int16(nii.img);
case 8
nii.img = int32(nii.img);
case 16
nii.img = single(nii.img);
case 32
nii.img = single(nii.img);
case 64
nii.img = double(nii.img);
case 128
nii.img = uint8(nii.img);
case 256
nii.img = int8(nii.img);
case 511
img = double(nii.img(:));
img = single((img - min(img))/(max(img) - min(img)));
nii.img = reshape(img, size(nii.img));
nii.hdr.dime.glmax = double(max(img));
nii.hdr.dime.glmin = double(min(img));
case 512
nii.img = uint16(nii.img);
case 768
nii.img = uint32(nii.img);
case 1792
nii.img = double(nii.img);
otherwise
error('Datatype is not supported by make_nii.');
end
return; % make_nii
%---------------------------------------------------------------------
function hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval)
hdr.hk = header_key;
hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);
hdr.hist = data_history(origin, descrip);
return; % make_header
%---------------------------------------------------------------------
function hk = header_key
hk.sizeof_hdr = 348; % must be 348!
hk.data_type = '';
hk.db_name = '';
hk.extents = 0;
hk.session_error = 0;
hk.regular = 'r';
hk.dim_info = 0;
return; % header_key
%---------------------------------------------------------------------
function dime = image_dimension(dims, voxel_size, datatype, maxval, minval)
dime.dim = dims;
dime.intent_p1 = 0;
dime.intent_p2 = 0;
dime.intent_p3 = 0;
dime.intent_code = 0;
dime.datatype = datatype;
switch dime.datatype
case 2,
dime.bitpix = 8; precision = 'uint8';
case 4,
dime.bitpix = 16; precision = 'int16';
case 8,
dime.bitpix = 32; precision = 'int32';
case 16,
dime.bitpix = 32; precision = 'float32';
case 32,
dime.bitpix = 64; precision = 'float32';
case 64,
dime.bitpix = 64; precision = 'float64';
case 128
dime.bitpix = 24; precision = 'uint8';
case 256
dime.bitpix = 8; precision = 'int8';
case 511
dime.bitpix = 96; precision = 'float32';
case 512
dime.bitpix = 16; precision = 'uint16';
case 768
dime.bitpix = 32; precision = 'uint32';
case 1792,
dime.bitpix = 128; precision = 'float64';
otherwise
error('Datatype is not supported by make_nii.');
end
dime.slice_start = 0;
dime.pixdim = voxel_size;
dime.vox_offset = 0;
dime.scl_slope = 0;
dime.scl_inter = 0;
dime.slice_end = 0;
dime.slice_code = 0;
dime.xyzt_units = 0;
dime.cal_max = 0;
dime.cal_min = 0;
dime.slice_duration = 0;
dime.toffset = 0;
dime.glmax = maxval;
dime.glmin = minval;
return; % image_dimension
%---------------------------------------------------------------------
function hist = data_history(origin, descrip)
hist.descrip = descrip;
hist.aux_file = 'none';
hist.qform_code = 0;
hist.sform_code = 0;
hist.quatern_b = 0;
hist.quatern_c = 0;
hist.quatern_d = 0;
hist.qoffset_x = 0;
hist.qoffset_y = 0;
hist.qoffset_z = 0;
hist.srow_x = zeros(1,4);
hist.srow_y = zeros(1,4);
hist.srow_z = zeros(1,4);
hist.intent_name = '';
hist.magic = '';
hist.originator = origin;
return; % data_history
|
github
|
uoguelph-mlrg/vlr-master
|
verify_nii_ext.m
|
.m
|
vlr-master/utils/nii/nifti_DL/verify_nii_ext.m
| 1,676 |
utf_8
|
db3d32ecba688905185f5ed01b409fd1
|
% Verify NIFTI header extension to make sure that each extension section
% must be an integer multiple of 16 byte long that includes the first 8
% bytes of esize and ecode. If the length of extension section is not the
% above mentioned case, edata should be padded with all 0.
%
% Usage: [ext, esize_total] = verify_nii_ext(ext)
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% esize_total - Sum of all esize variable in all header sections.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ext, esize_total] = verify_nii_ext(ext)
if ~isfield(ext, 'section')
error('Incorrect NIFTI header extension structure.');
elseif ~isfield(ext, 'num_ext')
ext.num_ext = length(ext.section);
elseif ~isfield(ext, 'extension')
ext.extension = [1 0 0 0];
end
esize_total = 0;
for i=1:ext.num_ext
if ~isfield(ext.section(i), 'ecode') | ~isfield(ext.section(i), 'edata')
error('Incorrect NIFTI header extension structure.');
end
ext.section(i).esize = ceil((length(ext.section(i).edata)+8)/16)*16;
ext.section(i).edata = ...
[ext.section(i).edata ...
zeros(1,ext.section(i).esize-length(ext.section(i).edata)-8)];
esize_total = esize_total + ext.section(i).esize;
end
return % verify_nii_ext
|
github
|
uoguelph-mlrg/vlr-master
|
get_nii_frame.m
|
.m
|
vlr-master/utils/nii/nifti_DL/get_nii_frame.m
| 4,333 |
utf_8
|
8b0cba9d07733a6f82753b0c40b51107
|
% Return time frame of a NIFTI dataset. Support both *.nii and
% *.hdr/*.img file extension. If file extension is not provided,
% *.hdr/*.img will be used as default.
%
% It is a lightweighted "load_nii_hdr", and is equivalent to
% hdr.dime.dim(5)
%
% Usage: [ total_scan ] = get_nii_frame(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% total_scan - total number of image scans for the time frame
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ total_scan ] = get_nii_frame(filename)
if ~exist('filename','var'),
error('Usage: [ total_scan ] = get_nii_frame(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
fileprefix = filename;
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
if hdr.sizeof_hdr ~= 348
% first try reading the opposite endian to 'machine'
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
end
if hdr.sizeof_hdr ~= 348
% Now throw an error
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
total_scan = hdr.dim(5);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return; % get_nii_frame
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
fseek(fid,0,'bof');
dsr.sizeof_hdr = fread(fid,1,'int32')'; % should be 348!
fseek(fid,40,'bof');
dsr.dim = fread(fid,8,'int16')';
return; % read_header
|
github
|
uoguelph-mlrg/vlr-master
|
flip_lr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/flip_lr.m
| 3,484 |
utf_8
|
a0b2d0189d90339a841863efeb60681a
|
% When you load any ANALYZE or NIfTI file with 'load_nii.m', and view
% it with 'view_nii.m', you may find that the image is L-R flipped.
% This is because of the confusion of radiological and neurological
% convention in the medical image before NIfTI format is adopted. You
% can find more details from:
%
% http://www.rotman-baycrest.on.ca/~jimmy/UseANALYZE.htm
%
% Sometime, people even want to convert RAS (standard orientation) back
% to LAS orientation to satisfy the legend programs or processes. This
% program is only written for those purpose. So PLEASE BE VERY CAUTIOUS
% WHEN USING THIS 'FLIP_LR.M' PROGRAM.
%
% With 'flip_lr.m', you can convert any ANALYZE or NIfTI (no matter
% 3D or 4D) file to a flipped NIfTI file. This is implemented simply
% by flipping the affine matrix in the NIfTI header. Since the L-R
% orientation is determined there, so the image will be flipped.
%
% Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance],[preferredForm])
%
% original_fn - filename of the original ANALYZE or NIfTI (3D or 4D) file
%
% flipped_fn - filename of the L-R flipped NIfTI file
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed for non-orthogonal rotation
% or shearing in NIfTI affine matrix. It will be set to 0.1 (10%),
% if it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Example: flip_lr('avg152T1_LR_nifti.nii', 'flipped_lr.nii');
% flip_lr('avg152T1_RL_nifti.nii', 'flipped_rl.nii');
%
% You will find that 'avg152T1_LR_nifti.nii' and 'avg152T1_RL_nifti.nii'
% are the same, and 'flipped_lr.nii' and 'flipped_rl.nii' are also the
% the same, but they are L-R flipped from 'avg152T1_*'.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function flip_lr(original_fn, flipped_fn, old_RGB, tolerance, preferredForm)
if ~exist('original_fn','var') | ~exist('flipped_fn','var')
error('Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance])');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
nii = load_nii(original_fn, [], [], [], [], old_RGB, tolerance, preferredForm);
M = diag(nii.hdr.dime.pixdim(2:5));
M(1:3,4) = -M(1:3,1:3)*(nii.hdr.hist.originator(1:3)-1)';
M(1,:) = -1*M(1,:);
nii.hdr.hist.sform_code = 1;
nii.hdr.hist.srow_x = M(1,:);
nii.hdr.hist.srow_y = M(2,:);
nii.hdr.hist.srow_z = M(3,:);
save_nii(nii, flipped_fn);
return; % flip_lr
|
github
|
uoguelph-mlrg/vlr-master
|
save_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_nii.m
| 9,404 |
utf_8
|
88aa93174482539fe993ac335fb01541
|
% Save NIFTI dataset. Support both *.nii and *.hdr/*.img file extension.
% If file extension is not provided, *.hdr/*.img will be used as default.
%
% Usage: save_nii(nii, filename, [old_RGB])
%
% nii.hdr - struct with NIFTI header fields (from load_nii.m or make_nii.m)
%
% nii.img - 3D (or 4D) matrix of NIFTI data.
%
% filename - NIFTI file name.
%
% old_RGB - an optional boolean variable to handle special RGB data
% sequence [R1 R2 ... G1 G2 ... B1 B2 ...] that is used only by
% AnalyzeDirect (Analyze Software). Since both NIfTI and Analyze
% file format use RGB triple [R1 G1 B1 R2 G2 B2 ...] sequentially
% for each voxel, this variable is set to FALSE by default. If you
% would like the saved image only to be opened by AnalyzeDirect
% Software, set old_RGB to TRUE (or 1). It will be set to 0, if it
% is default or empty.
%
% Tip: to change the data type, set nii.hdr.dime.datatype,
% and nii.hdr.dime.bitpix to:
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
% - "old_RGB" related codes in "save_nii.m" are added by Mike Harms (2006.06.28)
%
function save_nii(nii, fileprefix, old_RGB)
if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
~isfield(nii,'img') | ~exist('fileprefix','var') | isempty(fileprefix)
error('Usage: save_nii(nii, filename, [old_RGB])');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''save_untouch_nii.m'' for the untouched structure.');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(fileprefix) > 2 & strcmp(fileprefix(end-2:end), '.gz')
if ~strcmp(fileprefix(end-6:end), '.img.gz') & ...
~strcmp(fileprefix(end-6:end), '.hdr.gz') & ...
~strcmp(fileprefix(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
fileprefix = fileprefix(1:end-3);
end
end
filetype = 1;
% Note: fileprefix is actually the filename you want to save
%
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
filetype = 2;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
write_nii(nii, filetype, fileprefix, old_RGB);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
if filetype == 1
% So earlier versions of SPM can also open it with correct originator
%
M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
save([fileprefix '.mat'], 'M');
end
return % save_nii
%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix, old_RGB)
hdr = nii.hdr;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 511,
hdr.dime.bitpix = int16(96); precision = 'float32';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.glmax = round(double(max(nii.img(:))));
hdr.dime.glmin = round(double(min(nii.img(:))));
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
ScanDim = double(hdr.dime.dim(5)); % t
SliceDim = double(hdr.dime.dim(4)); % z
RowDim = double(hdr.dime.dim(3)); % y
PixelDim = double(hdr.dime.dim(2)); % x
SliceSz = double(hdr.dime.pixdim(4));
RowSz = double(hdr.dime.pixdim(3));
PixelSz = double(hdr.dime.pixdim(2));
x = 1:PixelDim;
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
if double(hdr.dime.datatype) == 511
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
fwrite(fid, nii.img, precision);
% fwrite(fid, nii.img, precision, skip_bytes); % error using skip
fclose(fid);
return; % write_nii
|
github
|
uoguelph-mlrg/vlr-master
|
rri_file_menu.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_file_menu.m
| 3,974 |
utf_8
|
1ec91620ceb4108dde9a63945380028f
|
% Imbed a file menu to any figure. If file menu exist, it will append
% to the existing file menu. This file menu includes: Copy to clipboard,
% print, save, close etc.
%
% Usage: rri_file_menu(fig);
%
% rri_file_menu(fig,0) means no 'Close' menu.
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function rri_file_menu(action, varargin)
if isnumeric(action)
fig = action;
action = 'init';
end
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
if ~strcmp(action, 'init')
set(gcbf, 'InvertHardcopy','off');
% set(gcbf, 'PaperPositionMode','auto');
end
switch action
case {'init'}
if nargin > 1
init(fig, 1); % no 'close' menu
else
init(fig, 0);
end
case {'print_fig'}
printdlg(gcbf);
case {'copy_fig'}
copy_fig;
case {'export_fig'}
export_fig;
end
return % rri_file_menu
%------------------------------------------------
%
% Create (or append) File menu
%
function init(fig, no_close)
% search for file menu
%
h_file = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
h_file = menuitems(i);
break;
end
end
set(fig, 'menubar', 'none');
if isempty(h_file)
if isempty(menuitems)
h_file = uimenu('parent', fig, 'label', 'File');
else
h_file = uimenu('parent', fig, 'label', 'Copy Figure');
end
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'label','Copy to Clipboard');
else
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'separator','on', ...
'label','Copy to Clipboard');
end
h2 = uimenu(h_file, ...
'callback','pagesetupdlg(gcbf);', ...
'label','Page Setup...');
h2 = uimenu(h_file, ...
'callback','printpreview(gcbf);', ...
'label','Print Preview...');
h2 = uimenu('parent', h_file, ...
'callback','printdlg(gcbf);', ...
'label','Print Figure ...');
h2 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''export_fig'');', ...
'label','Save Figure ...');
arch = computer;
if ~strcmpi(arch(1:2),'PC')
set(h1, 'enable', 'off');
end
if ~no_close
h1 = uimenu('parent', h_file, ...
'callback','close(gcbf);', ...
'separator','on', ...
'label','Close');
end
return; % init
%------------------------------------------------
%
% Copy to clipboard
%
function copy_fig
arch = computer;
if(~strcmpi(arch(1:2),'PC'))
error('copy to clipboard can only be used under MS Windows');
return;
end
print -noui -dbitmap;
return % copy_fig
%------------------------------------------------
%
% Save as an image file
%
function export_fig
curr = pwd;
if isempty(curr)
curr = filesep;
end
[selected_file, selected_path] = rri_select_file(curr,'Save As');
if isempty(selected_file) | isempty(selected_path)
return;
end
filename = [selected_path selected_file];
if(exist(filename,'file')==2) % file exist
dlg_title = 'Confirm File Overwrite';
msg = ['File ',filename,' exist. Are you sure you want to overwrite it?'];
response = questdlg(msg,dlg_title,'Yes','No','Yes');
if(strcmp(response,'No'))
return;
end
end
old_pointer = get(gcbf,'pointer');
set(gcbf,'pointer','watch');
try
saveas(gcbf,filename);
catch
msg = 'ERROR: Cannot save file';
set(findobj(gcf,'Tag','MessageLine'),'String',msg);
end
set(gcbf,'pointer',old_pointer);
return; % export_fig
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.